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/MCSymbolXCOFF.h"
78 #include "llvm/Support/AtomicOrdering.h"
79 #include "llvm/Support/BranchProbability.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/CodeGen.h"
82 #include "llvm/Support/CommandLine.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/KnownBits.h"
88 #include "llvm/Support/MachineValueType.h"
89 #include "llvm/Support/MathExtras.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Target/TargetMachine.h"
92 #include "llvm/Target/TargetOptions.h"
93 #include <algorithm>
94 #include <cassert>
95 #include <cstdint>
96 #include <iterator>
97 #include <list>
98 #include <utility>
99 #include <vector>
100 
101 using namespace llvm;
102 
103 #define DEBUG_TYPE "ppc-lowering"
104 
105 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
106 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
109 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
112 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
113 
114 static cl::opt<bool> DisableSCO("disable-ppc-sco",
115 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
116 
117 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
118 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
119 
120 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
121 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
122 
123 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
124 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
125 
126 STATISTIC(NumTailCalls, "Number of tail calls");
127 STATISTIC(NumSiblingCalls, "Number of sibling calls");
128 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
129 
130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
131 
132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
133 
134 // FIXME: Remove this once the bug has been fixed!
135 extern cl::opt<bool> ANDIGlueBug;
136 
137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
138                                      const PPCSubtarget &STI)
139     : TargetLowering(TM), Subtarget(STI) {
140   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
141   // arguments are at least 4/8 bytes aligned.
142   bool isPPC64 = Subtarget.isPPC64();
143   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
144 
145   // Set up the register classes.
146   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
147   if (!useSoftFloat()) {
148     if (hasSPE()) {
149       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
150       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
151     } else {
152       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
153       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
154     }
155   }
156 
157   // Match BITREVERSE to customized fast code sequence in the td file.
158   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
159   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
160 
161   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
162   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
163 
164   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
165   for (MVT VT : MVT::integer_valuetypes()) {
166     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
167     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
168   }
169 
170   if (Subtarget.isISA3_0()) {
171     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
172     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
173     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
174     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
175   } else {
176     // No extending loads from f16 or HW conversions back and forth.
177     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
178     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
179     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
180     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
181     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
182     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
183     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
184     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
185   }
186 
187   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
188 
189   // PowerPC has pre-inc load and store's.
190   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
191   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
192   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
193   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
195   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
196   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
197   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
198   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
200   if (!Subtarget.hasSPE()) {
201     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
202     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
203     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
204     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
205   }
206 
207   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
208   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
209   for (MVT VT : ScalarIntVTs) {
210     setOperationAction(ISD::ADDC, VT, Legal);
211     setOperationAction(ISD::ADDE, VT, Legal);
212     setOperationAction(ISD::SUBC, VT, Legal);
213     setOperationAction(ISD::SUBE, VT, Legal);
214   }
215 
216   if (Subtarget.useCRBits()) {
217     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
218 
219     if (isPPC64 || Subtarget.hasFPCVT()) {
220       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
221       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
222                          isPPC64 ? MVT::i64 : MVT::i32);
223       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
224       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
225                         isPPC64 ? MVT::i64 : MVT::i32);
226     } else {
227       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
228       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
229     }
230 
231     // PowerPC does not support direct load/store of condition registers.
232     setOperationAction(ISD::LOAD, MVT::i1, Custom);
233     setOperationAction(ISD::STORE, MVT::i1, Custom);
234 
235     // FIXME: Remove this once the ANDI glue bug is fixed:
236     if (ANDIGlueBug)
237       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
238 
239     for (MVT VT : MVT::integer_valuetypes()) {
240       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
241       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
242       setTruncStoreAction(VT, MVT::i1, Expand);
243     }
244 
245     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
246   }
247 
248   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
249   // PPC (the libcall is not available).
250   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
251   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
252 
253   // We do not currently implement these libm ops for PowerPC.
254   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
255   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
256   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
257   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
258   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
259   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
260 
261   // PowerPC has no SREM/UREM instructions unless we are on P9
262   // On P9 we may use a hardware instruction to compute the remainder.
263   // The instructions are not legalized directly because in the cases where the
264   // result of both the remainder and the division is required it is more
265   // efficient to compute the remainder from the result of the division rather
266   // than use the remainder instruction.
267   if (Subtarget.isISA3_0()) {
268     setOperationAction(ISD::SREM, MVT::i32, Custom);
269     setOperationAction(ISD::UREM, MVT::i32, Custom);
270     setOperationAction(ISD::SREM, MVT::i64, Custom);
271     setOperationAction(ISD::UREM, MVT::i64, Custom);
272   } else {
273     setOperationAction(ISD::SREM, MVT::i32, Expand);
274     setOperationAction(ISD::UREM, MVT::i32, Expand);
275     setOperationAction(ISD::SREM, MVT::i64, Expand);
276     setOperationAction(ISD::UREM, MVT::i64, Expand);
277   }
278 
279   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
280   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
281   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
282   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
283   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
284   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
285   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
287   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
288 
289   // Handle constrained floating-point operations of scalar.
290   // TODO: Handle SPE specific operation.
291   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
292   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
293   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
294   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
295   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
296   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
297 
298   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
299   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
300   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
301   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
302   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
303   if (Subtarget.hasVSX())
304     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal);
305 
306   if (Subtarget.hasFSQRT()) {
307     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
308     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
309   }
310 
311   if (Subtarget.hasFPRND()) {
312     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
313     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
314     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
315     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
316 
317     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
318     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
319     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
320     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
321   }
322 
323   // We don't support sin/cos/sqrt/fmod/pow
324   setOperationAction(ISD::FSIN , MVT::f64, Expand);
325   setOperationAction(ISD::FCOS , MVT::f64, Expand);
326   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
327   setOperationAction(ISD::FREM , MVT::f64, Expand);
328   setOperationAction(ISD::FPOW , MVT::f64, Expand);
329   setOperationAction(ISD::FSIN , MVT::f32, Expand);
330   setOperationAction(ISD::FCOS , MVT::f32, Expand);
331   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
332   setOperationAction(ISD::FREM , MVT::f32, Expand);
333   setOperationAction(ISD::FPOW , MVT::f32, Expand);
334   if (Subtarget.hasSPE()) {
335     setOperationAction(ISD::FMA  , MVT::f64, Expand);
336     setOperationAction(ISD::FMA  , MVT::f32, Expand);
337   } else {
338     setOperationAction(ISD::FMA  , MVT::f64, Legal);
339     setOperationAction(ISD::FMA  , MVT::f32, Legal);
340   }
341 
342   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
343 
344   // If we're enabling GP optimizations, use hardware square root
345   if (!Subtarget.hasFSQRT() &&
346       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
347         Subtarget.hasFRE()))
348     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
349 
350   if (!Subtarget.hasFSQRT() &&
351       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
352         Subtarget.hasFRES()))
353     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
354 
355   if (Subtarget.hasFCPSGN()) {
356     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
357     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
358   } else {
359     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
360     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
361   }
362 
363   if (Subtarget.hasFPRND()) {
364     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
365     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
366     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
367     setOperationAction(ISD::FROUND, MVT::f64, Legal);
368 
369     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
370     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
371     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
372     setOperationAction(ISD::FROUND, MVT::f32, Legal);
373   }
374 
375   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
376   // to speed up scalar BSWAP64.
377   // CTPOP or CTTZ were introduced in P8/P9 respectively
378   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
379   if (Subtarget.hasP9Vector())
380     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
381   else
382     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
383   if (Subtarget.isISA3_0()) {
384     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
385     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
386   } else {
387     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
388     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
389   }
390 
391   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
392     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
393     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
394   } else {
395     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
396     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
397   }
398 
399   // PowerPC does not have ROTR
400   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
401   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
402 
403   if (!Subtarget.useCRBits()) {
404     // PowerPC does not have Select
405     setOperationAction(ISD::SELECT, MVT::i32, Expand);
406     setOperationAction(ISD::SELECT, MVT::i64, Expand);
407     setOperationAction(ISD::SELECT, MVT::f32, Expand);
408     setOperationAction(ISD::SELECT, MVT::f64, Expand);
409   }
410 
411   // PowerPC wants to turn select_cc of FP into fsel when possible.
412   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
413   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
414 
415   // PowerPC wants to optimize integer setcc a bit
416   if (!Subtarget.useCRBits())
417     setOperationAction(ISD::SETCC, MVT::i32, Custom);
418 
419   // PowerPC does not have BRCOND which requires SetCC
420   if (!Subtarget.useCRBits())
421     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
422 
423   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
424 
425   if (Subtarget.hasSPE()) {
426     // SPE has built-in conversions
427     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
428     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
429     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
430   } else {
431     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
432     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
433 
434     // PowerPC does not have [U|S]INT_TO_FP
435     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
436     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
437   }
438 
439   if (Subtarget.hasDirectMove() && isPPC64) {
440     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
441     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
442     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
443     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
444     if (TM.Options.UnsafeFPMath) {
445       setOperationAction(ISD::LRINT, MVT::f64, Legal);
446       setOperationAction(ISD::LRINT, MVT::f32, Legal);
447       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
448       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
449       setOperationAction(ISD::LROUND, MVT::f64, Legal);
450       setOperationAction(ISD::LROUND, MVT::f32, Legal);
451       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
452       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
453     }
454   } else {
455     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
456     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
457     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
458     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
459   }
460 
461   // We cannot sextinreg(i1).  Expand to shifts.
462   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
463 
464   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
465   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
466   // support continuation, user-level threading, and etc.. As a result, no
467   // other SjLj exception interfaces are implemented and please don't build
468   // your own exception handling based on them.
469   // LLVM/Clang supports zero-cost DWARF exception handling.
470   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
471   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
472 
473   // We want to legalize GlobalAddress and ConstantPool nodes into the
474   // appropriate instructions to materialize the address.
475   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
476   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
477   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
478   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
479   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
480   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
481   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
482   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
483   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
484   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
485 
486   // TRAP is legal.
487   setOperationAction(ISD::TRAP, MVT::Other, Legal);
488 
489   // TRAMPOLINE is custom lowered.
490   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
491   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
492 
493   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
494   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
495 
496   if (Subtarget.is64BitELFABI()) {
497     // VAARG always uses double-word chunks, so promote anything smaller.
498     setOperationAction(ISD::VAARG, MVT::i1, Promote);
499     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
500     setOperationAction(ISD::VAARG, MVT::i8, Promote);
501     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
502     setOperationAction(ISD::VAARG, MVT::i16, Promote);
503     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
504     setOperationAction(ISD::VAARG, MVT::i32, Promote);
505     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
506     setOperationAction(ISD::VAARG, MVT::Other, Expand);
507   } else if (Subtarget.is32BitELFABI()) {
508     // VAARG is custom lowered with the 32-bit SVR4 ABI.
509     setOperationAction(ISD::VAARG, MVT::Other, Custom);
510     setOperationAction(ISD::VAARG, MVT::i64, Custom);
511   } else
512     setOperationAction(ISD::VAARG, MVT::Other, Expand);
513 
514   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
515   if (Subtarget.is32BitELFABI())
516     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
517   else
518     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
519 
520   // Use the default implementation.
521   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
522   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
523   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
524   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
525   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
526   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
527   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
528   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
529   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
530 
531   // We want to custom lower some of our intrinsics.
532   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
533 
534   // To handle counter-based loop conditions.
535   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
536 
537   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
538   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
539   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
540   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
541 
542   // Comparisons that require checking two conditions.
543   if (Subtarget.hasSPE()) {
544     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
545     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
546     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
547     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
548   }
549   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
550   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
551   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
552   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
553   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
554   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
555   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
556   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
557   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
558   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
559   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
560   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
561 
562   if (Subtarget.has64BitSupport()) {
563     // They also have instructions for converting between i64 and fp.
564     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
565     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
566     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
567     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
568     // This is just the low 32 bits of a (signed) fp->i64 conversion.
569     // We cannot do this with Promote because i64 is not a legal type.
570     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
571 
572     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
573       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
574   } else {
575     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
576     if (Subtarget.hasSPE())
577       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
578     else
579       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
580   }
581 
582   // With the instructions enabled under FPCVT, we can do everything.
583   if (Subtarget.hasFPCVT()) {
584     if (Subtarget.has64BitSupport()) {
585       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
586       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
587       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
588       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
589     }
590 
591     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
592     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
593     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
594     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
595   }
596 
597   if (Subtarget.use64BitRegs()) {
598     // 64-bit PowerPC implementations can support i64 types directly
599     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
600     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
601     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
602     // 64-bit PowerPC wants to expand i128 shifts itself.
603     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
604     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
605     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
606   } else {
607     // 32-bit PowerPC wants to expand i64 shifts itself.
608     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
609     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
610     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
611   }
612 
613   if (Subtarget.hasVSX()) {
614     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
615     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
616     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
617     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
618   }
619 
620   if (Subtarget.hasAltivec()) {
621     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
622       setOperationAction(ISD::SADDSAT, VT, Legal);
623       setOperationAction(ISD::SSUBSAT, VT, Legal);
624       setOperationAction(ISD::UADDSAT, VT, Legal);
625       setOperationAction(ISD::USUBSAT, VT, Legal);
626     }
627     // First set operation action for all vector types to expand. Then we
628     // will selectively turn on ones that can be effectively codegen'd.
629     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
630       // add/sub are legal for all supported vector VT's.
631       setOperationAction(ISD::ADD, VT, Legal);
632       setOperationAction(ISD::SUB, VT, Legal);
633 
634       // For v2i64, these are only valid with P8Vector. This is corrected after
635       // the loop.
636       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
637         setOperationAction(ISD::SMAX, VT, Legal);
638         setOperationAction(ISD::SMIN, VT, Legal);
639         setOperationAction(ISD::UMAX, VT, Legal);
640         setOperationAction(ISD::UMIN, VT, Legal);
641       }
642       else {
643         setOperationAction(ISD::SMAX, VT, Expand);
644         setOperationAction(ISD::SMIN, VT, Expand);
645         setOperationAction(ISD::UMAX, VT, Expand);
646         setOperationAction(ISD::UMIN, VT, Expand);
647       }
648 
649       if (Subtarget.hasVSX()) {
650         setOperationAction(ISD::FMAXNUM, VT, Legal);
651         setOperationAction(ISD::FMINNUM, VT, Legal);
652       }
653 
654       // Vector instructions introduced in P8
655       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
656         setOperationAction(ISD::CTPOP, VT, Legal);
657         setOperationAction(ISD::CTLZ, VT, Legal);
658       }
659       else {
660         setOperationAction(ISD::CTPOP, VT, Expand);
661         setOperationAction(ISD::CTLZ, VT, Expand);
662       }
663 
664       // Vector instructions introduced in P9
665       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
666         setOperationAction(ISD::CTTZ, VT, Legal);
667       else
668         setOperationAction(ISD::CTTZ, VT, Expand);
669 
670       // We promote all shuffles to v16i8.
671       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
672       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
673 
674       // We promote all non-typed operations to v4i32.
675       setOperationAction(ISD::AND   , VT, Promote);
676       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
677       setOperationAction(ISD::OR    , VT, Promote);
678       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
679       setOperationAction(ISD::XOR   , VT, Promote);
680       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
681       setOperationAction(ISD::LOAD  , VT, Promote);
682       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
683       setOperationAction(ISD::SELECT, VT, Promote);
684       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
685       setOperationAction(ISD::VSELECT, VT, Legal);
686       setOperationAction(ISD::SELECT_CC, VT, Promote);
687       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
688       setOperationAction(ISD::STORE, VT, Promote);
689       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
690 
691       // No other operations are legal.
692       setOperationAction(ISD::MUL , VT, Expand);
693       setOperationAction(ISD::SDIV, VT, Expand);
694       setOperationAction(ISD::SREM, VT, Expand);
695       setOperationAction(ISD::UDIV, VT, Expand);
696       setOperationAction(ISD::UREM, VT, Expand);
697       setOperationAction(ISD::FDIV, VT, Expand);
698       setOperationAction(ISD::FREM, VT, Expand);
699       setOperationAction(ISD::FNEG, VT, Expand);
700       setOperationAction(ISD::FSQRT, VT, Expand);
701       setOperationAction(ISD::FLOG, VT, Expand);
702       setOperationAction(ISD::FLOG10, VT, Expand);
703       setOperationAction(ISD::FLOG2, VT, Expand);
704       setOperationAction(ISD::FEXP, VT, Expand);
705       setOperationAction(ISD::FEXP2, VT, Expand);
706       setOperationAction(ISD::FSIN, VT, Expand);
707       setOperationAction(ISD::FCOS, VT, Expand);
708       setOperationAction(ISD::FABS, VT, Expand);
709       setOperationAction(ISD::FFLOOR, VT, Expand);
710       setOperationAction(ISD::FCEIL,  VT, Expand);
711       setOperationAction(ISD::FTRUNC, VT, Expand);
712       setOperationAction(ISD::FRINT,  VT, Expand);
713       setOperationAction(ISD::FNEARBYINT, VT, Expand);
714       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
715       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
716       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
717       setOperationAction(ISD::MULHU, VT, Expand);
718       setOperationAction(ISD::MULHS, VT, Expand);
719       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
720       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
721       setOperationAction(ISD::UDIVREM, VT, Expand);
722       setOperationAction(ISD::SDIVREM, VT, Expand);
723       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
724       setOperationAction(ISD::FPOW, VT, Expand);
725       setOperationAction(ISD::BSWAP, VT, Expand);
726       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
727       setOperationAction(ISD::ROTL, VT, Expand);
728       setOperationAction(ISD::ROTR, VT, Expand);
729 
730       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
731         setTruncStoreAction(VT, InnerVT, Expand);
732         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
733         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
734         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
735       }
736     }
737     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
738     if (!Subtarget.hasP8Vector()) {
739       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
740       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
741       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
742       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
743     }
744 
745     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
746       setOperationAction(ISD::ABS, VT, Custom);
747 
748     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
749     // with merges, splats, etc.
750     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
751 
752     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
753     // are cheap, so handle them before they get expanded to scalar.
754     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
755     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
756     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
757     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
758     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
759 
760     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
761     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
762     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
763     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
764     setOperationAction(ISD::SELECT, MVT::v4i32,
765                        Subtarget.useCRBits() ? Legal : Expand);
766     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
767     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
768     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
769     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
770     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
771     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
772     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
773     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
774     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
775 
776     // Without hasP8Altivec set, v2i64 SMAX isn't available.
777     // But ABS custom lowering requires SMAX support.
778     if (!Subtarget.hasP8Altivec())
779       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
780 
781     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
782     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
783     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
784     if (Subtarget.hasAltivec())
785       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
786         setOperationAction(ISD::ROTL, VT, Legal);
787     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
788     if (Subtarget.hasP8Altivec())
789       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
790 
791     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
792     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
793     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
794     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
795 
796     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
797     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
798 
799     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
800       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
801       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
802     }
803 
804     if (Subtarget.hasP8Altivec())
805       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
806     else
807       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
808 
809     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
810     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
811 
812     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
813     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
814 
815     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
816     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
817     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
818     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
819 
820     // Altivec does not contain unordered floating-point compare instructions
821     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
822     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
823     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
824     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
825 
826     if (Subtarget.hasVSX()) {
827       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
828       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
829       if (Subtarget.hasP8Vector()) {
830         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
831         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
832       }
833       if (Subtarget.hasDirectMove() && isPPC64) {
834         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
835         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
836         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
837         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
838         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
839         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
840         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
841         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
842       }
843       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
844 
845       // The nearbyint variants are not allowed to raise the inexact exception
846       // so we can only code-gen them with unsafe math.
847       if (TM.Options.UnsafeFPMath) {
848         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
849         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
850       }
851 
852       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
853       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
854       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
855       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
856       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
857       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
858       setOperationAction(ISD::FROUND, MVT::f64, Legal);
859       setOperationAction(ISD::FRINT, MVT::f64, Legal);
860 
861       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
862       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
863       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
864       setOperationAction(ISD::FROUND, MVT::f32, Legal);
865       setOperationAction(ISD::FRINT, MVT::f32, Legal);
866 
867       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
868       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
869 
870       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
871       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
872 
873       // Share the Altivec comparison restrictions.
874       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
875       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
876       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
877       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
878 
879       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
880       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
881 
882       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
883 
884       if (Subtarget.hasP8Vector())
885         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
886 
887       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
888 
889       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
890       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
891       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
892 
893       if (Subtarget.hasP8Altivec()) {
894         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
895         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
896         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
897 
898         // 128 bit shifts can be accomplished via 3 instructions for SHL and
899         // SRL, but not for SRA because of the instructions available:
900         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
901         // doing
902         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
903         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
904         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
905 
906         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
907       }
908       else {
909         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
910         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
911         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
912 
913         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
914 
915         // VSX v2i64 only supports non-arithmetic operations.
916         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
917         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
918       }
919 
920       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
921       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
922       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
923       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
924 
925       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
926 
927       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
928       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
929       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
930       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
931 
932       // Custom handling for partial vectors of integers converted to
933       // floating point. We already have optimal handling for v2i32 through
934       // the DAG combine, so those aren't necessary.
935       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
936       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
937       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
938       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
939       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
940       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
941       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
942       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
943 
944       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
945       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
946       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
947       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
948       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
949       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
950 
951       if (Subtarget.hasDirectMove())
952         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
953       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
954 
955       // Handle constrained floating-point operations of vector.
956       // The predictor is `hasVSX` because altivec instruction has
957       // no exception but VSX vector instruction has.
958       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
959       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
960       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
961       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
962       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
963       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
964       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
965       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
966       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
967       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
968       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
969       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
970       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
971 
972       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
973       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
974       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
975       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
976       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
977       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
978       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
979       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
980       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
981       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
982       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
983       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
984       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
985 
986       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
987     }
988 
989     if (Subtarget.hasP8Altivec()) {
990       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
991       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
992     }
993 
994     if (Subtarget.hasP9Vector()) {
995       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
996       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
997 
998       // 128 bit shifts can be accomplished via 3 instructions for SHL and
999       // SRL, but not for SRA because of the instructions available:
1000       // VS{RL} and VS{RL}O.
1001       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1002       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1003       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1004 
1005       if (EnableQuadPrecision) {
1006         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1007         setOperationAction(ISD::FADD, MVT::f128, Legal);
1008         setOperationAction(ISD::FSUB, MVT::f128, Legal);
1009         setOperationAction(ISD::FDIV, MVT::f128, Legal);
1010         setOperationAction(ISD::FMUL, MVT::f128, Legal);
1011         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1012         // No extending loads to f128 on PPC.
1013         for (MVT FPT : MVT::fp_valuetypes())
1014           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1015         setOperationAction(ISD::FMA, MVT::f128, Legal);
1016         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1017         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1018         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1019         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1020         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1021         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1022 
1023         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1024         setOperationAction(ISD::FRINT, MVT::f128, Legal);
1025         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1026         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1027         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1028         setOperationAction(ISD::FROUND, MVT::f128, Legal);
1029 
1030         setOperationAction(ISD::SELECT, MVT::f128, Expand);
1031         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1032         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1033         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1034         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1035         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1036         // No implementation for these ops for PowerPC.
1037         setOperationAction(ISD::FSIN , MVT::f128, Expand);
1038         setOperationAction(ISD::FCOS , MVT::f128, Expand);
1039         setOperationAction(ISD::FPOW, MVT::f128, Expand);
1040         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1041         setOperationAction(ISD::FREM, MVT::f128, Expand);
1042 
1043         // Handle constrained floating-point operations of fp128
1044         setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1045         setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1046         setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1047         setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1048         setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1049         setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1050         setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1051         setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1052         setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1053         setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1054         setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1055         setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1056         setOperationAction(ISD::STRICT_FCEIL,  MVT::f128, Legal);
1057         setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1058         setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1059       }
1060       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1061       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1062       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1063       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1064       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1065     }
1066 
1067     if (Subtarget.hasP9Altivec()) {
1068       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1069       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1070 
1071       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1072       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1073       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1074       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1075       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1076       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1077       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1078     }
1079   }
1080 
1081   if (Subtarget.hasQPX()) {
1082     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1083     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1084     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1085     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
1086 
1087     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
1088     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
1089 
1090     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
1091     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
1092 
1093     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1094     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
1095 
1096     if (!Subtarget.useCRBits())
1097       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
1098     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1099 
1100     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
1101     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1102     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1103     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1104     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1105     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1106     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1107 
1108     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1109     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1110 
1111     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1112     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1113 
1114     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1115     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1116     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1117     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1118     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1119     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1120     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1121     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1122     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1123     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1124 
1125     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1126     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1127 
1128     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1129     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1130 
1131     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1132 
1133     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1134     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1135     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1136     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1137 
1138     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1139     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1140 
1141     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1142     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1143 
1144     if (!Subtarget.useCRBits())
1145       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1146     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1147 
1148     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1149     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1150     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1151     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1152     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1153     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1154     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1155 
1156     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1157     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1158 
1159     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1160     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1161     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1162     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1163     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1164     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1165     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1166     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1167     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1168     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1169 
1170     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1171     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1172 
1173     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1174     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1175 
1176     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1177 
1178     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1179     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1180     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1181 
1182     if (!Subtarget.useCRBits())
1183       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1184     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1185 
1186     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1187     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1188 
1189     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1190     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1191     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1192     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1193     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1194     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1195     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1196 
1197     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1198     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1199 
1200     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1201 
1202     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1203     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1204     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1205     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1206 
1207     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1208     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1209     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1210     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1211 
1212     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1213     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1214 
1215     // These need to set FE_INEXACT, and so cannot be vectorized here.
1216     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1217     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1218 
1219     if (TM.Options.UnsafeFPMath) {
1220       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1221       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1222 
1223       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1224       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1225     } else {
1226       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1227       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1228 
1229       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1230       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1231     }
1232 
1233     // TODO: Handle constrained floating-point operations of v4f64
1234   }
1235 
1236   if (Subtarget.has64BitSupport())
1237     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1238 
1239   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1240 
1241   if (!isPPC64) {
1242     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1243     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1244   }
1245 
1246   setBooleanContents(ZeroOrOneBooleanContent);
1247 
1248   if (Subtarget.hasAltivec()) {
1249     // Altivec instructions set fields to all zeros or all ones.
1250     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1251   }
1252 
1253   if (!isPPC64) {
1254     // These libcalls are not available in 32-bit.
1255     setLibcallName(RTLIB::SHL_I128, nullptr);
1256     setLibcallName(RTLIB::SRL_I128, nullptr);
1257     setLibcallName(RTLIB::SRA_I128, nullptr);
1258   }
1259 
1260   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1261 
1262   // We have target-specific dag combine patterns for the following nodes:
1263   setTargetDAGCombine(ISD::ADD);
1264   setTargetDAGCombine(ISD::SHL);
1265   setTargetDAGCombine(ISD::SRA);
1266   setTargetDAGCombine(ISD::SRL);
1267   setTargetDAGCombine(ISD::MUL);
1268   setTargetDAGCombine(ISD::FMA);
1269   setTargetDAGCombine(ISD::SINT_TO_FP);
1270   setTargetDAGCombine(ISD::BUILD_VECTOR);
1271   if (Subtarget.hasFPCVT())
1272     setTargetDAGCombine(ISD::UINT_TO_FP);
1273   setTargetDAGCombine(ISD::LOAD);
1274   setTargetDAGCombine(ISD::STORE);
1275   setTargetDAGCombine(ISD::BR_CC);
1276   if (Subtarget.useCRBits())
1277     setTargetDAGCombine(ISD::BRCOND);
1278   setTargetDAGCombine(ISD::BSWAP);
1279   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1280   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1281   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1282 
1283   setTargetDAGCombine(ISD::SIGN_EXTEND);
1284   setTargetDAGCombine(ISD::ZERO_EXTEND);
1285   setTargetDAGCombine(ISD::ANY_EXTEND);
1286 
1287   setTargetDAGCombine(ISD::TRUNCATE);
1288   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1289 
1290 
1291   if (Subtarget.useCRBits()) {
1292     setTargetDAGCombine(ISD::TRUNCATE);
1293     setTargetDAGCombine(ISD::SETCC);
1294     setTargetDAGCombine(ISD::SELECT_CC);
1295   }
1296 
1297   // Use reciprocal estimates.
1298   if (TM.Options.UnsafeFPMath) {
1299     setTargetDAGCombine(ISD::FDIV);
1300     setTargetDAGCombine(ISD::FSQRT);
1301   }
1302 
1303   if (Subtarget.hasP9Altivec()) {
1304     setTargetDAGCombine(ISD::ABS);
1305     setTargetDAGCombine(ISD::VSELECT);
1306   }
1307 
1308   if (EnableQuadPrecision) {
1309     setLibcallName(RTLIB::LOG_F128, "logf128");
1310     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1311     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1312     setLibcallName(RTLIB::EXP_F128, "expf128");
1313     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1314     setLibcallName(RTLIB::SIN_F128, "sinf128");
1315     setLibcallName(RTLIB::COS_F128, "cosf128");
1316     setLibcallName(RTLIB::POW_F128, "powf128");
1317     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1318     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1319     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1320     setLibcallName(RTLIB::REM_F128, "fmodf128");
1321   }
1322 
1323   // With 32 condition bits, we don't need to sink (and duplicate) compares
1324   // aggressively in CodeGenPrep.
1325   if (Subtarget.useCRBits()) {
1326     setHasMultipleConditionRegisters();
1327     setJumpIsExpensive();
1328   }
1329 
1330   setMinFunctionAlignment(Align(4));
1331 
1332   switch (Subtarget.getCPUDirective()) {
1333   default: break;
1334   case PPC::DIR_970:
1335   case PPC::DIR_A2:
1336   case PPC::DIR_E500:
1337   case PPC::DIR_E500mc:
1338   case PPC::DIR_E5500:
1339   case PPC::DIR_PWR4:
1340   case PPC::DIR_PWR5:
1341   case PPC::DIR_PWR5X:
1342   case PPC::DIR_PWR6:
1343   case PPC::DIR_PWR6X:
1344   case PPC::DIR_PWR7:
1345   case PPC::DIR_PWR8:
1346   case PPC::DIR_PWR9:
1347   case PPC::DIR_PWR10:
1348   case PPC::DIR_PWR_FUTURE:
1349     setPrefLoopAlignment(Align(16));
1350     setPrefFunctionAlignment(Align(16));
1351     break;
1352   }
1353 
1354   if (Subtarget.enableMachineScheduler())
1355     setSchedulingPreference(Sched::Source);
1356   else
1357     setSchedulingPreference(Sched::Hybrid);
1358 
1359   computeRegisterProperties(STI.getRegisterInfo());
1360 
1361   // The Freescale cores do better with aggressive inlining of memcpy and
1362   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1363   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1364       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1365     MaxStoresPerMemset = 32;
1366     MaxStoresPerMemsetOptSize = 16;
1367     MaxStoresPerMemcpy = 32;
1368     MaxStoresPerMemcpyOptSize = 8;
1369     MaxStoresPerMemmove = 32;
1370     MaxStoresPerMemmoveOptSize = 8;
1371   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1372     // The A2 also benefits from (very) aggressive inlining of memcpy and
1373     // friends. The overhead of a the function call, even when warm, can be
1374     // over one hundred cycles.
1375     MaxStoresPerMemset = 128;
1376     MaxStoresPerMemcpy = 128;
1377     MaxStoresPerMemmove = 128;
1378     MaxLoadsPerMemcmp = 128;
1379   } else {
1380     MaxLoadsPerMemcmp = 8;
1381     MaxLoadsPerMemcmpOptSize = 4;
1382   }
1383 
1384   // Let the subtarget (CPU) decide if a predictable select is more expensive
1385   // than the corresponding branch. This information is used in CGP to decide
1386   // when to convert selects into branches.
1387   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1388 }
1389 
1390 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1391 /// the desired ByVal argument alignment.
1392 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1393                              unsigned MaxMaxAlign) {
1394   if (MaxAlign == MaxMaxAlign)
1395     return;
1396   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1397     if (MaxMaxAlign >= 32 &&
1398         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1399       MaxAlign = 32;
1400     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1401              MaxAlign < 16)
1402       MaxAlign = 16;
1403   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1404     unsigned EltAlign = 0;
1405     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1406     if (EltAlign > MaxAlign)
1407       MaxAlign = EltAlign;
1408   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1409     for (auto *EltTy : STy->elements()) {
1410       unsigned EltAlign = 0;
1411       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1412       if (EltAlign > MaxAlign)
1413         MaxAlign = EltAlign;
1414       if (MaxAlign == MaxMaxAlign)
1415         break;
1416     }
1417   }
1418 }
1419 
1420 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1421 /// function arguments in the caller parameter area.
1422 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1423                                                   const DataLayout &DL) const {
1424   // 16byte and wider vectors are passed on 16byte boundary.
1425   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1426   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1427   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1428     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1429   return Align;
1430 }
1431 
1432 bool PPCTargetLowering::useSoftFloat() const {
1433   return Subtarget.useSoftFloat();
1434 }
1435 
1436 bool PPCTargetLowering::hasSPE() const {
1437   return Subtarget.hasSPE();
1438 }
1439 
1440 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1441   return VT.isScalarInteger();
1442 }
1443 
1444 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1445 /// type is cheaper than a multiply followed by a shift.
1446 /// This is true for words and doublewords on 64-bit PowerPC.
1447 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1448   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1449                               isOperationLegal(ISD::MULHU, Type)))
1450     return true;
1451   return TargetLowering::isMulhCheaperThanMulShift(Type);
1452 }
1453 
1454 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1455   switch ((PPCISD::NodeType)Opcode) {
1456   case PPCISD::FIRST_NUMBER:    break;
1457   case PPCISD::FSEL:            return "PPCISD::FSEL";
1458   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1459   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1460   case PPCISD::FCFID:           return "PPCISD::FCFID";
1461   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1462   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1463   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1464   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1465   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1466   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1467   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1468   case PPCISD::FP_TO_UINT_IN_VSR:
1469                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1470   case PPCISD::FP_TO_SINT_IN_VSR:
1471                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1472   case PPCISD::FRE:             return "PPCISD::FRE";
1473   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1474   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1475   case PPCISD::VPERM:           return "PPCISD::VPERM";
1476   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1477   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1478   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1479   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1480   case PPCISD::CMPB:            return "PPCISD::CMPB";
1481   case PPCISD::Hi:              return "PPCISD::Hi";
1482   case PPCISD::Lo:              return "PPCISD::Lo";
1483   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1484   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1485   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1486   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1487   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1488   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1489   case PPCISD::SRL:             return "PPCISD::SRL";
1490   case PPCISD::SRA:             return "PPCISD::SRA";
1491   case PPCISD::SHL:             return "PPCISD::SHL";
1492   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1493   case PPCISD::CALL:            return "PPCISD::CALL";
1494   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1495   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1496   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1497   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1498   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1499   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1500   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1501   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1502   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1503   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1504   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1505   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1506   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1507   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1508   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1509   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1510     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1511   case PPCISD::ANDI_rec_1_EQ_BIT:
1512     return "PPCISD::ANDI_rec_1_EQ_BIT";
1513   case PPCISD::ANDI_rec_1_GT_BIT:
1514     return "PPCISD::ANDI_rec_1_GT_BIT";
1515   case PPCISD::VCMP:            return "PPCISD::VCMP";
1516   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1517   case PPCISD::LBRX:            return "PPCISD::LBRX";
1518   case PPCISD::STBRX:           return "PPCISD::STBRX";
1519   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1520   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1521   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1522   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1523   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1524   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1525   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1526   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1527   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1528   case PPCISD::ST_VSR_SCAL_INT:
1529                                 return "PPCISD::ST_VSR_SCAL_INT";
1530   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1531   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1532   case PPCISD::BDZ:             return "PPCISD::BDZ";
1533   case PPCISD::MFFS:            return "PPCISD::MFFS";
1534   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1535   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1536   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1537   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1538   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1539   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1540   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1541   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1542   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1543   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1544   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1545   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1546   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1547   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1548   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1549   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1550   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1551   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1552   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1553   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1554   case PPCISD::SC:              return "PPCISD::SC";
1555   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1556   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1557   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1558   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1559   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1560   case PPCISD::VABSD:           return "PPCISD::VABSD";
1561   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1562   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1563   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1564   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1565   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1566   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1567   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1568   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1569   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1570   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1571   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1572   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1573   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1574   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1575   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1576   }
1577   return nullptr;
1578 }
1579 
1580 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1581                                           EVT VT) const {
1582   if (!VT.isVector())
1583     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1584 
1585   if (Subtarget.hasQPX())
1586     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1587 
1588   return VT.changeVectorElementTypeToInteger();
1589 }
1590 
1591 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1592   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1593   return true;
1594 }
1595 
1596 //===----------------------------------------------------------------------===//
1597 // Node matching predicates, for use by the tblgen matching code.
1598 //===----------------------------------------------------------------------===//
1599 
1600 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1601 static bool isFloatingPointZero(SDValue Op) {
1602   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1603     return CFP->getValueAPF().isZero();
1604   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1605     // Maybe this has already been legalized into the constant pool?
1606     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1607       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1608         return CFP->getValueAPF().isZero();
1609   }
1610   return false;
1611 }
1612 
1613 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1614 /// true if Op is undef or if it matches the specified value.
1615 static bool isConstantOrUndef(int Op, int Val) {
1616   return Op < 0 || Op == Val;
1617 }
1618 
1619 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1620 /// VPKUHUM instruction.
1621 /// The ShuffleKind distinguishes between big-endian operations with
1622 /// two different inputs (0), either-endian operations with two identical
1623 /// inputs (1), and little-endian operations with two different inputs (2).
1624 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1625 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1626                                SelectionDAG &DAG) {
1627   bool IsLE = DAG.getDataLayout().isLittleEndian();
1628   if (ShuffleKind == 0) {
1629     if (IsLE)
1630       return false;
1631     for (unsigned i = 0; i != 16; ++i)
1632       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1633         return false;
1634   } else if (ShuffleKind == 2) {
1635     if (!IsLE)
1636       return false;
1637     for (unsigned i = 0; i != 16; ++i)
1638       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1639         return false;
1640   } else if (ShuffleKind == 1) {
1641     unsigned j = IsLE ? 0 : 1;
1642     for (unsigned i = 0; i != 8; ++i)
1643       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1644           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1645         return false;
1646   }
1647   return true;
1648 }
1649 
1650 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1651 /// VPKUWUM instruction.
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::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1657                                SelectionDAG &DAG) {
1658   bool IsLE = DAG.getDataLayout().isLittleEndian();
1659   if (ShuffleKind == 0) {
1660     if (IsLE)
1661       return false;
1662     for (unsigned i = 0; i != 16; i += 2)
1663       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1664           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1665         return false;
1666   } else if (ShuffleKind == 2) {
1667     if (!IsLE)
1668       return false;
1669     for (unsigned i = 0; i != 16; i += 2)
1670       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1671           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1672         return false;
1673   } else if (ShuffleKind == 1) {
1674     unsigned j = IsLE ? 0 : 2;
1675     for (unsigned i = 0; i != 8; i += 2)
1676       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1677           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1678           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1679           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1680         return false;
1681   }
1682   return true;
1683 }
1684 
1685 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1686 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1687 /// current subtarget.
1688 ///
1689 /// The ShuffleKind distinguishes between big-endian operations with
1690 /// two different inputs (0), either-endian operations with two identical
1691 /// inputs (1), and little-endian operations with two different inputs (2).
1692 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1693 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1694                                SelectionDAG &DAG) {
1695   const PPCSubtarget& Subtarget =
1696       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1697   if (!Subtarget.hasP8Vector())
1698     return false;
1699 
1700   bool IsLE = DAG.getDataLayout().isLittleEndian();
1701   if (ShuffleKind == 0) {
1702     if (IsLE)
1703       return false;
1704     for (unsigned i = 0; i != 16; i += 4)
1705       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1706           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1707           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1708           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1709         return false;
1710   } else if (ShuffleKind == 2) {
1711     if (!IsLE)
1712       return false;
1713     for (unsigned i = 0; i != 16; i += 4)
1714       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1715           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1716           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1717           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1718         return false;
1719   } else if (ShuffleKind == 1) {
1720     unsigned j = IsLE ? 0 : 4;
1721     for (unsigned i = 0; i != 8; i += 4)
1722       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1723           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1724           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1725           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1726           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1727           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1728           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1729           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1730         return false;
1731   }
1732   return true;
1733 }
1734 
1735 /// isVMerge - Common function, used to match vmrg* shuffles.
1736 ///
1737 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1738                      unsigned LHSStart, unsigned RHSStart) {
1739   if (N->getValueType(0) != MVT::v16i8)
1740     return false;
1741   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1742          "Unsupported merge size!");
1743 
1744   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1745     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1746       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1747                              LHSStart+j+i*UnitSize) ||
1748           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1749                              RHSStart+j+i*UnitSize))
1750         return false;
1751     }
1752   return true;
1753 }
1754 
1755 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1756 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1757 /// The ShuffleKind distinguishes between big-endian merges with two
1758 /// different inputs (0), either-endian merges with two identical inputs (1),
1759 /// and little-endian merges with two different inputs (2).  For the latter,
1760 /// the input operands are swapped (see PPCInstrAltivec.td).
1761 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1762                              unsigned ShuffleKind, SelectionDAG &DAG) {
1763   if (DAG.getDataLayout().isLittleEndian()) {
1764     if (ShuffleKind == 1) // unary
1765       return isVMerge(N, UnitSize, 0, 0);
1766     else if (ShuffleKind == 2) // swapped
1767       return isVMerge(N, UnitSize, 0, 16);
1768     else
1769       return false;
1770   } else {
1771     if (ShuffleKind == 1) // unary
1772       return isVMerge(N, UnitSize, 8, 8);
1773     else if (ShuffleKind == 0) // normal
1774       return isVMerge(N, UnitSize, 8, 24);
1775     else
1776       return false;
1777   }
1778 }
1779 
1780 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1781 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1782 /// The ShuffleKind distinguishes between big-endian merges with two
1783 /// different inputs (0), either-endian merges with two identical inputs (1),
1784 /// and little-endian merges with two different inputs (2).  For the latter,
1785 /// the input operands are swapped (see PPCInstrAltivec.td).
1786 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1787                              unsigned ShuffleKind, SelectionDAG &DAG) {
1788   if (DAG.getDataLayout().isLittleEndian()) {
1789     if (ShuffleKind == 1) // unary
1790       return isVMerge(N, UnitSize, 8, 8);
1791     else if (ShuffleKind == 2) // swapped
1792       return isVMerge(N, UnitSize, 8, 24);
1793     else
1794       return false;
1795   } else {
1796     if (ShuffleKind == 1) // unary
1797       return isVMerge(N, UnitSize, 0, 0);
1798     else if (ShuffleKind == 0) // normal
1799       return isVMerge(N, UnitSize, 0, 16);
1800     else
1801       return false;
1802   }
1803 }
1804 
1805 /**
1806  * Common function used to match vmrgew and vmrgow shuffles
1807  *
1808  * The indexOffset determines whether to look for even or odd words in
1809  * the shuffle mask. This is based on the of the endianness of the target
1810  * machine.
1811  *   - Little Endian:
1812  *     - Use offset of 0 to check for odd elements
1813  *     - Use offset of 4 to check for even elements
1814  *   - Big Endian:
1815  *     - Use offset of 0 to check for even elements
1816  *     - Use offset of 4 to check for odd elements
1817  * A detailed description of the vector element ordering for little endian and
1818  * big endian can be found at
1819  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1820  * Targeting your applications - what little endian and big endian IBM XL C/C++
1821  * compiler differences mean to you
1822  *
1823  * The mask to the shuffle vector instruction specifies the indices of the
1824  * elements from the two input vectors to place in the result. The elements are
1825  * numbered in array-access order, starting with the first vector. These vectors
1826  * are always of type v16i8, thus each vector will contain 16 elements of size
1827  * 8. More info on the shuffle vector can be found in the
1828  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1829  * Language Reference.
1830  *
1831  * The RHSStartValue indicates whether the same input vectors are used (unary)
1832  * or two different input vectors are used, based on the following:
1833  *   - If the instruction uses the same vector for both inputs, the range of the
1834  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1835  *     be 0.
1836  *   - If the instruction has two different vectors then the range of the
1837  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1838  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1839  *     to 31 specify elements in the second vector).
1840  *
1841  * \param[in] N The shuffle vector SD Node to analyze
1842  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1843  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1844  * vector to the shuffle_vector instruction
1845  * \return true iff this shuffle vector represents an even or odd word merge
1846  */
1847 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1848                      unsigned RHSStartValue) {
1849   if (N->getValueType(0) != MVT::v16i8)
1850     return false;
1851 
1852   for (unsigned i = 0; i < 2; ++i)
1853     for (unsigned j = 0; j < 4; ++j)
1854       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1855                              i*RHSStartValue+j+IndexOffset) ||
1856           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1857                              i*RHSStartValue+j+IndexOffset+8))
1858         return false;
1859   return true;
1860 }
1861 
1862 /**
1863  * Determine if the specified shuffle mask is suitable for the vmrgew or
1864  * vmrgow instructions.
1865  *
1866  * \param[in] N The shuffle vector SD Node to analyze
1867  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1868  * \param[in] ShuffleKind Identify the type of merge:
1869  *   - 0 = big-endian merge with two different inputs;
1870  *   - 1 = either-endian merge with two identical inputs;
1871  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1872  *     little-endian merges).
1873  * \param[in] DAG The current SelectionDAG
1874  * \return true iff this shuffle mask
1875  */
1876 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1877                               unsigned ShuffleKind, SelectionDAG &DAG) {
1878   if (DAG.getDataLayout().isLittleEndian()) {
1879     unsigned indexOffset = CheckEven ? 4 : 0;
1880     if (ShuffleKind == 1) // Unary
1881       return isVMerge(N, indexOffset, 0);
1882     else if (ShuffleKind == 2) // swapped
1883       return isVMerge(N, indexOffset, 16);
1884     else
1885       return false;
1886   }
1887   else {
1888     unsigned indexOffset = CheckEven ? 0 : 4;
1889     if (ShuffleKind == 1) // Unary
1890       return isVMerge(N, indexOffset, 0);
1891     else if (ShuffleKind == 0) // Normal
1892       return isVMerge(N, indexOffset, 16);
1893     else
1894       return false;
1895   }
1896   return false;
1897 }
1898 
1899 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1900 /// amount, otherwise return -1.
1901 /// The ShuffleKind distinguishes between big-endian operations with two
1902 /// different inputs (0), either-endian operations with two identical inputs
1903 /// (1), and little-endian operations with two different inputs (2).  For the
1904 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1905 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1906                              SelectionDAG &DAG) {
1907   if (N->getValueType(0) != MVT::v16i8)
1908     return -1;
1909 
1910   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1911 
1912   // Find the first non-undef value in the shuffle mask.
1913   unsigned i;
1914   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1915     /*search*/;
1916 
1917   if (i == 16) return -1;  // all undef.
1918 
1919   // Otherwise, check to see if the rest of the elements are consecutively
1920   // numbered from this value.
1921   unsigned ShiftAmt = SVOp->getMaskElt(i);
1922   if (ShiftAmt < i) return -1;
1923 
1924   ShiftAmt -= i;
1925   bool isLE = DAG.getDataLayout().isLittleEndian();
1926 
1927   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1928     // Check the rest of the elements to see if they are consecutive.
1929     for (++i; i != 16; ++i)
1930       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1931         return -1;
1932   } else if (ShuffleKind == 1) {
1933     // Check the rest of the elements to see if they are consecutive.
1934     for (++i; i != 16; ++i)
1935       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1936         return -1;
1937   } else
1938     return -1;
1939 
1940   if (isLE)
1941     ShiftAmt = 16 - ShiftAmt;
1942 
1943   return ShiftAmt;
1944 }
1945 
1946 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1947 /// specifies a splat of a single element that is suitable for input to
1948 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1949 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1950   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1951          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1952 
1953   // The consecutive indices need to specify an element, not part of two
1954   // different elements.  So abandon ship early if this isn't the case.
1955   if (N->getMaskElt(0) % EltSize != 0)
1956     return false;
1957 
1958   // This is a splat operation if each element of the permute is the same, and
1959   // if the value doesn't reference the second vector.
1960   unsigned ElementBase = N->getMaskElt(0);
1961 
1962   // FIXME: Handle UNDEF elements too!
1963   if (ElementBase >= 16)
1964     return false;
1965 
1966   // Check that the indices are consecutive, in the case of a multi-byte element
1967   // splatted with a v16i8 mask.
1968   for (unsigned i = 1; i != EltSize; ++i)
1969     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1970       return false;
1971 
1972   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1973     if (N->getMaskElt(i) < 0) continue;
1974     for (unsigned j = 0; j != EltSize; ++j)
1975       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1976         return false;
1977   }
1978   return true;
1979 }
1980 
1981 /// Check that the mask is shuffling N byte elements. Within each N byte
1982 /// element of the mask, the indices could be either in increasing or
1983 /// decreasing order as long as they are consecutive.
1984 /// \param[in] N the shuffle vector SD Node to analyze
1985 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1986 /// Word/DoubleWord/QuadWord).
1987 /// \param[in] StepLen the delta indices number among the N byte element, if
1988 /// the mask is in increasing/decreasing order then it is 1/-1.
1989 /// \return true iff the mask is shuffling N byte elements.
1990 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1991                                    int StepLen) {
1992   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1993          "Unexpected element width.");
1994   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1995 
1996   unsigned NumOfElem = 16 / Width;
1997   unsigned MaskVal[16]; //  Width is never greater than 16
1998   for (unsigned i = 0; i < NumOfElem; ++i) {
1999     MaskVal[0] = N->getMaskElt(i * Width);
2000     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2001       return false;
2002     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2003       return false;
2004     }
2005 
2006     for (unsigned int j = 1; j < Width; ++j) {
2007       MaskVal[j] = N->getMaskElt(i * Width + j);
2008       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2009         return false;
2010       }
2011     }
2012   }
2013 
2014   return true;
2015 }
2016 
2017 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2018                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2019   if (!isNByteElemShuffleMask(N, 4, 1))
2020     return false;
2021 
2022   // Now we look at mask elements 0,4,8,12
2023   unsigned M0 = N->getMaskElt(0) / 4;
2024   unsigned M1 = N->getMaskElt(4) / 4;
2025   unsigned M2 = N->getMaskElt(8) / 4;
2026   unsigned M3 = N->getMaskElt(12) / 4;
2027   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2028   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2029 
2030   // Below, let H and L be arbitrary elements of the shuffle mask
2031   // where H is in the range [4,7] and L is in the range [0,3].
2032   // H, 1, 2, 3 or L, 5, 6, 7
2033   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2034       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2035     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2036     InsertAtByte = IsLE ? 12 : 0;
2037     Swap = M0 < 4;
2038     return true;
2039   }
2040   // 0, H, 2, 3 or 4, L, 6, 7
2041   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2042       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2043     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2044     InsertAtByte = IsLE ? 8 : 4;
2045     Swap = M1 < 4;
2046     return true;
2047   }
2048   // 0, 1, H, 3 or 4, 5, L, 7
2049   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2050       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2051     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2052     InsertAtByte = IsLE ? 4 : 8;
2053     Swap = M2 < 4;
2054     return true;
2055   }
2056   // 0, 1, 2, H or 4, 5, 6, L
2057   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2058       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2059     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2060     InsertAtByte = IsLE ? 0 : 12;
2061     Swap = M3 < 4;
2062     return true;
2063   }
2064 
2065   // If both vector operands for the shuffle are the same vector, the mask will
2066   // contain only elements from the first one and the second one will be undef.
2067   if (N->getOperand(1).isUndef()) {
2068     ShiftElts = 0;
2069     Swap = true;
2070     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2071     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2072       InsertAtByte = IsLE ? 12 : 0;
2073       return true;
2074     }
2075     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2076       InsertAtByte = IsLE ? 8 : 4;
2077       return true;
2078     }
2079     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2080       InsertAtByte = IsLE ? 4 : 8;
2081       return true;
2082     }
2083     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2084       InsertAtByte = IsLE ? 0 : 12;
2085       return true;
2086     }
2087   }
2088 
2089   return false;
2090 }
2091 
2092 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2093                                bool &Swap, bool IsLE) {
2094   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2095   // Ensure each byte index of the word is consecutive.
2096   if (!isNByteElemShuffleMask(N, 4, 1))
2097     return false;
2098 
2099   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2100   unsigned M0 = N->getMaskElt(0) / 4;
2101   unsigned M1 = N->getMaskElt(4) / 4;
2102   unsigned M2 = N->getMaskElt(8) / 4;
2103   unsigned M3 = N->getMaskElt(12) / 4;
2104 
2105   // If both vector operands for the shuffle are the same vector, the mask will
2106   // contain only elements from the first one and the second one will be undef.
2107   if (N->getOperand(1).isUndef()) {
2108     assert(M0 < 4 && "Indexing into an undef vector?");
2109     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2110       return false;
2111 
2112     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2113     Swap = false;
2114     return true;
2115   }
2116 
2117   // Ensure each word index of the ShuffleVector Mask is consecutive.
2118   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2119     return false;
2120 
2121   if (IsLE) {
2122     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2123       // Input vectors don't need to be swapped if the leading element
2124       // of the result is one of the 3 left elements of the second vector
2125       // (or if there is no shift to be done at all).
2126       Swap = false;
2127       ShiftElts = (8 - M0) % 8;
2128     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2129       // Input vectors need to be swapped if the leading element
2130       // of the result is one of the 3 left elements of the first vector
2131       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2132       Swap = true;
2133       ShiftElts = (4 - M0) % 4;
2134     }
2135 
2136     return true;
2137   } else {                                          // BE
2138     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2139       // Input vectors don't need to be swapped if the leading element
2140       // of the result is one of the 4 elements of the first vector.
2141       Swap = false;
2142       ShiftElts = M0;
2143     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2144       // Input vectors need to be swapped if the leading element
2145       // of the result is one of the 4 elements of the right vector.
2146       Swap = true;
2147       ShiftElts = M0 - 4;
2148     }
2149 
2150     return true;
2151   }
2152 }
2153 
2154 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2155   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2156 
2157   if (!isNByteElemShuffleMask(N, Width, -1))
2158     return false;
2159 
2160   for (int i = 0; i < 16; i += Width)
2161     if (N->getMaskElt(i) != i + Width - 1)
2162       return false;
2163 
2164   return true;
2165 }
2166 
2167 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2168   return isXXBRShuffleMaskHelper(N, 2);
2169 }
2170 
2171 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2172   return isXXBRShuffleMaskHelper(N, 4);
2173 }
2174 
2175 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2176   return isXXBRShuffleMaskHelper(N, 8);
2177 }
2178 
2179 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2180   return isXXBRShuffleMaskHelper(N, 16);
2181 }
2182 
2183 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2184 /// if the inputs to the instruction should be swapped and set \p DM to the
2185 /// value for the immediate.
2186 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2187 /// AND element 0 of the result comes from the first input (LE) or second input
2188 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2189 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2190 /// mask.
2191 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2192                                bool &Swap, bool IsLE) {
2193   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2194 
2195   // Ensure each byte index of the double word is consecutive.
2196   if (!isNByteElemShuffleMask(N, 8, 1))
2197     return false;
2198 
2199   unsigned M0 = N->getMaskElt(0) / 8;
2200   unsigned M1 = N->getMaskElt(8) / 8;
2201   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2202 
2203   // If both vector operands for the shuffle are the same vector, the mask will
2204   // contain only elements from the first one and the second one will be undef.
2205   if (N->getOperand(1).isUndef()) {
2206     if ((M0 | M1) < 2) {
2207       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2208       Swap = false;
2209       return true;
2210     } else
2211       return false;
2212   }
2213 
2214   if (IsLE) {
2215     if (M0 > 1 && M1 < 2) {
2216       Swap = false;
2217     } else if (M0 < 2 && M1 > 1) {
2218       M0 = (M0 + 2) % 4;
2219       M1 = (M1 + 2) % 4;
2220       Swap = true;
2221     } else
2222       return false;
2223 
2224     // Note: if control flow comes here that means Swap is already set above
2225     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2226     return true;
2227   } else { // BE
2228     if (M0 < 2 && M1 > 1) {
2229       Swap = false;
2230     } else if (M0 > 1 && M1 < 2) {
2231       M0 = (M0 + 2) % 4;
2232       M1 = (M1 + 2) % 4;
2233       Swap = true;
2234     } else
2235       return false;
2236 
2237     // Note: if control flow comes here that means Swap is already set above
2238     DM = (M0 << 1) + (M1 & 1);
2239     return true;
2240   }
2241 }
2242 
2243 
2244 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2245 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2246 /// elements are counted from the left of the vector register).
2247 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2248                                          SelectionDAG &DAG) {
2249   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2250   assert(isSplatShuffleMask(SVOp, EltSize));
2251   if (DAG.getDataLayout().isLittleEndian())
2252     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2253   else
2254     return SVOp->getMaskElt(0) / EltSize;
2255 }
2256 
2257 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2258 /// by using a vspltis[bhw] instruction of the specified element size, return
2259 /// the constant being splatted.  The ByteSize field indicates the number of
2260 /// bytes of each element [124] -> [bhw].
2261 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2262   SDValue OpVal(nullptr, 0);
2263 
2264   // If ByteSize of the splat is bigger than the element size of the
2265   // build_vector, then we have a case where we are checking for a splat where
2266   // multiple elements of the buildvector are folded together into a single
2267   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2268   unsigned EltSize = 16/N->getNumOperands();
2269   if (EltSize < ByteSize) {
2270     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2271     SDValue UniquedVals[4];
2272     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2273 
2274     // See if all of the elements in the buildvector agree across.
2275     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2276       if (N->getOperand(i).isUndef()) continue;
2277       // If the element isn't a constant, bail fully out.
2278       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2279 
2280       if (!UniquedVals[i&(Multiple-1)].getNode())
2281         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2282       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2283         return SDValue();  // no match.
2284     }
2285 
2286     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2287     // either constant or undef values that are identical for each chunk.  See
2288     // if these chunks can form into a larger vspltis*.
2289 
2290     // Check to see if all of the leading entries are either 0 or -1.  If
2291     // neither, then this won't fit into the immediate field.
2292     bool LeadingZero = true;
2293     bool LeadingOnes = true;
2294     for (unsigned i = 0; i != Multiple-1; ++i) {
2295       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2296 
2297       LeadingZero &= isNullConstant(UniquedVals[i]);
2298       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2299     }
2300     // Finally, check the least significant entry.
2301     if (LeadingZero) {
2302       if (!UniquedVals[Multiple-1].getNode())
2303         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2304       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2305       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2306         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2307     }
2308     if (LeadingOnes) {
2309       if (!UniquedVals[Multiple-1].getNode())
2310         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2311       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2312       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2313         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2314     }
2315 
2316     return SDValue();
2317   }
2318 
2319   // Check to see if this buildvec has a single non-undef value in its elements.
2320   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2321     if (N->getOperand(i).isUndef()) continue;
2322     if (!OpVal.getNode())
2323       OpVal = N->getOperand(i);
2324     else if (OpVal != N->getOperand(i))
2325       return SDValue();
2326   }
2327 
2328   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2329 
2330   unsigned ValSizeInBytes = EltSize;
2331   uint64_t Value = 0;
2332   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2333     Value = CN->getZExtValue();
2334   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2335     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2336     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2337   }
2338 
2339   // If the splat value is larger than the element value, then we can never do
2340   // this splat.  The only case that we could fit the replicated bits into our
2341   // immediate field for would be zero, and we prefer to use vxor for it.
2342   if (ValSizeInBytes < ByteSize) return SDValue();
2343 
2344   // If the element value is larger than the splat value, check if it consists
2345   // of a repeated bit pattern of size ByteSize.
2346   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2347     return SDValue();
2348 
2349   // Properly sign extend the value.
2350   int MaskVal = SignExtend32(Value, ByteSize * 8);
2351 
2352   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2353   if (MaskVal == 0) return SDValue();
2354 
2355   // Finally, if this value fits in a 5 bit sext field, return it
2356   if (SignExtend32<5>(MaskVal) == MaskVal)
2357     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2358   return SDValue();
2359 }
2360 
2361 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2362 /// amount, otherwise return -1.
2363 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2364   EVT VT = N->getValueType(0);
2365   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2366     return -1;
2367 
2368   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2369 
2370   // Find the first non-undef value in the shuffle mask.
2371   unsigned i;
2372   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2373     /*search*/;
2374 
2375   if (i == 4) return -1;  // all undef.
2376 
2377   // Otherwise, check to see if the rest of the elements are consecutively
2378   // numbered from this value.
2379   unsigned ShiftAmt = SVOp->getMaskElt(i);
2380   if (ShiftAmt < i) return -1;
2381   ShiftAmt -= i;
2382 
2383   // Check the rest of the elements to see if they are consecutive.
2384   for (++i; i != 4; ++i)
2385     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2386       return -1;
2387 
2388   return ShiftAmt;
2389 }
2390 
2391 //===----------------------------------------------------------------------===//
2392 //  Addressing Mode Selection
2393 //===----------------------------------------------------------------------===//
2394 
2395 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2396 /// or 64-bit immediate, and if the value can be accurately represented as a
2397 /// sign extension from a 16-bit value.  If so, this returns true and the
2398 /// immediate.
2399 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2400   if (!isa<ConstantSDNode>(N))
2401     return false;
2402 
2403   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2404   if (N->getValueType(0) == MVT::i32)
2405     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2406   else
2407     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2408 }
2409 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2410   return isIntS16Immediate(Op.getNode(), Imm);
2411 }
2412 
2413 
2414 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2415 /// be represented as an indexed [r+r] operation.
2416 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2417                                                SDValue &Index,
2418                                                SelectionDAG &DAG) const {
2419   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2420       UI != E; ++UI) {
2421     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2422       if (Memop->getMemoryVT() == MVT::f64) {
2423           Base = N.getOperand(0);
2424           Index = N.getOperand(1);
2425           return true;
2426       }
2427     }
2428   }
2429   return false;
2430 }
2431 
2432 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2433 /// can be represented as an indexed [r+r] operation.  Returns false if it
2434 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2435 /// non-zero and N can be represented by a base register plus a signed 16-bit
2436 /// displacement, make a more precise judgement by checking (displacement % \p
2437 /// EncodingAlignment).
2438 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2439                                             SDValue &Index, SelectionDAG &DAG,
2440                                             unsigned EncodingAlignment) const {
2441   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2442   // a [pc+imm].
2443   if (SelectAddressPCRel(N, Base))
2444     return false;
2445 
2446   int16_t imm = 0;
2447   if (N.getOpcode() == ISD::ADD) {
2448     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2449     // SPE load/store can only handle 8-bit offsets.
2450     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2451         return true;
2452     if (isIntS16Immediate(N.getOperand(1), imm) &&
2453         (!EncodingAlignment || !(imm % EncodingAlignment)))
2454       return false; // r+i
2455     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2456       return false;    // r+i
2457 
2458     Base = N.getOperand(0);
2459     Index = N.getOperand(1);
2460     return true;
2461   } else if (N.getOpcode() == ISD::OR) {
2462     if (isIntS16Immediate(N.getOperand(1), imm) &&
2463         (!EncodingAlignment || !(imm % EncodingAlignment)))
2464       return false; // r+i can fold it if we can.
2465 
2466     // If this is an or of disjoint bitfields, we can codegen this as an add
2467     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2468     // disjoint.
2469     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2470 
2471     if (LHSKnown.Zero.getBoolValue()) {
2472       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2473       // If all of the bits are known zero on the LHS or RHS, the add won't
2474       // carry.
2475       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2476         Base = N.getOperand(0);
2477         Index = N.getOperand(1);
2478         return true;
2479       }
2480     }
2481   }
2482 
2483   return false;
2484 }
2485 
2486 // If we happen to be doing an i64 load or store into a stack slot that has
2487 // less than a 4-byte alignment, then the frame-index elimination may need to
2488 // use an indexed load or store instruction (because the offset may not be a
2489 // multiple of 4). The extra register needed to hold the offset comes from the
2490 // register scavenger, and it is possible that the scavenger will need to use
2491 // an emergency spill slot. As a result, we need to make sure that a spill slot
2492 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2493 // stack slot.
2494 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2495   // FIXME: This does not handle the LWA case.
2496   if (VT != MVT::i64)
2497     return;
2498 
2499   // NOTE: We'll exclude negative FIs here, which come from argument
2500   // lowering, because there are no known test cases triggering this problem
2501   // using packed structures (or similar). We can remove this exclusion if
2502   // we find such a test case. The reason why this is so test-case driven is
2503   // because this entire 'fixup' is only to prevent crashes (from the
2504   // register scavenger) on not-really-valid inputs. For example, if we have:
2505   //   %a = alloca i1
2506   //   %b = bitcast i1* %a to i64*
2507   //   store i64* a, i64 b
2508   // then the store should really be marked as 'align 1', but is not. If it
2509   // were marked as 'align 1' then the indexed form would have been
2510   // instruction-selected initially, and the problem this 'fixup' is preventing
2511   // won't happen regardless.
2512   if (FrameIdx < 0)
2513     return;
2514 
2515   MachineFunction &MF = DAG.getMachineFunction();
2516   MachineFrameInfo &MFI = MF.getFrameInfo();
2517 
2518   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2519     return;
2520 
2521   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2522   FuncInfo->setHasNonRISpills();
2523 }
2524 
2525 /// Returns true if the address N can be represented by a base register plus
2526 /// a signed 16-bit displacement [r+imm], and if it is not better
2527 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2528 /// displacements that are multiples of that value.
2529 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2530                                             SDValue &Base,
2531                                             SelectionDAG &DAG,
2532                                             unsigned EncodingAlignment) const {
2533   // FIXME dl should come from parent load or store, not from address
2534   SDLoc dl(N);
2535 
2536   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2537   // a [pc+imm].
2538   if (SelectAddressPCRel(N, Base))
2539     return false;
2540 
2541   // If this can be more profitably realized as r+r, fail.
2542   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2543     return false;
2544 
2545   if (N.getOpcode() == ISD::ADD) {
2546     int16_t imm = 0;
2547     if (isIntS16Immediate(N.getOperand(1), imm) &&
2548         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2549       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2550       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2551         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2552         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2553       } else {
2554         Base = N.getOperand(0);
2555       }
2556       return true; // [r+i]
2557     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2558       // Match LOAD (ADD (X, Lo(G))).
2559       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2560              && "Cannot handle constant offsets yet!");
2561       Disp = N.getOperand(1).getOperand(0);  // The global address.
2562       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2563              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2564              Disp.getOpcode() == ISD::TargetConstantPool ||
2565              Disp.getOpcode() == ISD::TargetJumpTable);
2566       Base = N.getOperand(0);
2567       return true;  // [&g+r]
2568     }
2569   } else if (N.getOpcode() == ISD::OR) {
2570     int16_t imm = 0;
2571     if (isIntS16Immediate(N.getOperand(1), imm) &&
2572         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2573       // If this is an or of disjoint bitfields, we can codegen this as an add
2574       // (for better address arithmetic) if the LHS and RHS of the OR are
2575       // provably disjoint.
2576       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2577 
2578       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2579         // If all of the bits are known zero on the LHS or RHS, the add won't
2580         // carry.
2581         if (FrameIndexSDNode *FI =
2582               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2583           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2584           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2585         } else {
2586           Base = N.getOperand(0);
2587         }
2588         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2589         return true;
2590       }
2591     }
2592   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2593     // Loading from a constant address.
2594 
2595     // If this address fits entirely in a 16-bit sext immediate field, codegen
2596     // this as "d, 0"
2597     int16_t Imm;
2598     if (isIntS16Immediate(CN, Imm) &&
2599         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2600       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2601       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2602                              CN->getValueType(0));
2603       return true;
2604     }
2605 
2606     // Handle 32-bit sext immediates with LIS + addr mode.
2607     if ((CN->getValueType(0) == MVT::i32 ||
2608          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2609         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2610       int Addr = (int)CN->getZExtValue();
2611 
2612       // Otherwise, break this down into an LIS + disp.
2613       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2614 
2615       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2616                                    MVT::i32);
2617       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2618       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2619       return true;
2620     }
2621   }
2622 
2623   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2624   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2625     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2626     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2627   } else
2628     Base = N;
2629   return true;      // [r+0]
2630 }
2631 
2632 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2633 /// represented as an indexed [r+r] operation.
2634 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2635                                                 SDValue &Index,
2636                                                 SelectionDAG &DAG) const {
2637   // Check to see if we can easily represent this as an [r+r] address.  This
2638   // will fail if it thinks that the address is more profitably represented as
2639   // reg+imm, e.g. where imm = 0.
2640   if (SelectAddressRegReg(N, Base, Index, DAG))
2641     return true;
2642 
2643   // If the address is the result of an add, we will utilize the fact that the
2644   // address calculation includes an implicit add.  However, we can reduce
2645   // register pressure if we do not materialize a constant just for use as the
2646   // index register.  We only get rid of the add if it is not an add of a
2647   // value and a 16-bit signed constant and both have a single use.
2648   int16_t imm = 0;
2649   if (N.getOpcode() == ISD::ADD &&
2650       (!isIntS16Immediate(N.getOperand(1), imm) ||
2651        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2652     Base = N.getOperand(0);
2653     Index = N.getOperand(1);
2654     return true;
2655   }
2656 
2657   // Otherwise, do it the hard way, using R0 as the base register.
2658   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2659                          N.getValueType());
2660   Index = N;
2661   return true;
2662 }
2663 
2664 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2665   Ty *PCRelCand = dyn_cast<Ty>(N);
2666   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2667 }
2668 
2669 /// Returns true if this address is a PC Relative address.
2670 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2671 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2672 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2673   // This is a materialize PC Relative node. Always select this as PC Relative.
2674   Base = N;
2675   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2676     return true;
2677   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2678       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2679       isValidPCRelNode<JumpTableSDNode>(N) ||
2680       isValidPCRelNode<BlockAddressSDNode>(N))
2681     return true;
2682   return false;
2683 }
2684 
2685 /// Returns true if we should use a direct load into vector instruction
2686 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2687 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2688 
2689   // If there are any other uses other than scalar to vector, then we should
2690   // keep it as a scalar load -> direct move pattern to prevent multiple
2691   // loads.
2692   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2693   if (!LD)
2694     return false;
2695 
2696   EVT MemVT = LD->getMemoryVT();
2697   if (!MemVT.isSimple())
2698     return false;
2699   switch(MemVT.getSimpleVT().SimpleTy) {
2700   case MVT::i64:
2701     break;
2702   case MVT::i32:
2703     if (!ST.hasP8Vector())
2704       return false;
2705     break;
2706   case MVT::i16:
2707   case MVT::i8:
2708     if (!ST.hasP9Vector())
2709       return false;
2710     break;
2711   default:
2712     return false;
2713   }
2714 
2715   SDValue LoadedVal(N, 0);
2716   if (!LoadedVal.hasOneUse())
2717     return false;
2718 
2719   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2720        UI != UE; ++UI)
2721     if (UI.getUse().get().getResNo() == 0 &&
2722         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2723         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2724       return false;
2725 
2726   return true;
2727 }
2728 
2729 /// getPreIndexedAddressParts - returns true by value, base pointer and
2730 /// offset pointer and addressing mode by reference if the node's address
2731 /// can be legally represented as pre-indexed load / store address.
2732 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2733                                                   SDValue &Offset,
2734                                                   ISD::MemIndexedMode &AM,
2735                                                   SelectionDAG &DAG) const {
2736   if (DisablePPCPreinc) return false;
2737 
2738   bool isLoad = true;
2739   SDValue Ptr;
2740   EVT VT;
2741   unsigned Alignment;
2742   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2743     Ptr = LD->getBasePtr();
2744     VT = LD->getMemoryVT();
2745     Alignment = LD->getAlignment();
2746   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2747     Ptr = ST->getBasePtr();
2748     VT  = ST->getMemoryVT();
2749     Alignment = ST->getAlignment();
2750     isLoad = false;
2751   } else
2752     return false;
2753 
2754   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2755   // instructions because we can fold these into a more efficient instruction
2756   // instead, (such as LXSD).
2757   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2758     return false;
2759   }
2760 
2761   // PowerPC doesn't have preinc load/store instructions for vectors (except
2762   // for QPX, which does have preinc r+r forms).
2763   if (VT.isVector()) {
2764     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2765       return false;
2766     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2767       AM = ISD::PRE_INC;
2768       return true;
2769     }
2770   }
2771 
2772   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2773     // Common code will reject creating a pre-inc form if the base pointer
2774     // is a frame index, or if N is a store and the base pointer is either
2775     // the same as or a predecessor of the value being stored.  Check for
2776     // those situations here, and try with swapped Base/Offset instead.
2777     bool Swap = false;
2778 
2779     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2780       Swap = true;
2781     else if (!isLoad) {
2782       SDValue Val = cast<StoreSDNode>(N)->getValue();
2783       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2784         Swap = true;
2785     }
2786 
2787     if (Swap)
2788       std::swap(Base, Offset);
2789 
2790     AM = ISD::PRE_INC;
2791     return true;
2792   }
2793 
2794   // LDU/STU can only handle immediates that are a multiple of 4.
2795   if (VT != MVT::i64) {
2796     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2797       return false;
2798   } else {
2799     // LDU/STU need an address with at least 4-byte alignment.
2800     if (Alignment < 4)
2801       return false;
2802 
2803     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2804       return false;
2805   }
2806 
2807   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2808     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2809     // sext i32 to i64 when addr mode is r+i.
2810     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2811         LD->getExtensionType() == ISD::SEXTLOAD &&
2812         isa<ConstantSDNode>(Offset))
2813       return false;
2814   }
2815 
2816   AM = ISD::PRE_INC;
2817   return true;
2818 }
2819 
2820 //===----------------------------------------------------------------------===//
2821 //  LowerOperation implementation
2822 //===----------------------------------------------------------------------===//
2823 
2824 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2825 /// and LoOpFlags to the target MO flags.
2826 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2827                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2828                                const GlobalValue *GV = nullptr) {
2829   HiOpFlags = PPCII::MO_HA;
2830   LoOpFlags = PPCII::MO_LO;
2831 
2832   // Don't use the pic base if not in PIC relocation model.
2833   if (IsPIC) {
2834     HiOpFlags |= PPCII::MO_PIC_FLAG;
2835     LoOpFlags |= PPCII::MO_PIC_FLAG;
2836   }
2837 }
2838 
2839 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2840                              SelectionDAG &DAG) {
2841   SDLoc DL(HiPart);
2842   EVT PtrVT = HiPart.getValueType();
2843   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2844 
2845   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2846   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2847 
2848   // With PIC, the first instruction is actually "GR+hi(&G)".
2849   if (isPIC)
2850     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2851                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2852 
2853   // Generate non-pic code that has direct accesses to the constant pool.
2854   // The address of the global is just (hi(&g)+lo(&g)).
2855   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2856 }
2857 
2858 static void setUsesTOCBasePtr(MachineFunction &MF) {
2859   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2860   FuncInfo->setUsesTOCBasePtr();
2861 }
2862 
2863 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2864   setUsesTOCBasePtr(DAG.getMachineFunction());
2865 }
2866 
2867 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2868                                        SDValue GA) const {
2869   const bool Is64Bit = Subtarget.isPPC64();
2870   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2871   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2872                         : Subtarget.isAIXABI()
2873                               ? DAG.getRegister(PPC::R2, VT)
2874                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2875   SDValue Ops[] = { GA, Reg };
2876   return DAG.getMemIntrinsicNode(
2877       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2878       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2879       MachineMemOperand::MOLoad);
2880 }
2881 
2882 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2883                                              SelectionDAG &DAG) const {
2884   EVT PtrVT = Op.getValueType();
2885   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2886   const Constant *C = CP->getConstVal();
2887 
2888   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2889   // The actual address of the GlobalValue is stored in the TOC.
2890   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2891     if (Subtarget.isUsingPCRelativeCalls()) {
2892       SDLoc DL(CP);
2893       EVT Ty = getPointerTy(DAG.getDataLayout());
2894       SDValue ConstPool = DAG.getTargetConstantPool(
2895           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2896       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2897     }
2898     setUsesTOCBasePtr(DAG);
2899     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2900     return getTOCEntry(DAG, SDLoc(CP), GA);
2901   }
2902 
2903   unsigned MOHiFlag, MOLoFlag;
2904   bool IsPIC = isPositionIndependent();
2905   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2906 
2907   if (IsPIC && Subtarget.isSVR4ABI()) {
2908     SDValue GA =
2909         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2910     return getTOCEntry(DAG, SDLoc(CP), GA);
2911   }
2912 
2913   SDValue CPIHi =
2914       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2915   SDValue CPILo =
2916       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2917   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2918 }
2919 
2920 // For 64-bit PowerPC, prefer the more compact relative encodings.
2921 // This trades 32 bits per jump table entry for one or two instructions
2922 // on the jump site.
2923 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2924   if (isJumpTableRelative())
2925     return MachineJumpTableInfo::EK_LabelDifference32;
2926 
2927   return TargetLowering::getJumpTableEncoding();
2928 }
2929 
2930 bool PPCTargetLowering::isJumpTableRelative() const {
2931   if (UseAbsoluteJumpTables)
2932     return false;
2933   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2934     return true;
2935   return TargetLowering::isJumpTableRelative();
2936 }
2937 
2938 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2939                                                     SelectionDAG &DAG) const {
2940   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2941     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2942 
2943   switch (getTargetMachine().getCodeModel()) {
2944   case CodeModel::Small:
2945   case CodeModel::Medium:
2946     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2947   default:
2948     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2949                        getPointerTy(DAG.getDataLayout()));
2950   }
2951 }
2952 
2953 const MCExpr *
2954 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2955                                                 unsigned JTI,
2956                                                 MCContext &Ctx) const {
2957   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2958     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2959 
2960   switch (getTargetMachine().getCodeModel()) {
2961   case CodeModel::Small:
2962   case CodeModel::Medium:
2963     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2964   default:
2965     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2966   }
2967 }
2968 
2969 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2970   EVT PtrVT = Op.getValueType();
2971   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2972 
2973   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2974   if (Subtarget.isUsingPCRelativeCalls()) {
2975     SDLoc DL(JT);
2976     EVT Ty = getPointerTy(DAG.getDataLayout());
2977     SDValue GA =
2978         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2979     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2980     return MatAddr;
2981   }
2982 
2983   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2984   // The actual address of the GlobalValue is stored in the TOC.
2985   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2986     setUsesTOCBasePtr(DAG);
2987     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2988     return getTOCEntry(DAG, SDLoc(JT), GA);
2989   }
2990 
2991   unsigned MOHiFlag, MOLoFlag;
2992   bool IsPIC = isPositionIndependent();
2993   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2994 
2995   if (IsPIC && Subtarget.isSVR4ABI()) {
2996     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2997                                         PPCII::MO_PIC_FLAG);
2998     return getTOCEntry(DAG, SDLoc(GA), GA);
2999   }
3000 
3001   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3002   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3003   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3004 }
3005 
3006 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3007                                              SelectionDAG &DAG) const {
3008   EVT PtrVT = Op.getValueType();
3009   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3010   const BlockAddress *BA = BASDN->getBlockAddress();
3011 
3012   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3013   if (Subtarget.isUsingPCRelativeCalls()) {
3014     SDLoc DL(BASDN);
3015     EVT Ty = getPointerTy(DAG.getDataLayout());
3016     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3017                                            PPCII::MO_PCREL_FLAG);
3018     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3019     return MatAddr;
3020   }
3021 
3022   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3023   // The actual BlockAddress is stored in the TOC.
3024   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3025     setUsesTOCBasePtr(DAG);
3026     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3027     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3028   }
3029 
3030   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3031   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3032     return getTOCEntry(
3033         DAG, SDLoc(BASDN),
3034         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3035 
3036   unsigned MOHiFlag, MOLoFlag;
3037   bool IsPIC = isPositionIndependent();
3038   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3039   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3040   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3041   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3042 }
3043 
3044 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3045                                               SelectionDAG &DAG) const {
3046   // FIXME: TLS addresses currently use medium model code sequences,
3047   // which is the most useful form.  Eventually support for small and
3048   // large models could be added if users need it, at the cost of
3049   // additional complexity.
3050   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3051   if (DAG.getTarget().useEmulatedTLS())
3052     return LowerToTLSEmulatedModel(GA, DAG);
3053 
3054   SDLoc dl(GA);
3055   const GlobalValue *GV = GA->getGlobal();
3056   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3057   bool is64bit = Subtarget.isPPC64();
3058   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3059   PICLevel::Level picLevel = M->getPICLevel();
3060 
3061   const TargetMachine &TM = getTargetMachine();
3062   TLSModel::Model Model = TM.getTLSModel(GV);
3063 
3064   if (Model == TLSModel::LocalExec) {
3065     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3066                                                PPCII::MO_TPREL_HA);
3067     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3068                                                PPCII::MO_TPREL_LO);
3069     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3070                              : DAG.getRegister(PPC::R2, MVT::i32);
3071 
3072     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3073     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3074   }
3075 
3076   if (Model == TLSModel::InitialExec) {
3077     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3078     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3079                                                 PPCII::MO_TLS);
3080     SDValue GOTPtr;
3081     if (is64bit) {
3082       setUsesTOCBasePtr(DAG);
3083       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3084       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
3085                            PtrVT, GOTReg, TGA);
3086     } else {
3087       if (!TM.isPositionIndependent())
3088         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3089       else if (picLevel == PICLevel::SmallPIC)
3090         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3091       else
3092         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3093     }
3094     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
3095                                    PtrVT, TGA, GOTPtr);
3096     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3097   }
3098 
3099   if (Model == TLSModel::GeneralDynamic) {
3100     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3101     SDValue GOTPtr;
3102     if (is64bit) {
3103       setUsesTOCBasePtr(DAG);
3104       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3105       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3106                                    GOTReg, TGA);
3107     } else {
3108       if (picLevel == PICLevel::SmallPIC)
3109         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3110       else
3111         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3112     }
3113     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3114                        GOTPtr, TGA, TGA);
3115   }
3116 
3117   if (Model == TLSModel::LocalDynamic) {
3118     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3119     SDValue GOTPtr;
3120     if (is64bit) {
3121       setUsesTOCBasePtr(DAG);
3122       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3123       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3124                            GOTReg, TGA);
3125     } else {
3126       if (picLevel == PICLevel::SmallPIC)
3127         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3128       else
3129         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3130     }
3131     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3132                                   PtrVT, GOTPtr, TGA, TGA);
3133     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3134                                       PtrVT, TLSAddr, TGA);
3135     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3136   }
3137 
3138   llvm_unreachable("Unknown TLS model!");
3139 }
3140 
3141 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3142                                               SelectionDAG &DAG) const {
3143   EVT PtrVT = Op.getValueType();
3144   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3145   SDLoc DL(GSDN);
3146   const GlobalValue *GV = GSDN->getGlobal();
3147 
3148   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3149   // The actual address of the GlobalValue is stored in the TOC.
3150   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3151     if (Subtarget.isUsingPCRelativeCalls()) {
3152       EVT Ty = getPointerTy(DAG.getDataLayout());
3153       if (isAccessedAsGotIndirect(Op)) {
3154         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3155                                                 PPCII::MO_PCREL_FLAG |
3156                                                     PPCII::MO_GOT_FLAG);
3157         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3158         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3159                                    MachinePointerInfo());
3160         return Load;
3161       } else {
3162         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3163                                                 PPCII::MO_PCREL_FLAG);
3164         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3165       }
3166     }
3167     setUsesTOCBasePtr(DAG);
3168     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3169     return getTOCEntry(DAG, DL, GA);
3170   }
3171 
3172   unsigned MOHiFlag, MOLoFlag;
3173   bool IsPIC = isPositionIndependent();
3174   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3175 
3176   if (IsPIC && Subtarget.isSVR4ABI()) {
3177     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3178                                             GSDN->getOffset(),
3179                                             PPCII::MO_PIC_FLAG);
3180     return getTOCEntry(DAG, DL, GA);
3181   }
3182 
3183   SDValue GAHi =
3184     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3185   SDValue GALo =
3186     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3187 
3188   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3189 }
3190 
3191 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3192   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3193   SDLoc dl(Op);
3194 
3195   if (Op.getValueType() == MVT::v2i64) {
3196     // When the operands themselves are v2i64 values, we need to do something
3197     // special because VSX has no underlying comparison operations for these.
3198     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3199       // Equality can be handled by casting to the legal type for Altivec
3200       // comparisons, everything else needs to be expanded.
3201       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3202         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3203                  DAG.getSetCC(dl, MVT::v4i32,
3204                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3205                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3206                    CC));
3207       }
3208 
3209       return SDValue();
3210     }
3211 
3212     // We handle most of these in the usual way.
3213     return Op;
3214   }
3215 
3216   // If we're comparing for equality to zero, expose the fact that this is
3217   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3218   // fold the new nodes.
3219   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3220     return V;
3221 
3222   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3223     // Leave comparisons against 0 and -1 alone for now, since they're usually
3224     // optimized.  FIXME: revisit this when we can custom lower all setcc
3225     // optimizations.
3226     if (C->isAllOnesValue() || C->isNullValue())
3227       return SDValue();
3228   }
3229 
3230   // If we have an integer seteq/setne, turn it into a compare against zero
3231   // by xor'ing the rhs with the lhs, which is faster than setting a
3232   // condition register, reading it back out, and masking the correct bit.  The
3233   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3234   // the result to other bit-twiddling opportunities.
3235   EVT LHSVT = Op.getOperand(0).getValueType();
3236   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3237     EVT VT = Op.getValueType();
3238     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3239                                 Op.getOperand(1));
3240     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3241   }
3242   return SDValue();
3243 }
3244 
3245 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3246   SDNode *Node = Op.getNode();
3247   EVT VT = Node->getValueType(0);
3248   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3249   SDValue InChain = Node->getOperand(0);
3250   SDValue VAListPtr = Node->getOperand(1);
3251   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3252   SDLoc dl(Node);
3253 
3254   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3255 
3256   // gpr_index
3257   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3258                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3259   InChain = GprIndex.getValue(1);
3260 
3261   if (VT == MVT::i64) {
3262     // Check if GprIndex is even
3263     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3264                                  DAG.getConstant(1, dl, MVT::i32));
3265     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3266                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3267     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3268                                           DAG.getConstant(1, dl, MVT::i32));
3269     // Align GprIndex to be even if it isn't
3270     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3271                            GprIndex);
3272   }
3273 
3274   // fpr index is 1 byte after gpr
3275   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3276                                DAG.getConstant(1, dl, MVT::i32));
3277 
3278   // fpr
3279   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3280                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3281   InChain = FprIndex.getValue(1);
3282 
3283   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3284                                        DAG.getConstant(8, dl, MVT::i32));
3285 
3286   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3287                                         DAG.getConstant(4, dl, MVT::i32));
3288 
3289   // areas
3290   SDValue OverflowArea =
3291       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3292   InChain = OverflowArea.getValue(1);
3293 
3294   SDValue RegSaveArea =
3295       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3296   InChain = RegSaveArea.getValue(1);
3297 
3298   // select overflow_area if index > 8
3299   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3300                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3301 
3302   // adjustment constant gpr_index * 4/8
3303   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3304                                     VT.isInteger() ? GprIndex : FprIndex,
3305                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3306                                                     MVT::i32));
3307 
3308   // OurReg = RegSaveArea + RegConstant
3309   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3310                                RegConstant);
3311 
3312   // Floating types are 32 bytes into RegSaveArea
3313   if (VT.isFloatingPoint())
3314     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3315                          DAG.getConstant(32, dl, MVT::i32));
3316 
3317   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3318   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3319                                    VT.isInteger() ? GprIndex : FprIndex,
3320                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3321                                                    MVT::i32));
3322 
3323   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3324                               VT.isInteger() ? VAListPtr : FprPtr,
3325                               MachinePointerInfo(SV), MVT::i8);
3326 
3327   // determine if we should load from reg_save_area or overflow_area
3328   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3329 
3330   // increase overflow_area by 4/8 if gpr/fpr > 8
3331   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3332                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3333                                           dl, MVT::i32));
3334 
3335   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3336                              OverflowAreaPlusN);
3337 
3338   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3339                               MachinePointerInfo(), MVT::i32);
3340 
3341   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3342 }
3343 
3344 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3345   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3346 
3347   // We have to copy the entire va_list struct:
3348   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3349   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3350                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3351                        false, true, false, MachinePointerInfo(),
3352                        MachinePointerInfo());
3353 }
3354 
3355 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3356                                                   SelectionDAG &DAG) const {
3357   if (Subtarget.isAIXABI())
3358     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3359 
3360   return Op.getOperand(0);
3361 }
3362 
3363 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3364                                                 SelectionDAG &DAG) const {
3365   if (Subtarget.isAIXABI())
3366     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3367 
3368   SDValue Chain = Op.getOperand(0);
3369   SDValue Trmp = Op.getOperand(1); // trampoline
3370   SDValue FPtr = Op.getOperand(2); // nested function
3371   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3372   SDLoc dl(Op);
3373 
3374   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3375   bool isPPC64 = (PtrVT == MVT::i64);
3376   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3377 
3378   TargetLowering::ArgListTy Args;
3379   TargetLowering::ArgListEntry Entry;
3380 
3381   Entry.Ty = IntPtrTy;
3382   Entry.Node = Trmp; Args.push_back(Entry);
3383 
3384   // TrampSize == (isPPC64 ? 48 : 40);
3385   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3386                                isPPC64 ? MVT::i64 : MVT::i32);
3387   Args.push_back(Entry);
3388 
3389   Entry.Node = FPtr; Args.push_back(Entry);
3390   Entry.Node = Nest; Args.push_back(Entry);
3391 
3392   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3393   TargetLowering::CallLoweringInfo CLI(DAG);
3394   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3395       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3396       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3397 
3398   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3399   return CallResult.second;
3400 }
3401 
3402 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3403   MachineFunction &MF = DAG.getMachineFunction();
3404   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3405   EVT PtrVT = getPointerTy(MF.getDataLayout());
3406 
3407   SDLoc dl(Op);
3408 
3409   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3410     // vastart just stores the address of the VarArgsFrameIndex slot into the
3411     // memory location argument.
3412     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3413     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3414     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3415                         MachinePointerInfo(SV));
3416   }
3417 
3418   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3419   // We suppose the given va_list is already allocated.
3420   //
3421   // typedef struct {
3422   //  char gpr;     /* index into the array of 8 GPRs
3423   //                 * stored in the register save area
3424   //                 * gpr=0 corresponds to r3,
3425   //                 * gpr=1 to r4, etc.
3426   //                 */
3427   //  char fpr;     /* index into the array of 8 FPRs
3428   //                 * stored in the register save area
3429   //                 * fpr=0 corresponds to f1,
3430   //                 * fpr=1 to f2, etc.
3431   //                 */
3432   //  char *overflow_arg_area;
3433   //                /* location on stack that holds
3434   //                 * the next overflow argument
3435   //                 */
3436   //  char *reg_save_area;
3437   //               /* where r3:r10 and f1:f8 (if saved)
3438   //                * are stored
3439   //                */
3440   // } va_list[1];
3441 
3442   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3443   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3444   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3445                                             PtrVT);
3446   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3447                                  PtrVT);
3448 
3449   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3450   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3451 
3452   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3453   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3454 
3455   uint64_t FPROffset = 1;
3456   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3457 
3458   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3459 
3460   // Store first byte : number of int regs
3461   SDValue firstStore =
3462       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3463                         MachinePointerInfo(SV), MVT::i8);
3464   uint64_t nextOffset = FPROffset;
3465   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3466                                   ConstFPROffset);
3467 
3468   // Store second byte : number of float regs
3469   SDValue secondStore =
3470       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3471                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3472   nextOffset += StackOffset;
3473   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3474 
3475   // Store second word : arguments given on stack
3476   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3477                                     MachinePointerInfo(SV, nextOffset));
3478   nextOffset += FrameOffset;
3479   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3480 
3481   // Store third word : arguments given in registers
3482   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3483                       MachinePointerInfo(SV, nextOffset));
3484 }
3485 
3486 /// FPR - The set of FP registers that should be allocated for arguments
3487 /// on Darwin and AIX.
3488 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3489                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3490                                 PPC::F11, PPC::F12, PPC::F13};
3491 
3492 /// QFPR - The set of QPX registers that should be allocated for arguments.
3493 static const MCPhysReg QFPR[] = {
3494     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3495     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3496 
3497 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3498 /// the stack.
3499 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3500                                        unsigned PtrByteSize) {
3501   unsigned ArgSize = ArgVT.getStoreSize();
3502   if (Flags.isByVal())
3503     ArgSize = Flags.getByValSize();
3504 
3505   // Round up to multiples of the pointer size, except for array members,
3506   // which are always packed.
3507   if (!Flags.isInConsecutiveRegs())
3508     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3509 
3510   return ArgSize;
3511 }
3512 
3513 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3514 /// on the stack.
3515 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3516                                          ISD::ArgFlagsTy Flags,
3517                                          unsigned PtrByteSize) {
3518   Align Alignment(PtrByteSize);
3519 
3520   // Altivec parameters are padded to a 16 byte boundary.
3521   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3522       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3523       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3524       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3525     Alignment = Align(16);
3526   // QPX vector types stored in double-precision are padded to a 32 byte
3527   // boundary.
3528   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3529     Alignment = Align(32);
3530 
3531   // ByVal parameters are aligned as requested.
3532   if (Flags.isByVal()) {
3533     auto BVAlign = Flags.getNonZeroByValAlign();
3534     if (BVAlign > PtrByteSize) {
3535       if (BVAlign.value() % PtrByteSize != 0)
3536         llvm_unreachable(
3537             "ByVal alignment is not a multiple of the pointer size");
3538 
3539       Alignment = BVAlign;
3540     }
3541   }
3542 
3543   // Array members are always packed to their original alignment.
3544   if (Flags.isInConsecutiveRegs()) {
3545     // If the array member was split into multiple registers, the first
3546     // needs to be aligned to the size of the full type.  (Except for
3547     // ppcf128, which is only aligned as its f64 components.)
3548     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3549       Alignment = Align(OrigVT.getStoreSize());
3550     else
3551       Alignment = Align(ArgVT.getStoreSize());
3552   }
3553 
3554   return Alignment;
3555 }
3556 
3557 /// CalculateStackSlotUsed - Return whether this argument will use its
3558 /// stack slot (instead of being passed in registers).  ArgOffset,
3559 /// AvailableFPRs, and AvailableVRs must hold the current argument
3560 /// position, and will be updated to account for this argument.
3561 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3562                                    ISD::ArgFlagsTy Flags,
3563                                    unsigned PtrByteSize,
3564                                    unsigned LinkageSize,
3565                                    unsigned ParamAreaSize,
3566                                    unsigned &ArgOffset,
3567                                    unsigned &AvailableFPRs,
3568                                    unsigned &AvailableVRs, bool HasQPX) {
3569   bool UseMemory = false;
3570 
3571   // Respect alignment of argument on the stack.
3572   Align Alignment =
3573       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3574   ArgOffset = alignTo(ArgOffset, Alignment);
3575   // If there's no space left in the argument save area, we must
3576   // use memory (this check also catches zero-sized arguments).
3577   if (ArgOffset >= LinkageSize + ParamAreaSize)
3578     UseMemory = true;
3579 
3580   // Allocate argument on the stack.
3581   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3582   if (Flags.isInConsecutiveRegsLast())
3583     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3584   // If we overran the argument save area, we must use memory
3585   // (this check catches arguments passed partially in memory)
3586   if (ArgOffset > LinkageSize + ParamAreaSize)
3587     UseMemory = true;
3588 
3589   // However, if the argument is actually passed in an FPR or a VR,
3590   // we don't use memory after all.
3591   if (!Flags.isByVal()) {
3592     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3593         // QPX registers overlap with the scalar FP registers.
3594         (HasQPX && (ArgVT == MVT::v4f32 ||
3595                     ArgVT == MVT::v4f64 ||
3596                     ArgVT == MVT::v4i1)))
3597       if (AvailableFPRs > 0) {
3598         --AvailableFPRs;
3599         return false;
3600       }
3601     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3602         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3603         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3604         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3605       if (AvailableVRs > 0) {
3606         --AvailableVRs;
3607         return false;
3608       }
3609   }
3610 
3611   return UseMemory;
3612 }
3613 
3614 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3615 /// ensure minimum alignment required for target.
3616 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3617                                      unsigned NumBytes) {
3618   return alignTo(NumBytes, Lowering->getStackAlign());
3619 }
3620 
3621 SDValue PPCTargetLowering::LowerFormalArguments(
3622     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3623     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3624     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3625   if (Subtarget.isAIXABI())
3626     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3627                                     InVals);
3628   if (Subtarget.is64BitELFABI())
3629     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3630                                        InVals);
3631   if (Subtarget.is32BitELFABI())
3632     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3633                                        InVals);
3634 
3635   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3636                                      InVals);
3637 }
3638 
3639 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3640     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3641     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3642     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3643 
3644   // 32-bit SVR4 ABI Stack Frame Layout:
3645   //              +-----------------------------------+
3646   //        +-->  |            Back chain             |
3647   //        |     +-----------------------------------+
3648   //        |     | Floating-point register save area |
3649   //        |     +-----------------------------------+
3650   //        |     |    General register save area     |
3651   //        |     +-----------------------------------+
3652   //        |     |          CR save word             |
3653   //        |     +-----------------------------------+
3654   //        |     |         VRSAVE save word          |
3655   //        |     +-----------------------------------+
3656   //        |     |         Alignment padding         |
3657   //        |     +-----------------------------------+
3658   //        |     |     Vector register save area     |
3659   //        |     +-----------------------------------+
3660   //        |     |       Local variable space        |
3661   //        |     +-----------------------------------+
3662   //        |     |        Parameter list area        |
3663   //        |     +-----------------------------------+
3664   //        |     |           LR save word            |
3665   //        |     +-----------------------------------+
3666   // SP-->  +---  |            Back chain             |
3667   //              +-----------------------------------+
3668   //
3669   // Specifications:
3670   //   System V Application Binary Interface PowerPC Processor Supplement
3671   //   AltiVec Technology Programming Interface Manual
3672 
3673   MachineFunction &MF = DAG.getMachineFunction();
3674   MachineFrameInfo &MFI = MF.getFrameInfo();
3675   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3676 
3677   EVT PtrVT = getPointerTy(MF.getDataLayout());
3678   // Potential tail calls could cause overwriting of argument stack slots.
3679   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3680                        (CallConv == CallingConv::Fast));
3681   const Align PtrAlign(4);
3682 
3683   // Assign locations to all of the incoming arguments.
3684   SmallVector<CCValAssign, 16> ArgLocs;
3685   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3686                  *DAG.getContext());
3687 
3688   // Reserve space for the linkage area on the stack.
3689   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3690   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3691   if (useSoftFloat())
3692     CCInfo.PreAnalyzeFormalArguments(Ins);
3693 
3694   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3695   CCInfo.clearWasPPCF128();
3696 
3697   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3698     CCValAssign &VA = ArgLocs[i];
3699 
3700     // Arguments stored in registers.
3701     if (VA.isRegLoc()) {
3702       const TargetRegisterClass *RC;
3703       EVT ValVT = VA.getValVT();
3704 
3705       switch (ValVT.getSimpleVT().SimpleTy) {
3706         default:
3707           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3708         case MVT::i1:
3709         case MVT::i32:
3710           RC = &PPC::GPRCRegClass;
3711           break;
3712         case MVT::f32:
3713           if (Subtarget.hasP8Vector())
3714             RC = &PPC::VSSRCRegClass;
3715           else if (Subtarget.hasSPE())
3716             RC = &PPC::GPRCRegClass;
3717           else
3718             RC = &PPC::F4RCRegClass;
3719           break;
3720         case MVT::f64:
3721           if (Subtarget.hasVSX())
3722             RC = &PPC::VSFRCRegClass;
3723           else if (Subtarget.hasSPE())
3724             // SPE passes doubles in GPR pairs.
3725             RC = &PPC::GPRCRegClass;
3726           else
3727             RC = &PPC::F8RCRegClass;
3728           break;
3729         case MVT::v16i8:
3730         case MVT::v8i16:
3731         case MVT::v4i32:
3732           RC = &PPC::VRRCRegClass;
3733           break;
3734         case MVT::v4f32:
3735           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3736           break;
3737         case MVT::v2f64:
3738         case MVT::v2i64:
3739           RC = &PPC::VRRCRegClass;
3740           break;
3741         case MVT::v4f64:
3742           RC = &PPC::QFRCRegClass;
3743           break;
3744         case MVT::v4i1:
3745           RC = &PPC::QBRCRegClass;
3746           break;
3747       }
3748 
3749       SDValue ArgValue;
3750       // Transform the arguments stored in physical registers into
3751       // virtual ones.
3752       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3753         assert(i + 1 < e && "No second half of double precision argument");
3754         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3755         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3756         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3757         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3758         if (!Subtarget.isLittleEndian())
3759           std::swap (ArgValueLo, ArgValueHi);
3760         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3761                                ArgValueHi);
3762       } else {
3763         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3764         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3765                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3766         if (ValVT == MVT::i1)
3767           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3768       }
3769 
3770       InVals.push_back(ArgValue);
3771     } else {
3772       // Argument stored in memory.
3773       assert(VA.isMemLoc());
3774 
3775       // Get the extended size of the argument type in stack
3776       unsigned ArgSize = VA.getLocVT().getStoreSize();
3777       // Get the actual size of the argument type
3778       unsigned ObjSize = VA.getValVT().getStoreSize();
3779       unsigned ArgOffset = VA.getLocMemOffset();
3780       // Stack objects in PPC32 are right justified.
3781       ArgOffset += ArgSize - ObjSize;
3782       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3783 
3784       // Create load nodes to retrieve arguments from the stack.
3785       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3786       InVals.push_back(
3787           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3788     }
3789   }
3790 
3791   // Assign locations to all of the incoming aggregate by value arguments.
3792   // Aggregates passed by value are stored in the local variable space of the
3793   // caller's stack frame, right above the parameter list area.
3794   SmallVector<CCValAssign, 16> ByValArgLocs;
3795   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3796                       ByValArgLocs, *DAG.getContext());
3797 
3798   // Reserve stack space for the allocations in CCInfo.
3799   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3800 
3801   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3802 
3803   // Area that is at least reserved in the caller of this function.
3804   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3805   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3806 
3807   // Set the size that is at least reserved in caller of this function.  Tail
3808   // call optimized function's reserved stack space needs to be aligned so that
3809   // taking the difference between two stack areas will result in an aligned
3810   // stack.
3811   MinReservedArea =
3812       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3813   FuncInfo->setMinReservedArea(MinReservedArea);
3814 
3815   SmallVector<SDValue, 8> MemOps;
3816 
3817   // If the function takes variable number of arguments, make a frame index for
3818   // the start of the first vararg value... for expansion of llvm.va_start.
3819   if (isVarArg) {
3820     static const MCPhysReg GPArgRegs[] = {
3821       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3822       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3823     };
3824     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3825 
3826     static const MCPhysReg FPArgRegs[] = {
3827       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3828       PPC::F8
3829     };
3830     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3831 
3832     if (useSoftFloat() || hasSPE())
3833        NumFPArgRegs = 0;
3834 
3835     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3836     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3837 
3838     // Make room for NumGPArgRegs and NumFPArgRegs.
3839     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3840                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3841 
3842     FuncInfo->setVarArgsStackOffset(
3843       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3844                             CCInfo.getNextStackOffset(), true));
3845 
3846     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3847     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3848 
3849     // The fixed integer arguments of a variadic function are stored to the
3850     // VarArgsFrameIndex on the stack so that they may be loaded by
3851     // dereferencing the result of va_next.
3852     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3853       // Get an existing live-in vreg, or add a new one.
3854       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3855       if (!VReg)
3856         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3857 
3858       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3859       SDValue Store =
3860           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3861       MemOps.push_back(Store);
3862       // Increment the address by four for the next argument to store
3863       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3864       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3865     }
3866 
3867     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3868     // is set.
3869     // The double arguments are stored to the VarArgsFrameIndex
3870     // on the stack.
3871     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3872       // Get an existing live-in vreg, or add a new one.
3873       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3874       if (!VReg)
3875         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3876 
3877       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3878       SDValue Store =
3879           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3880       MemOps.push_back(Store);
3881       // Increment the address by eight for the next argument to store
3882       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3883                                          PtrVT);
3884       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3885     }
3886   }
3887 
3888   if (!MemOps.empty())
3889     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3890 
3891   return Chain;
3892 }
3893 
3894 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3895 // value to MVT::i64 and then truncate to the correct register size.
3896 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3897                                              EVT ObjectVT, SelectionDAG &DAG,
3898                                              SDValue ArgVal,
3899                                              const SDLoc &dl) const {
3900   if (Flags.isSExt())
3901     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3902                          DAG.getValueType(ObjectVT));
3903   else if (Flags.isZExt())
3904     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3905                          DAG.getValueType(ObjectVT));
3906 
3907   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3908 }
3909 
3910 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3911     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3912     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3913     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3914   // TODO: add description of PPC stack frame format, or at least some docs.
3915   //
3916   bool isELFv2ABI = Subtarget.isELFv2ABI();
3917   bool isLittleEndian = Subtarget.isLittleEndian();
3918   MachineFunction &MF = DAG.getMachineFunction();
3919   MachineFrameInfo &MFI = MF.getFrameInfo();
3920   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3921 
3922   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3923          "fastcc not supported on varargs functions");
3924 
3925   EVT PtrVT = getPointerTy(MF.getDataLayout());
3926   // Potential tail calls could cause overwriting of argument stack slots.
3927   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3928                        (CallConv == CallingConv::Fast));
3929   unsigned PtrByteSize = 8;
3930   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3931 
3932   static const MCPhysReg GPR[] = {
3933     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3934     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3935   };
3936   static const MCPhysReg VR[] = {
3937     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3938     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3939   };
3940 
3941   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3942   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3943   const unsigned Num_VR_Regs  = array_lengthof(VR);
3944   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3945 
3946   // Do a first pass over the arguments to determine whether the ABI
3947   // guarantees that our caller has allocated the parameter save area
3948   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3949   // in the ELFv2 ABI, it is true if this is a vararg function or if
3950   // any parameter is located in a stack slot.
3951 
3952   bool HasParameterArea = !isELFv2ABI || isVarArg;
3953   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3954   unsigned NumBytes = LinkageSize;
3955   unsigned AvailableFPRs = Num_FPR_Regs;
3956   unsigned AvailableVRs = Num_VR_Regs;
3957   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3958     if (Ins[i].Flags.isNest())
3959       continue;
3960 
3961     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3962                                PtrByteSize, LinkageSize, ParamAreaSize,
3963                                NumBytes, AvailableFPRs, AvailableVRs,
3964                                Subtarget.hasQPX()))
3965       HasParameterArea = true;
3966   }
3967 
3968   // Add DAG nodes to load the arguments or copy them out of registers.  On
3969   // entry to a function on PPC, the arguments start after the linkage area,
3970   // although the first ones are often in registers.
3971 
3972   unsigned ArgOffset = LinkageSize;
3973   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3974   unsigned &QFPR_idx = FPR_idx;
3975   SmallVector<SDValue, 8> MemOps;
3976   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3977   unsigned CurArgIdx = 0;
3978   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3979     SDValue ArgVal;
3980     bool needsLoad = false;
3981     EVT ObjectVT = Ins[ArgNo].VT;
3982     EVT OrigVT = Ins[ArgNo].ArgVT;
3983     unsigned ObjSize = ObjectVT.getStoreSize();
3984     unsigned ArgSize = ObjSize;
3985     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3986     if (Ins[ArgNo].isOrigArg()) {
3987       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3988       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3989     }
3990     // We re-align the argument offset for each argument, except when using the
3991     // fast calling convention, when we need to make sure we do that only when
3992     // we'll actually use a stack slot.
3993     unsigned CurArgOffset;
3994     Align Alignment;
3995     auto ComputeArgOffset = [&]() {
3996       /* Respect alignment of argument on the stack.  */
3997       Alignment =
3998           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3999       ArgOffset = alignTo(ArgOffset, Alignment);
4000       CurArgOffset = ArgOffset;
4001     };
4002 
4003     if (CallConv != CallingConv::Fast) {
4004       ComputeArgOffset();
4005 
4006       /* Compute GPR index associated with argument offset.  */
4007       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4008       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4009     }
4010 
4011     // FIXME the codegen can be much improved in some cases.
4012     // We do not have to keep everything in memory.
4013     if (Flags.isByVal()) {
4014       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4015 
4016       if (CallConv == CallingConv::Fast)
4017         ComputeArgOffset();
4018 
4019       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4020       ObjSize = Flags.getByValSize();
4021       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4022       // Empty aggregate parameters do not take up registers.  Examples:
4023       //   struct { } a;
4024       //   union  { } b;
4025       //   int c[0];
4026       // etc.  However, we have to provide a place-holder in InVals, so
4027       // pretend we have an 8-byte item at the current address for that
4028       // purpose.
4029       if (!ObjSize) {
4030         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4031         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4032         InVals.push_back(FIN);
4033         continue;
4034       }
4035 
4036       // Create a stack object covering all stack doublewords occupied
4037       // by the argument.  If the argument is (fully or partially) on
4038       // the stack, or if the argument is fully in registers but the
4039       // caller has allocated the parameter save anyway, we can refer
4040       // directly to the caller's stack frame.  Otherwise, create a
4041       // local copy in our own frame.
4042       int FI;
4043       if (HasParameterArea ||
4044           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4045         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4046       else
4047         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4048       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4049 
4050       // Handle aggregates smaller than 8 bytes.
4051       if (ObjSize < PtrByteSize) {
4052         // The value of the object is its address, which differs from the
4053         // address of the enclosing doubleword on big-endian systems.
4054         SDValue Arg = FIN;
4055         if (!isLittleEndian) {
4056           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4057           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4058         }
4059         InVals.push_back(Arg);
4060 
4061         if (GPR_idx != Num_GPR_Regs) {
4062           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4063           FuncInfo->addLiveInAttr(VReg, Flags);
4064           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4065           SDValue Store;
4066 
4067           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4068             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4069                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4070             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4071                                       MachinePointerInfo(&*FuncArg), ObjType);
4072           } else {
4073             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4074             // store the whole register as-is to the parameter save area
4075             // slot.
4076             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4077                                  MachinePointerInfo(&*FuncArg));
4078           }
4079 
4080           MemOps.push_back(Store);
4081         }
4082         // Whether we copied from a register or not, advance the offset
4083         // into the parameter save area by a full doubleword.
4084         ArgOffset += PtrByteSize;
4085         continue;
4086       }
4087 
4088       // The value of the object is its address, which is the address of
4089       // its first stack doubleword.
4090       InVals.push_back(FIN);
4091 
4092       // Store whatever pieces of the object are in registers to memory.
4093       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4094         if (GPR_idx == Num_GPR_Regs)
4095           break;
4096 
4097         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4098         FuncInfo->addLiveInAttr(VReg, Flags);
4099         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4100         SDValue Addr = FIN;
4101         if (j) {
4102           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4103           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4104         }
4105         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4106                                      MachinePointerInfo(&*FuncArg, j));
4107         MemOps.push_back(Store);
4108         ++GPR_idx;
4109       }
4110       ArgOffset += ArgSize;
4111       continue;
4112     }
4113 
4114     switch (ObjectVT.getSimpleVT().SimpleTy) {
4115     default: llvm_unreachable("Unhandled argument type!");
4116     case MVT::i1:
4117     case MVT::i32:
4118     case MVT::i64:
4119       if (Flags.isNest()) {
4120         // The 'nest' parameter, if any, is passed in R11.
4121         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4122         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4123 
4124         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4125           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4126 
4127         break;
4128       }
4129 
4130       // These can be scalar arguments or elements of an integer array type
4131       // passed directly.  Clang may use those instead of "byval" aggregate
4132       // types to avoid forcing arguments to memory unnecessarily.
4133       if (GPR_idx != Num_GPR_Regs) {
4134         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4135         FuncInfo->addLiveInAttr(VReg, Flags);
4136         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4137 
4138         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4139           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4140           // value to MVT::i64 and then truncate to the correct register size.
4141           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4142       } else {
4143         if (CallConv == CallingConv::Fast)
4144           ComputeArgOffset();
4145 
4146         needsLoad = true;
4147         ArgSize = PtrByteSize;
4148       }
4149       if (CallConv != CallingConv::Fast || needsLoad)
4150         ArgOffset += 8;
4151       break;
4152 
4153     case MVT::f32:
4154     case MVT::f64:
4155       // These can be scalar arguments or elements of a float array type
4156       // passed directly.  The latter are used to implement ELFv2 homogenous
4157       // float aggregates.
4158       if (FPR_idx != Num_FPR_Regs) {
4159         unsigned VReg;
4160 
4161         if (ObjectVT == MVT::f32)
4162           VReg = MF.addLiveIn(FPR[FPR_idx],
4163                               Subtarget.hasP8Vector()
4164                                   ? &PPC::VSSRCRegClass
4165                                   : &PPC::F4RCRegClass);
4166         else
4167           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4168                                                 ? &PPC::VSFRCRegClass
4169                                                 : &PPC::F8RCRegClass);
4170 
4171         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4172         ++FPR_idx;
4173       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4174         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4175         // once we support fp <-> gpr moves.
4176 
4177         // This can only ever happen in the presence of f32 array types,
4178         // since otherwise we never run out of FPRs before running out
4179         // of GPRs.
4180         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4181         FuncInfo->addLiveInAttr(VReg, Flags);
4182         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4183 
4184         if (ObjectVT == MVT::f32) {
4185           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4186             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4187                                  DAG.getConstant(32, dl, MVT::i32));
4188           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4189         }
4190 
4191         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4192       } else {
4193         if (CallConv == CallingConv::Fast)
4194           ComputeArgOffset();
4195 
4196         needsLoad = true;
4197       }
4198 
4199       // When passing an array of floats, the array occupies consecutive
4200       // space in the argument area; only round up to the next doubleword
4201       // at the end of the array.  Otherwise, each float takes 8 bytes.
4202       if (CallConv != CallingConv::Fast || needsLoad) {
4203         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4204         ArgOffset += ArgSize;
4205         if (Flags.isInConsecutiveRegsLast())
4206           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4207       }
4208       break;
4209     case MVT::v4f32:
4210     case MVT::v4i32:
4211     case MVT::v8i16:
4212     case MVT::v16i8:
4213     case MVT::v2f64:
4214     case MVT::v2i64:
4215     case MVT::v1i128:
4216     case MVT::f128:
4217       if (!Subtarget.hasQPX()) {
4218         // These can be scalar arguments or elements of a vector array type
4219         // passed directly.  The latter are used to implement ELFv2 homogenous
4220         // vector aggregates.
4221         if (VR_idx != Num_VR_Regs) {
4222           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4223           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4224           ++VR_idx;
4225         } else {
4226           if (CallConv == CallingConv::Fast)
4227             ComputeArgOffset();
4228           needsLoad = true;
4229         }
4230         if (CallConv != CallingConv::Fast || needsLoad)
4231           ArgOffset += 16;
4232         break;
4233       } // not QPX
4234 
4235       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4236              "Invalid QPX parameter type");
4237       LLVM_FALLTHROUGH;
4238 
4239     case MVT::v4f64:
4240     case MVT::v4i1:
4241       // QPX vectors are treated like their scalar floating-point subregisters
4242       // (except that they're larger).
4243       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4244       if (QFPR_idx != Num_QFPR_Regs) {
4245         const TargetRegisterClass *RC;
4246         switch (ObjectVT.getSimpleVT().SimpleTy) {
4247         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4248         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4249         default:         RC = &PPC::QBRCRegClass; break;
4250         }
4251 
4252         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4253         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4254         ++QFPR_idx;
4255       } else {
4256         if (CallConv == CallingConv::Fast)
4257           ComputeArgOffset();
4258         needsLoad = true;
4259       }
4260       if (CallConv != CallingConv::Fast || needsLoad)
4261         ArgOffset += Sz;
4262       break;
4263     }
4264 
4265     // We need to load the argument to a virtual register if we determined
4266     // above that we ran out of physical registers of the appropriate type.
4267     if (needsLoad) {
4268       if (ObjSize < ArgSize && !isLittleEndian)
4269         CurArgOffset += ArgSize - ObjSize;
4270       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4271       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4272       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4273     }
4274 
4275     InVals.push_back(ArgVal);
4276   }
4277 
4278   // Area that is at least reserved in the caller of this function.
4279   unsigned MinReservedArea;
4280   if (HasParameterArea)
4281     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4282   else
4283     MinReservedArea = LinkageSize;
4284 
4285   // Set the size that is at least reserved in caller of this function.  Tail
4286   // call optimized functions' reserved stack space needs to be aligned so that
4287   // taking the difference between two stack areas will result in an aligned
4288   // stack.
4289   MinReservedArea =
4290       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4291   FuncInfo->setMinReservedArea(MinReservedArea);
4292 
4293   // If the function takes variable number of arguments, make a frame index for
4294   // the start of the first vararg value... for expansion of llvm.va_start.
4295   if (isVarArg) {
4296     int Depth = ArgOffset;
4297 
4298     FuncInfo->setVarArgsFrameIndex(
4299       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4300     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4301 
4302     // If this function is vararg, store any remaining integer argument regs
4303     // to their spots on the stack so that they may be loaded by dereferencing
4304     // the result of va_next.
4305     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4306          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4307       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4308       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4309       SDValue Store =
4310           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4311       MemOps.push_back(Store);
4312       // Increment the address by four for the next argument to store
4313       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4314       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4315     }
4316   }
4317 
4318   if (!MemOps.empty())
4319     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4320 
4321   return Chain;
4322 }
4323 
4324 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4325     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4326     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4327     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4328   // TODO: add description of PPC stack frame format, or at least some docs.
4329   //
4330   MachineFunction &MF = DAG.getMachineFunction();
4331   MachineFrameInfo &MFI = MF.getFrameInfo();
4332   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4333 
4334   EVT PtrVT = getPointerTy(MF.getDataLayout());
4335   bool isPPC64 = PtrVT == MVT::i64;
4336   // Potential tail calls could cause overwriting of argument stack slots.
4337   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4338                        (CallConv == CallingConv::Fast));
4339   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4340   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4341   unsigned ArgOffset = LinkageSize;
4342   // Area that is at least reserved in caller of this function.
4343   unsigned MinReservedArea = ArgOffset;
4344 
4345   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4346     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4347     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4348   };
4349   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4350     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4351     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4352   };
4353   static const MCPhysReg VR[] = {
4354     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4355     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4356   };
4357 
4358   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4359   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4360   const unsigned Num_VR_Regs  = array_lengthof( VR);
4361 
4362   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4363 
4364   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4365 
4366   // In 32-bit non-varargs functions, the stack space for vectors is after the
4367   // stack space for non-vectors.  We do not use this space unless we have
4368   // too many vectors to fit in registers, something that only occurs in
4369   // constructed examples:), but we have to walk the arglist to figure
4370   // that out...for the pathological case, compute VecArgOffset as the
4371   // start of the vector parameter area.  Computing VecArgOffset is the
4372   // entire point of the following loop.
4373   unsigned VecArgOffset = ArgOffset;
4374   if (!isVarArg && !isPPC64) {
4375     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4376          ++ArgNo) {
4377       EVT ObjectVT = Ins[ArgNo].VT;
4378       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4379 
4380       if (Flags.isByVal()) {
4381         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4382         unsigned ObjSize = Flags.getByValSize();
4383         unsigned ArgSize =
4384                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4385         VecArgOffset += ArgSize;
4386         continue;
4387       }
4388 
4389       switch(ObjectVT.getSimpleVT().SimpleTy) {
4390       default: llvm_unreachable("Unhandled argument type!");
4391       case MVT::i1:
4392       case MVT::i32:
4393       case MVT::f32:
4394         VecArgOffset += 4;
4395         break;
4396       case MVT::i64:  // PPC64
4397       case MVT::f64:
4398         // FIXME: We are guaranteed to be !isPPC64 at this point.
4399         // Does MVT::i64 apply?
4400         VecArgOffset += 8;
4401         break;
4402       case MVT::v4f32:
4403       case MVT::v4i32:
4404       case MVT::v8i16:
4405       case MVT::v16i8:
4406         // Nothing to do, we're only looking at Nonvector args here.
4407         break;
4408       }
4409     }
4410   }
4411   // We've found where the vector parameter area in memory is.  Skip the
4412   // first 12 parameters; these don't use that memory.
4413   VecArgOffset = ((VecArgOffset+15)/16)*16;
4414   VecArgOffset += 12*16;
4415 
4416   // Add DAG nodes to load the arguments or copy them out of registers.  On
4417   // entry to a function on PPC, the arguments start after the linkage area,
4418   // although the first ones are often in registers.
4419 
4420   SmallVector<SDValue, 8> MemOps;
4421   unsigned nAltivecParamsAtEnd = 0;
4422   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4423   unsigned CurArgIdx = 0;
4424   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4425     SDValue ArgVal;
4426     bool needsLoad = false;
4427     EVT ObjectVT = Ins[ArgNo].VT;
4428     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4429     unsigned ArgSize = ObjSize;
4430     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4431     if (Ins[ArgNo].isOrigArg()) {
4432       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4433       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4434     }
4435     unsigned CurArgOffset = ArgOffset;
4436 
4437     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4438     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4439         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4440       if (isVarArg || isPPC64) {
4441         MinReservedArea = ((MinReservedArea+15)/16)*16;
4442         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4443                                                   Flags,
4444                                                   PtrByteSize);
4445       } else  nAltivecParamsAtEnd++;
4446     } else
4447       // Calculate min reserved area.
4448       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4449                                                 Flags,
4450                                                 PtrByteSize);
4451 
4452     // FIXME the codegen can be much improved in some cases.
4453     // We do not have to keep everything in memory.
4454     if (Flags.isByVal()) {
4455       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4456 
4457       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4458       ObjSize = Flags.getByValSize();
4459       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4460       // Objects of size 1 and 2 are right justified, everything else is
4461       // left justified.  This means the memory address is adjusted forwards.
4462       if (ObjSize==1 || ObjSize==2) {
4463         CurArgOffset = CurArgOffset + (4 - ObjSize);
4464       }
4465       // The value of the object is its address.
4466       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4467       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4468       InVals.push_back(FIN);
4469       if (ObjSize==1 || ObjSize==2) {
4470         if (GPR_idx != Num_GPR_Regs) {
4471           unsigned VReg;
4472           if (isPPC64)
4473             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4474           else
4475             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4476           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4477           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4478           SDValue Store =
4479               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4480                                 MachinePointerInfo(&*FuncArg), ObjType);
4481           MemOps.push_back(Store);
4482           ++GPR_idx;
4483         }
4484 
4485         ArgOffset += PtrByteSize;
4486 
4487         continue;
4488       }
4489       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4490         // Store whatever pieces of the object are in registers
4491         // to memory.  ArgOffset will be the address of the beginning
4492         // of the object.
4493         if (GPR_idx != Num_GPR_Regs) {
4494           unsigned VReg;
4495           if (isPPC64)
4496             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4497           else
4498             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4499           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4500           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4501           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4502           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4503                                        MachinePointerInfo(&*FuncArg, j));
4504           MemOps.push_back(Store);
4505           ++GPR_idx;
4506           ArgOffset += PtrByteSize;
4507         } else {
4508           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4509           break;
4510         }
4511       }
4512       continue;
4513     }
4514 
4515     switch (ObjectVT.getSimpleVT().SimpleTy) {
4516     default: llvm_unreachable("Unhandled argument type!");
4517     case MVT::i1:
4518     case MVT::i32:
4519       if (!isPPC64) {
4520         if (GPR_idx != Num_GPR_Regs) {
4521           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4522           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4523 
4524           if (ObjectVT == MVT::i1)
4525             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4526 
4527           ++GPR_idx;
4528         } else {
4529           needsLoad = true;
4530           ArgSize = PtrByteSize;
4531         }
4532         // All int arguments reserve stack space in the Darwin ABI.
4533         ArgOffset += PtrByteSize;
4534         break;
4535       }
4536       LLVM_FALLTHROUGH;
4537     case MVT::i64:  // PPC64
4538       if (GPR_idx != Num_GPR_Regs) {
4539         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4540         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4541 
4542         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4543           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4544           // value to MVT::i64 and then truncate to the correct register size.
4545           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4546 
4547         ++GPR_idx;
4548       } else {
4549         needsLoad = true;
4550         ArgSize = PtrByteSize;
4551       }
4552       // All int arguments reserve stack space in the Darwin ABI.
4553       ArgOffset += 8;
4554       break;
4555 
4556     case MVT::f32:
4557     case MVT::f64:
4558       // Every 4 bytes of argument space consumes one of the GPRs available for
4559       // argument passing.
4560       if (GPR_idx != Num_GPR_Regs) {
4561         ++GPR_idx;
4562         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4563           ++GPR_idx;
4564       }
4565       if (FPR_idx != Num_FPR_Regs) {
4566         unsigned VReg;
4567 
4568         if (ObjectVT == MVT::f32)
4569           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4570         else
4571           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4572 
4573         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4574         ++FPR_idx;
4575       } else {
4576         needsLoad = true;
4577       }
4578 
4579       // All FP arguments reserve stack space in the Darwin ABI.
4580       ArgOffset += isPPC64 ? 8 : ObjSize;
4581       break;
4582     case MVT::v4f32:
4583     case MVT::v4i32:
4584     case MVT::v8i16:
4585     case MVT::v16i8:
4586       // Note that vector arguments in registers don't reserve stack space,
4587       // except in varargs functions.
4588       if (VR_idx != Num_VR_Regs) {
4589         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4590         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4591         if (isVarArg) {
4592           while ((ArgOffset % 16) != 0) {
4593             ArgOffset += PtrByteSize;
4594             if (GPR_idx != Num_GPR_Regs)
4595               GPR_idx++;
4596           }
4597           ArgOffset += 16;
4598           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4599         }
4600         ++VR_idx;
4601       } else {
4602         if (!isVarArg && !isPPC64) {
4603           // Vectors go after all the nonvectors.
4604           CurArgOffset = VecArgOffset;
4605           VecArgOffset += 16;
4606         } else {
4607           // Vectors are aligned.
4608           ArgOffset = ((ArgOffset+15)/16)*16;
4609           CurArgOffset = ArgOffset;
4610           ArgOffset += 16;
4611         }
4612         needsLoad = true;
4613       }
4614       break;
4615     }
4616 
4617     // We need to load the argument to a virtual register if we determined above
4618     // that we ran out of physical registers of the appropriate type.
4619     if (needsLoad) {
4620       int FI = MFI.CreateFixedObject(ObjSize,
4621                                      CurArgOffset + (ArgSize - ObjSize),
4622                                      isImmutable);
4623       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4624       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4625     }
4626 
4627     InVals.push_back(ArgVal);
4628   }
4629 
4630   // Allow for Altivec parameters at the end, if needed.
4631   if (nAltivecParamsAtEnd) {
4632     MinReservedArea = ((MinReservedArea+15)/16)*16;
4633     MinReservedArea += 16*nAltivecParamsAtEnd;
4634   }
4635 
4636   // Area that is at least reserved in the caller of this function.
4637   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4638 
4639   // Set the size that is at least reserved in caller of this function.  Tail
4640   // call optimized functions' reserved stack space needs to be aligned so that
4641   // taking the difference between two stack areas will result in an aligned
4642   // stack.
4643   MinReservedArea =
4644       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4645   FuncInfo->setMinReservedArea(MinReservedArea);
4646 
4647   // If the function takes variable number of arguments, make a frame index for
4648   // the start of the first vararg value... for expansion of llvm.va_start.
4649   if (isVarArg) {
4650     int Depth = ArgOffset;
4651 
4652     FuncInfo->setVarArgsFrameIndex(
4653       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4654                             Depth, true));
4655     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4656 
4657     // If this function is vararg, store any remaining integer argument regs
4658     // to their spots on the stack so that they may be loaded by dereferencing
4659     // the result of va_next.
4660     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4661       unsigned VReg;
4662 
4663       if (isPPC64)
4664         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4665       else
4666         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4667 
4668       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4669       SDValue Store =
4670           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4671       MemOps.push_back(Store);
4672       // Increment the address by four for the next argument to store
4673       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4674       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4675     }
4676   }
4677 
4678   if (!MemOps.empty())
4679     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4680 
4681   return Chain;
4682 }
4683 
4684 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4685 /// adjusted to accommodate the arguments for the tailcall.
4686 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4687                                    unsigned ParamSize) {
4688 
4689   if (!isTailCall) return 0;
4690 
4691   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4692   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4693   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4694   // Remember only if the new adjustment is bigger.
4695   if (SPDiff < FI->getTailCallSPDelta())
4696     FI->setTailCallSPDelta(SPDiff);
4697 
4698   return SPDiff;
4699 }
4700 
4701 static bool isFunctionGlobalAddress(SDValue Callee);
4702 
4703 static bool
4704 callsShareTOCBase(const Function *Caller, SDValue Callee,
4705                     const TargetMachine &TM) {
4706    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4707    // don't have enough information to determine if the caller and calle share
4708    // the same  TOC base, so we have to pessimistically assume they don't for
4709    // correctness.
4710    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4711    if (!G)
4712      return false;
4713 
4714    const GlobalValue *GV = G->getGlobal();
4715   // The medium and large code models are expected to provide a sufficiently
4716   // large TOC to provide all data addressing needs of a module with a
4717   // single TOC. Since each module will be addressed with a single TOC then we
4718   // only need to check that caller and callee don't cross dso boundaries.
4719   if (CodeModel::Medium == TM.getCodeModel() ||
4720       CodeModel::Large == TM.getCodeModel())
4721     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4722 
4723   // Otherwise we need to ensure callee and caller are in the same section,
4724   // since the linker may allocate multiple TOCs, and we don't know which
4725   // sections will belong to the same TOC base.
4726 
4727   if (!GV->isStrongDefinitionForLinker())
4728     return false;
4729 
4730   // Any explicitly-specified sections and section prefixes must also match.
4731   // Also, if we're using -ffunction-sections, then each function is always in
4732   // a different section (the same is true for COMDAT functions).
4733   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4734       GV->getSection() != Caller->getSection())
4735     return false;
4736   if (const auto *F = dyn_cast<Function>(GV)) {
4737     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4738       return false;
4739   }
4740 
4741   // If the callee might be interposed, then we can't assume the ultimate call
4742   // target will be in the same section. Even in cases where we can assume that
4743   // interposition won't happen, in any case where the linker might insert a
4744   // stub to allow for interposition, we must generate code as though
4745   // interposition might occur. To understand why this matters, consider a
4746   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4747   // in the same section, but a is in a different module (i.e. has a different
4748   // TOC base pointer). If the linker allows for interposition between b and c,
4749   // then it will generate a stub for the call edge between b and c which will
4750   // save the TOC pointer into the designated stack slot allocated by b. If we
4751   // return true here, and therefore allow a tail call between b and c, that
4752   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4753   // pointer into the stack slot allocated by a (where the a -> b stub saved
4754   // a's TOC base pointer). If we're not considering a tail call, but rather,
4755   // whether a nop is needed after the call instruction in b, because the linker
4756   // will insert a stub, it might complain about a missing nop if we omit it
4757   // (although many don't complain in this case).
4758   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4759     return false;
4760 
4761   return true;
4762 }
4763 
4764 static bool
4765 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4766                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4767   assert(Subtarget.is64BitELFABI());
4768 
4769   const unsigned PtrByteSize = 8;
4770   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4771 
4772   static const MCPhysReg GPR[] = {
4773     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4774     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4775   };
4776   static const MCPhysReg VR[] = {
4777     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4778     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4779   };
4780 
4781   const unsigned NumGPRs = array_lengthof(GPR);
4782   const unsigned NumFPRs = 13;
4783   const unsigned NumVRs = array_lengthof(VR);
4784   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4785 
4786   unsigned NumBytes = LinkageSize;
4787   unsigned AvailableFPRs = NumFPRs;
4788   unsigned AvailableVRs = NumVRs;
4789 
4790   for (const ISD::OutputArg& Param : Outs) {
4791     if (Param.Flags.isNest()) continue;
4792 
4793     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4794                                PtrByteSize, LinkageSize, ParamAreaSize,
4795                                NumBytes, AvailableFPRs, AvailableVRs,
4796                                Subtarget.hasQPX()))
4797       return true;
4798   }
4799   return false;
4800 }
4801 
4802 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4803   if (CB.arg_size() != CallerFn->arg_size())
4804     return false;
4805 
4806   auto CalleeArgIter = CB.arg_begin();
4807   auto CalleeArgEnd = CB.arg_end();
4808   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4809 
4810   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4811     const Value* CalleeArg = *CalleeArgIter;
4812     const Value* CallerArg = &(*CallerArgIter);
4813     if (CalleeArg == CallerArg)
4814       continue;
4815 
4816     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4817     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4818     //      }
4819     // 1st argument of callee is undef and has the same type as caller.
4820     if (CalleeArg->getType() == CallerArg->getType() &&
4821         isa<UndefValue>(CalleeArg))
4822       continue;
4823 
4824     return false;
4825   }
4826 
4827   return true;
4828 }
4829 
4830 // Returns true if TCO is possible between the callers and callees
4831 // calling conventions.
4832 static bool
4833 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4834                                     CallingConv::ID CalleeCC) {
4835   // Tail calls are possible with fastcc and ccc.
4836   auto isTailCallableCC  = [] (CallingConv::ID CC){
4837       return  CC == CallingConv::C || CC == CallingConv::Fast;
4838   };
4839   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4840     return false;
4841 
4842   // We can safely tail call both fastcc and ccc callees from a c calling
4843   // convention caller. If the caller is fastcc, we may have less stack space
4844   // than a non-fastcc caller with the same signature so disable tail-calls in
4845   // that case.
4846   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4847 }
4848 
4849 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4850     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4851     const SmallVectorImpl<ISD::OutputArg> &Outs,
4852     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4853   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4854 
4855   if (DisableSCO && !TailCallOpt) return false;
4856 
4857   // Variadic argument functions are not supported.
4858   if (isVarArg) return false;
4859 
4860   auto &Caller = DAG.getMachineFunction().getFunction();
4861   // Check that the calling conventions are compatible for tco.
4862   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4863     return false;
4864 
4865   // Caller contains any byval parameter is not supported.
4866   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4867     return false;
4868 
4869   // Callee contains any byval parameter is not supported, too.
4870   // Note: This is a quick work around, because in some cases, e.g.
4871   // caller's stack size > callee's stack size, we are still able to apply
4872   // sibling call optimization. For example, gcc is able to do SCO for caller1
4873   // in the following example, but not for caller2.
4874   //   struct test {
4875   //     long int a;
4876   //     char ary[56];
4877   //   } gTest;
4878   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4879   //     b->a = v.a;
4880   //     return 0;
4881   //   }
4882   //   void caller1(struct test a, struct test c, struct test *b) {
4883   //     callee(gTest, b); }
4884   //   void caller2(struct test *b) { callee(gTest, b); }
4885   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4886     return false;
4887 
4888   // If callee and caller use different calling conventions, we cannot pass
4889   // parameters on stack since offsets for the parameter area may be different.
4890   if (Caller.getCallingConv() != CalleeCC &&
4891       needStackSlotPassParameters(Subtarget, Outs))
4892     return false;
4893 
4894   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4895   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4896   // callee potentially have different TOC bases then we cannot tail call since
4897   // we need to restore the TOC pointer after the call.
4898   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4899   // We cannot guarantee this for indirect calls or calls to external functions.
4900   // When PC-Relative addressing is used, the concept of the TOC is no longer
4901   // applicable so this check is not required.
4902   // Check first for indirect calls.
4903   if (!Subtarget.isUsingPCRelativeCalls() &&
4904       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4905     return false;
4906 
4907   // Check if we share the TOC base.
4908   if (!Subtarget.isUsingPCRelativeCalls() &&
4909       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4910     return false;
4911 
4912   // TCO allows altering callee ABI, so we don't have to check further.
4913   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4914     return true;
4915 
4916   if (DisableSCO) return false;
4917 
4918   // If callee use the same argument list that caller is using, then we can
4919   // apply SCO on this case. If it is not, then we need to check if callee needs
4920   // stack for passing arguments.
4921   // PC Relative tail calls may not have a CallBase.
4922   // If there is no CallBase we cannot verify if we have the same argument
4923   // list so assume that we don't have the same argument list.
4924   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4925       needStackSlotPassParameters(Subtarget, Outs))
4926     return false;
4927   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4928     return false;
4929 
4930   return true;
4931 }
4932 
4933 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4934 /// for tail call optimization. Targets which want to do tail call
4935 /// optimization should implement this function.
4936 bool
4937 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4938                                                      CallingConv::ID CalleeCC,
4939                                                      bool isVarArg,
4940                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4941                                                      SelectionDAG& DAG) const {
4942   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4943     return false;
4944 
4945   // Variable argument functions are not supported.
4946   if (isVarArg)
4947     return false;
4948 
4949   MachineFunction &MF = DAG.getMachineFunction();
4950   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4951   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4952     // Functions containing by val parameters are not supported.
4953     for (unsigned i = 0; i != Ins.size(); i++) {
4954        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4955        if (Flags.isByVal()) return false;
4956     }
4957 
4958     // Non-PIC/GOT tail calls are supported.
4959     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4960       return true;
4961 
4962     // At the moment we can only do local tail calls (in same module, hidden
4963     // or protected) if we are generating PIC.
4964     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4965       return G->getGlobal()->hasHiddenVisibility()
4966           || G->getGlobal()->hasProtectedVisibility();
4967   }
4968 
4969   return false;
4970 }
4971 
4972 /// isCallCompatibleAddress - Return the immediate to use if the specified
4973 /// 32-bit value is representable in the immediate field of a BxA instruction.
4974 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4975   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4976   if (!C) return nullptr;
4977 
4978   int Addr = C->getZExtValue();
4979   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4980       SignExtend32<26>(Addr) != Addr)
4981     return nullptr;  // Top 6 bits have to be sext of immediate.
4982 
4983   return DAG
4984       .getConstant(
4985           (int)C->getZExtValue() >> 2, SDLoc(Op),
4986           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4987       .getNode();
4988 }
4989 
4990 namespace {
4991 
4992 struct TailCallArgumentInfo {
4993   SDValue Arg;
4994   SDValue FrameIdxOp;
4995   int FrameIdx = 0;
4996 
4997   TailCallArgumentInfo() = default;
4998 };
4999 
5000 } // end anonymous namespace
5001 
5002 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5003 static void StoreTailCallArgumentsToStackSlot(
5004     SelectionDAG &DAG, SDValue Chain,
5005     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5006     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5007   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5008     SDValue Arg = TailCallArgs[i].Arg;
5009     SDValue FIN = TailCallArgs[i].FrameIdxOp;
5010     int FI = TailCallArgs[i].FrameIdx;
5011     // Store relative to framepointer.
5012     MemOpChains.push_back(DAG.getStore(
5013         Chain, dl, Arg, FIN,
5014         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
5015   }
5016 }
5017 
5018 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5019 /// the appropriate stack slot for the tail call optimized function call.
5020 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
5021                                              SDValue OldRetAddr, SDValue OldFP,
5022                                              int SPDiff, const SDLoc &dl) {
5023   if (SPDiff) {
5024     // Calculate the new stack slot for the return address.
5025     MachineFunction &MF = DAG.getMachineFunction();
5026     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5027     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5028     bool isPPC64 = Subtarget.isPPC64();
5029     int SlotSize = isPPC64 ? 8 : 4;
5030     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5031     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5032                                                          NewRetAddrLoc, true);
5033     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5034     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5035     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5036                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5037   }
5038   return Chain;
5039 }
5040 
5041 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5042 /// the position of the argument.
5043 static void
5044 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5045                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5046                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5047   int Offset = ArgOffset + SPDiff;
5048   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5049   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5050   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5051   SDValue FIN = DAG.getFrameIndex(FI, VT);
5052   TailCallArgumentInfo Info;
5053   Info.Arg = Arg;
5054   Info.FrameIdxOp = FIN;
5055   Info.FrameIdx = FI;
5056   TailCallArguments.push_back(Info);
5057 }
5058 
5059 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5060 /// stack slot. Returns the chain as result and the loaded frame pointers in
5061 /// LROpOut/FPOpout. Used when tail calling.
5062 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5063     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5064     SDValue &FPOpOut, const SDLoc &dl) const {
5065   if (SPDiff) {
5066     // Load the LR and FP stack slot for later adjusting.
5067     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5068     LROpOut = getReturnAddrFrameIndex(DAG);
5069     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5070     Chain = SDValue(LROpOut.getNode(), 1);
5071   }
5072   return Chain;
5073 }
5074 
5075 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5076 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5077 /// specified by the specific parameter attribute. The copy will be passed as
5078 /// a byval function parameter.
5079 /// Sometimes what we are copying is the end of a larger object, the part that
5080 /// does not fit in registers.
5081 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5082                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5083                                          SelectionDAG &DAG, const SDLoc &dl) {
5084   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5085   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5086                        Flags.getNonZeroByValAlign(), false, false, false,
5087                        MachinePointerInfo(), MachinePointerInfo());
5088 }
5089 
5090 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5091 /// tail calls.
5092 static void LowerMemOpCallTo(
5093     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5094     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5095     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5096     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5097   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5098   if (!isTailCall) {
5099     if (isVector) {
5100       SDValue StackPtr;
5101       if (isPPC64)
5102         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5103       else
5104         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5105       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5106                            DAG.getConstant(ArgOffset, dl, PtrVT));
5107     }
5108     MemOpChains.push_back(
5109         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5110     // Calculate and remember argument location.
5111   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5112                                   TailCallArguments);
5113 }
5114 
5115 static void
5116 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5117                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5118                 SDValue FPOp,
5119                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5120   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5121   // might overwrite each other in case of tail call optimization.
5122   SmallVector<SDValue, 8> MemOpChains2;
5123   // Do not flag preceding copytoreg stuff together with the following stuff.
5124   InFlag = SDValue();
5125   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5126                                     MemOpChains2, dl);
5127   if (!MemOpChains2.empty())
5128     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5129 
5130   // Store the return address to the appropriate stack slot.
5131   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5132 
5133   // Emit callseq_end just before tailcall node.
5134   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5135                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5136   InFlag = Chain.getValue(1);
5137 }
5138 
5139 // Is this global address that of a function that can be called by name? (as
5140 // opposed to something that must hold a descriptor for an indirect call).
5141 static bool isFunctionGlobalAddress(SDValue Callee) {
5142   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5143     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5144         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5145       return false;
5146 
5147     return G->getGlobal()->getValueType()->isFunctionTy();
5148   }
5149 
5150   return false;
5151 }
5152 
5153 SDValue PPCTargetLowering::LowerCallResult(
5154     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5155     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5156     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5157   SmallVector<CCValAssign, 16> RVLocs;
5158   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5159                     *DAG.getContext());
5160 
5161   CCRetInfo.AnalyzeCallResult(
5162       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5163                ? RetCC_PPC_Cold
5164                : RetCC_PPC);
5165 
5166   // Copy all of the result registers out of their specified physreg.
5167   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5168     CCValAssign &VA = RVLocs[i];
5169     assert(VA.isRegLoc() && "Can only return in registers!");
5170 
5171     SDValue Val;
5172 
5173     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5174       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5175                                       InFlag);
5176       Chain = Lo.getValue(1);
5177       InFlag = Lo.getValue(2);
5178       VA = RVLocs[++i]; // skip ahead to next loc
5179       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5180                                       InFlag);
5181       Chain = Hi.getValue(1);
5182       InFlag = Hi.getValue(2);
5183       if (!Subtarget.isLittleEndian())
5184         std::swap (Lo, Hi);
5185       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5186     } else {
5187       Val = DAG.getCopyFromReg(Chain, dl,
5188                                VA.getLocReg(), VA.getLocVT(), InFlag);
5189       Chain = Val.getValue(1);
5190       InFlag = Val.getValue(2);
5191     }
5192 
5193     switch (VA.getLocInfo()) {
5194     default: llvm_unreachable("Unknown loc info!");
5195     case CCValAssign::Full: break;
5196     case CCValAssign::AExt:
5197       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5198       break;
5199     case CCValAssign::ZExt:
5200       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5201                         DAG.getValueType(VA.getValVT()));
5202       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5203       break;
5204     case CCValAssign::SExt:
5205       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5206                         DAG.getValueType(VA.getValVT()));
5207       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5208       break;
5209     }
5210 
5211     InVals.push_back(Val);
5212   }
5213 
5214   return Chain;
5215 }
5216 
5217 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5218                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5219   // PatchPoint calls are not indirect.
5220   if (isPatchPoint)
5221     return false;
5222 
5223   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5224     return false;
5225 
5226   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5227   // becuase the immediate function pointer points to a descriptor instead of
5228   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5229   // pointer immediate points to the global entry point, while the BLA would
5230   // need to jump to the local entry point (see rL211174).
5231   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5232       isBLACompatibleAddress(Callee, DAG))
5233     return false;
5234 
5235   return true;
5236 }
5237 
5238 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5239 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5240   return Subtarget.isAIXABI() ||
5241          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5242 }
5243 
5244 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5245                               const Function &Caller,
5246                               const SDValue &Callee,
5247                               const PPCSubtarget &Subtarget,
5248                               const TargetMachine &TM) {
5249   if (CFlags.IsTailCall)
5250     return PPCISD::TC_RETURN;
5251 
5252   // This is a call through a function pointer.
5253   if (CFlags.IsIndirect) {
5254     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5255     // indirect calls. The save of the caller's TOC pointer to the stack will be
5256     // inserted into the DAG as part of call lowering. The restore of the TOC
5257     // pointer is modeled by using a pseudo instruction for the call opcode that
5258     // represents the 2 instruction sequence of an indirect branch and link,
5259     // immediately followed by a load of the TOC pointer from the the stack save
5260     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5261     // as it is not saved or used.
5262     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5263                                                : PPCISD::BCTRL;
5264   }
5265 
5266   if (Subtarget.isUsingPCRelativeCalls()) {
5267     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5268     return PPCISD::CALL_NOTOC;
5269   }
5270 
5271   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5272   // immediately following the call instruction if the caller and callee may
5273   // have different TOC bases. At link time if the linker determines the calls
5274   // may not share a TOC base, the call is redirected to a trampoline inserted
5275   // by the linker. The trampoline will (among other things) save the callers
5276   // TOC pointer at an ABI designated offset in the linkage area and the linker
5277   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5278   // into gpr2.
5279   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5280       return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5281                                                     : PPCISD::CALL_NOP;
5282 
5283   return PPCISD::CALL;
5284 }
5285 
5286 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5287                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5288   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5289     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5290       return SDValue(Dest, 0);
5291 
5292   // Returns true if the callee is local, and false otherwise.
5293   auto isLocalCallee = [&]() {
5294     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5295     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5296     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5297 
5298     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5299            !dyn_cast_or_null<GlobalIFunc>(GV);
5300   };
5301 
5302   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5303   // a static relocation model causes some versions of GNU LD (2.17.50, at
5304   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5305   // built with secure-PLT.
5306   bool UsePlt =
5307       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5308       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5309 
5310   // On AIX, direct function calls reference the symbol for the function's
5311   // entry point, which is named by prepending a "." before the function's
5312   // C-linkage name.
5313   const auto getAIXFuncEntryPointSymbolSDNode =
5314       [&](StringRef FuncName, bool IsDeclaration,
5315           const XCOFF::StorageClass &SC) {
5316         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5317 
5318         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5319             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5320 
5321         if (IsDeclaration && !S->hasRepresentedCsectSet()) {
5322           // On AIX, an undefined symbol needs to be associated with a
5323           // MCSectionXCOFF to get the correct storage mapping class.
5324           // In this case, XCOFF::XMC_PR.
5325           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5326               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5327               SectionKind::getMetadata());
5328           S->setRepresentedCsect(Sec);
5329         }
5330 
5331         MVT PtrVT =
5332             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5333         return DAG.getMCSymbol(S, PtrVT);
5334       };
5335 
5336   if (isFunctionGlobalAddress(Callee)) {
5337     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5338     const GlobalValue *GV = G->getGlobal();
5339 
5340     if (!Subtarget.isAIXABI())
5341       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5342                                         UsePlt ? PPCII::MO_PLT : 0);
5343 
5344     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5345     const GlobalObject *GO = cast<GlobalObject>(GV);
5346     const XCOFF::StorageClass SC =
5347         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5348     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5349                                             SC);
5350   }
5351 
5352   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5353     const char *SymName = S->getSymbol();
5354     if (!Subtarget.isAIXABI())
5355       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5356                                          UsePlt ? PPCII::MO_PLT : 0);
5357 
5358     // If there exists a user-declared function whose name is the same as the
5359     // ExternalSymbol's, then we pick up the user-declared version.
5360     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5361     if (const Function *F =
5362             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5363       const XCOFF::StorageClass SC =
5364           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5365       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5366                                               SC);
5367     }
5368 
5369     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5370   }
5371 
5372   // No transformation needed.
5373   assert(Callee.getNode() && "What no callee?");
5374   return Callee;
5375 }
5376 
5377 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5378   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5379          "Expected a CALLSEQ_STARTSDNode.");
5380 
5381   // The last operand is the chain, except when the node has glue. If the node
5382   // has glue, then the last operand is the glue, and the chain is the second
5383   // last operand.
5384   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5385   if (LastValue.getValueType() != MVT::Glue)
5386     return LastValue;
5387 
5388   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5389 }
5390 
5391 // Creates the node that moves a functions address into the count register
5392 // to prepare for an indirect call instruction.
5393 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5394                                 SDValue &Glue, SDValue &Chain,
5395                                 const SDLoc &dl) {
5396   SDValue MTCTROps[] = {Chain, Callee, Glue};
5397   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5398   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5399                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5400   // The glue is the second value produced.
5401   Glue = Chain.getValue(1);
5402 }
5403 
5404 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5405                                           SDValue &Glue, SDValue &Chain,
5406                                           SDValue CallSeqStart,
5407                                           const CallBase *CB, const SDLoc &dl,
5408                                           bool hasNest,
5409                                           const PPCSubtarget &Subtarget) {
5410   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5411   // entry point, but to the function descriptor (the function entry point
5412   // address is part of the function descriptor though).
5413   // The function descriptor is a three doubleword structure with the
5414   // following fields: function entry point, TOC base address and
5415   // environment pointer.
5416   // Thus for a call through a function pointer, the following actions need
5417   // to be performed:
5418   //   1. Save the TOC of the caller in the TOC save area of its stack
5419   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5420   //   2. Load the address of the function entry point from the function
5421   //      descriptor.
5422   //   3. Load the TOC of the callee from the function descriptor into r2.
5423   //   4. Load the environment pointer from the function descriptor into
5424   //      r11.
5425   //   5. Branch to the function entry point address.
5426   //   6. On return of the callee, the TOC of the caller needs to be
5427   //      restored (this is done in FinishCall()).
5428   //
5429   // The loads are scheduled at the beginning of the call sequence, and the
5430   // register copies are flagged together to ensure that no other
5431   // operations can be scheduled in between. E.g. without flagging the
5432   // copies together, a TOC access in the caller could be scheduled between
5433   // the assignment of the callee TOC and the branch to the callee, which leads
5434   // to incorrect code.
5435 
5436   // Start by loading the function address from the descriptor.
5437   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5438   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5439                       ? (MachineMemOperand::MODereferenceable |
5440                          MachineMemOperand::MOInvariant)
5441                       : MachineMemOperand::MONone;
5442 
5443   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5444 
5445   // Registers used in building the DAG.
5446   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5447   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5448 
5449   // Offsets of descriptor members.
5450   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5451   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5452 
5453   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5454   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5455 
5456   // One load for the functions entry point address.
5457   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5458                                     Alignment, MMOFlags);
5459 
5460   // One for loading the TOC anchor for the module that contains the called
5461   // function.
5462   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5463   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5464   SDValue TOCPtr =
5465       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5466                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5467 
5468   // One for loading the environment pointer.
5469   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5470   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5471   SDValue LoadEnvPtr =
5472       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5473                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5474 
5475 
5476   // Then copy the newly loaded TOC anchor to the TOC pointer.
5477   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5478   Chain = TOCVal.getValue(0);
5479   Glue = TOCVal.getValue(1);
5480 
5481   // If the function call has an explicit 'nest' parameter, it takes the
5482   // place of the environment pointer.
5483   assert((!hasNest || !Subtarget.isAIXABI()) &&
5484          "Nest parameter is not supported on AIX.");
5485   if (!hasNest) {
5486     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5487     Chain = EnvVal.getValue(0);
5488     Glue = EnvVal.getValue(1);
5489   }
5490 
5491   // The rest of the indirect call sequence is the same as the non-descriptor
5492   // DAG.
5493   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5494 }
5495 
5496 static void
5497 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5498                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5499                   SelectionDAG &DAG,
5500                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5501                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5502                   const PPCSubtarget &Subtarget) {
5503   const bool IsPPC64 = Subtarget.isPPC64();
5504   // MVT for a general purpose register.
5505   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5506 
5507   // First operand is always the chain.
5508   Ops.push_back(Chain);
5509 
5510   // If it's a direct call pass the callee as the second operand.
5511   if (!CFlags.IsIndirect)
5512     Ops.push_back(Callee);
5513   else {
5514     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5515 
5516     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5517     // on the stack (this would have been done in `LowerCall_64SVR4` or
5518     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5519     // represents both the indirect branch and a load that restores the TOC
5520     // pointer from the linkage area. The operand for the TOC restore is an add
5521     // of the TOC save offset to the stack pointer. This must be the second
5522     // operand: after the chain input but before any other variadic arguments.
5523     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5524     // saved or used.
5525     if (isTOCSaveRestoreRequired(Subtarget)) {
5526       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5527 
5528       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5529       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5530       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5531       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5532       Ops.push_back(AddTOC);
5533     }
5534 
5535     // Add the register used for the environment pointer.
5536     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5537       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5538                                     RegVT));
5539 
5540 
5541     // Add CTR register as callee so a bctr can be emitted later.
5542     if (CFlags.IsTailCall)
5543       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5544   }
5545 
5546   // If this is a tail call add stack pointer delta.
5547   if (CFlags.IsTailCall)
5548     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5549 
5550   // Add argument registers to the end of the list so that they are known live
5551   // into the call.
5552   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5553     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5554                                   RegsToPass[i].second.getValueType()));
5555 
5556   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5557   // no way to mark dependencies as implicit here.
5558   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5559   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5560        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5561     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5562 
5563   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5564   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5565     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5566 
5567   // Add a register mask operand representing the call-preserved registers.
5568   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5569   const uint32_t *Mask =
5570       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5571   assert(Mask && "Missing call preserved mask for calling convention");
5572   Ops.push_back(DAG.getRegisterMask(Mask));
5573 
5574   // If the glue is valid, it is the last operand.
5575   if (Glue.getNode())
5576     Ops.push_back(Glue);
5577 }
5578 
5579 SDValue PPCTargetLowering::FinishCall(
5580     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5581     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5582     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5583     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5584     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5585 
5586   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5587       Subtarget.isAIXABI())
5588     setUsesTOCBasePtr(DAG);
5589 
5590   unsigned CallOpc =
5591       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5592                     Subtarget, DAG.getTarget());
5593 
5594   if (!CFlags.IsIndirect)
5595     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5596   else if (Subtarget.usesFunctionDescriptors())
5597     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5598                                   dl, CFlags.HasNest, Subtarget);
5599   else
5600     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5601 
5602   // Build the operand list for the call instruction.
5603   SmallVector<SDValue, 8> Ops;
5604   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5605                     SPDiff, Subtarget);
5606 
5607   // Emit tail call.
5608   if (CFlags.IsTailCall) {
5609     // Indirect tail call when using PC Relative calls do not have the same
5610     // constraints.
5611     assert(((Callee.getOpcode() == ISD::Register &&
5612              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5613             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5614             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5615             isa<ConstantSDNode>(Callee) ||
5616             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5617            "Expecting a global address, external symbol, absolute value, "
5618            "register or an indirect tail call when PC Relative calls are "
5619            "used.");
5620     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5621     assert(CallOpc == PPCISD::TC_RETURN &&
5622            "Unexpected call opcode for a tail call.");
5623     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5624     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5625   }
5626 
5627   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5628   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5629   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5630   Glue = Chain.getValue(1);
5631 
5632   // When performing tail call optimization the callee pops its arguments off
5633   // the stack. Account for this here so these bytes can be pushed back on in
5634   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5635   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5636                          getTargetMachine().Options.GuaranteedTailCallOpt)
5637                             ? NumBytes
5638                             : 0;
5639 
5640   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5641                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5642                              Glue, dl);
5643   Glue = Chain.getValue(1);
5644 
5645   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5646                          DAG, InVals);
5647 }
5648 
5649 SDValue
5650 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5651                              SmallVectorImpl<SDValue> &InVals) const {
5652   SelectionDAG &DAG                     = CLI.DAG;
5653   SDLoc &dl                             = CLI.DL;
5654   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5655   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5656   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5657   SDValue Chain                         = CLI.Chain;
5658   SDValue Callee                        = CLI.Callee;
5659   bool &isTailCall                      = CLI.IsTailCall;
5660   CallingConv::ID CallConv              = CLI.CallConv;
5661   bool isVarArg                         = CLI.IsVarArg;
5662   bool isPatchPoint                     = CLI.IsPatchPoint;
5663   const CallBase *CB                    = CLI.CB;
5664 
5665   if (isTailCall) {
5666     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5667       isTailCall = false;
5668     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5669       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5670           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5671     else
5672       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5673                                                      Ins, DAG);
5674     if (isTailCall) {
5675       ++NumTailCalls;
5676       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5677         ++NumSiblingCalls;
5678 
5679       // PC Relative calls no longer guarantee that the callee is a Global
5680       // Address Node. The callee could be an indirect tail call in which
5681       // case the SDValue for the callee could be a load (to load the address
5682       // of a function pointer) or it may be a register copy (to move the
5683       // address of the callee from a function parameter into a virtual
5684       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5685       assert((Subtarget.isUsingPCRelativeCalls() ||
5686               isa<GlobalAddressSDNode>(Callee)) &&
5687              "Callee should be an llvm::Function object.");
5688 
5689       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5690                         << "\nTCO callee: ");
5691       LLVM_DEBUG(Callee.dump());
5692     }
5693   }
5694 
5695   if (!isTailCall && CB && CB->isMustTailCall())
5696     report_fatal_error("failed to perform tail call elimination on a call "
5697                        "site marked musttail");
5698 
5699   // When long calls (i.e. indirect calls) are always used, calls are always
5700   // made via function pointer. If we have a function name, first translate it
5701   // into a pointer.
5702   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5703       !isTailCall)
5704     Callee = LowerGlobalAddress(Callee, DAG);
5705 
5706   CallFlags CFlags(
5707       CallConv, isTailCall, isVarArg, isPatchPoint,
5708       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5709       // hasNest
5710       Subtarget.is64BitELFABI() &&
5711           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5712       CLI.NoMerge);
5713 
5714   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5715     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5716                             InVals, CB);
5717 
5718   if (Subtarget.isSVR4ABI())
5719     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5720                             InVals, CB);
5721 
5722   if (Subtarget.isAIXABI())
5723     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5724                          InVals, CB);
5725 
5726   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5727                           InVals, CB);
5728 }
5729 
5730 SDValue PPCTargetLowering::LowerCall_32SVR4(
5731     SDValue Chain, SDValue Callee, CallFlags CFlags,
5732     const SmallVectorImpl<ISD::OutputArg> &Outs,
5733     const SmallVectorImpl<SDValue> &OutVals,
5734     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5735     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5736     const CallBase *CB) const {
5737   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5738   // of the 32-bit SVR4 ABI stack frame layout.
5739 
5740   const CallingConv::ID CallConv = CFlags.CallConv;
5741   const bool IsVarArg = CFlags.IsVarArg;
5742   const bool IsTailCall = CFlags.IsTailCall;
5743 
5744   assert((CallConv == CallingConv::C ||
5745           CallConv == CallingConv::Cold ||
5746           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5747 
5748   const Align PtrAlign(4);
5749 
5750   MachineFunction &MF = DAG.getMachineFunction();
5751 
5752   // Mark this function as potentially containing a function that contains a
5753   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5754   // and restoring the callers stack pointer in this functions epilog. This is
5755   // done because by tail calling the called function might overwrite the value
5756   // in this function's (MF) stack pointer stack slot 0(SP).
5757   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5758       CallConv == CallingConv::Fast)
5759     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5760 
5761   // Count how many bytes are to be pushed on the stack, including the linkage
5762   // area, parameter list area and the part of the local variable space which
5763   // contains copies of aggregates which are passed by value.
5764 
5765   // Assign locations to all of the outgoing arguments.
5766   SmallVector<CCValAssign, 16> ArgLocs;
5767   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5768 
5769   // Reserve space for the linkage area on the stack.
5770   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5771                        PtrAlign);
5772   if (useSoftFloat())
5773     CCInfo.PreAnalyzeCallOperands(Outs);
5774 
5775   if (IsVarArg) {
5776     // Handle fixed and variable vector arguments differently.
5777     // Fixed vector arguments go into registers as long as registers are
5778     // available. Variable vector arguments always go into memory.
5779     unsigned NumArgs = Outs.size();
5780 
5781     for (unsigned i = 0; i != NumArgs; ++i) {
5782       MVT ArgVT = Outs[i].VT;
5783       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5784       bool Result;
5785 
5786       if (Outs[i].IsFixed) {
5787         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5788                                CCInfo);
5789       } else {
5790         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5791                                       ArgFlags, CCInfo);
5792       }
5793 
5794       if (Result) {
5795 #ifndef NDEBUG
5796         errs() << "Call operand #" << i << " has unhandled type "
5797              << EVT(ArgVT).getEVTString() << "\n";
5798 #endif
5799         llvm_unreachable(nullptr);
5800       }
5801     }
5802   } else {
5803     // All arguments are treated the same.
5804     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5805   }
5806   CCInfo.clearWasPPCF128();
5807 
5808   // Assign locations to all of the outgoing aggregate by value arguments.
5809   SmallVector<CCValAssign, 16> ByValArgLocs;
5810   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5811 
5812   // Reserve stack space for the allocations in CCInfo.
5813   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5814 
5815   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5816 
5817   // Size of the linkage area, parameter list area and the part of the local
5818   // space variable where copies of aggregates which are passed by value are
5819   // stored.
5820   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5821 
5822   // Calculate by how many bytes the stack has to be adjusted in case of tail
5823   // call optimization.
5824   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5825 
5826   // Adjust the stack pointer for the new arguments...
5827   // These operations are automatically eliminated by the prolog/epilog pass
5828   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5829   SDValue CallSeqStart = Chain;
5830 
5831   // Load the return address and frame pointer so it can be moved somewhere else
5832   // later.
5833   SDValue LROp, FPOp;
5834   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5835 
5836   // Set up a copy of the stack pointer for use loading and storing any
5837   // arguments that may not fit in the registers available for argument
5838   // passing.
5839   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5840 
5841   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5842   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5843   SmallVector<SDValue, 8> MemOpChains;
5844 
5845   bool seenFloatArg = false;
5846   // Walk the register/memloc assignments, inserting copies/loads.
5847   // i - Tracks the index into the list of registers allocated for the call
5848   // RealArgIdx - Tracks the index into the list of actual function arguments
5849   // j - Tracks the index into the list of byval arguments
5850   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5851        i != e;
5852        ++i, ++RealArgIdx) {
5853     CCValAssign &VA = ArgLocs[i];
5854     SDValue Arg = OutVals[RealArgIdx];
5855     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5856 
5857     if (Flags.isByVal()) {
5858       // Argument is an aggregate which is passed by value, thus we need to
5859       // create a copy of it in the local variable space of the current stack
5860       // frame (which is the stack frame of the caller) and pass the address of
5861       // this copy to the callee.
5862       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5863       CCValAssign &ByValVA = ByValArgLocs[j++];
5864       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5865 
5866       // Memory reserved in the local variable space of the callers stack frame.
5867       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5868 
5869       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5870       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5871                            StackPtr, PtrOff);
5872 
5873       // Create a copy of the argument in the local area of the current
5874       // stack frame.
5875       SDValue MemcpyCall =
5876         CreateCopyOfByValArgument(Arg, PtrOff,
5877                                   CallSeqStart.getNode()->getOperand(0),
5878                                   Flags, DAG, dl);
5879 
5880       // This must go outside the CALLSEQ_START..END.
5881       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5882                                                      SDLoc(MemcpyCall));
5883       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5884                              NewCallSeqStart.getNode());
5885       Chain = CallSeqStart = NewCallSeqStart;
5886 
5887       // Pass the address of the aggregate copy on the stack either in a
5888       // physical register or in the parameter list area of the current stack
5889       // frame to the callee.
5890       Arg = PtrOff;
5891     }
5892 
5893     // When useCRBits() is true, there can be i1 arguments.
5894     // It is because getRegisterType(MVT::i1) => MVT::i1,
5895     // and for other integer types getRegisterType() => MVT::i32.
5896     // Extend i1 and ensure callee will get i32.
5897     if (Arg.getValueType() == MVT::i1)
5898       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5899                         dl, MVT::i32, Arg);
5900 
5901     if (VA.isRegLoc()) {
5902       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5903       // Put argument in a physical register.
5904       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5905         bool IsLE = Subtarget.isLittleEndian();
5906         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5907                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5908         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5909         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5910                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5911         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5912                              SVal.getValue(0)));
5913       } else
5914         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5915     } else {
5916       // Put argument in the parameter list area of the current stack frame.
5917       assert(VA.isMemLoc());
5918       unsigned LocMemOffset = VA.getLocMemOffset();
5919 
5920       if (!IsTailCall) {
5921         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5922         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5923                              StackPtr, PtrOff);
5924 
5925         MemOpChains.push_back(
5926             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5927       } else {
5928         // Calculate and remember argument location.
5929         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5930                                  TailCallArguments);
5931       }
5932     }
5933   }
5934 
5935   if (!MemOpChains.empty())
5936     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5937 
5938   // Build a sequence of copy-to-reg nodes chained together with token chain
5939   // and flag operands which copy the outgoing args into the appropriate regs.
5940   SDValue InFlag;
5941   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5942     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5943                              RegsToPass[i].second, InFlag);
5944     InFlag = Chain.getValue(1);
5945   }
5946 
5947   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5948   // registers.
5949   if (IsVarArg) {
5950     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5951     SDValue Ops[] = { Chain, InFlag };
5952 
5953     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5954                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5955 
5956     InFlag = Chain.getValue(1);
5957   }
5958 
5959   if (IsTailCall)
5960     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5961                     TailCallArguments);
5962 
5963   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5964                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5965 }
5966 
5967 // Copy an argument into memory, being careful to do this outside the
5968 // call sequence for the call to which the argument belongs.
5969 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5970     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5971     SelectionDAG &DAG, const SDLoc &dl) const {
5972   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5973                         CallSeqStart.getNode()->getOperand(0),
5974                         Flags, DAG, dl);
5975   // The MEMCPY must go outside the CALLSEQ_START..END.
5976   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5977   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5978                                                  SDLoc(MemcpyCall));
5979   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5980                          NewCallSeqStart.getNode());
5981   return NewCallSeqStart;
5982 }
5983 
5984 SDValue PPCTargetLowering::LowerCall_64SVR4(
5985     SDValue Chain, SDValue Callee, CallFlags CFlags,
5986     const SmallVectorImpl<ISD::OutputArg> &Outs,
5987     const SmallVectorImpl<SDValue> &OutVals,
5988     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5989     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5990     const CallBase *CB) const {
5991   bool isELFv2ABI = Subtarget.isELFv2ABI();
5992   bool isLittleEndian = Subtarget.isLittleEndian();
5993   unsigned NumOps = Outs.size();
5994   bool IsSibCall = false;
5995   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5996 
5997   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5998   unsigned PtrByteSize = 8;
5999 
6000   MachineFunction &MF = DAG.getMachineFunction();
6001 
6002   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6003     IsSibCall = true;
6004 
6005   // Mark this function as potentially containing a function that contains a
6006   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6007   // and restoring the callers stack pointer in this functions epilog. This is
6008   // done because by tail calling the called function might overwrite the value
6009   // in this function's (MF) stack pointer stack slot 0(SP).
6010   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6011     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6012 
6013   assert(!(IsFastCall && CFlags.IsVarArg) &&
6014          "fastcc not supported on varargs functions");
6015 
6016   // Count how many bytes are to be pushed on the stack, including the linkage
6017   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
6018   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6019   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6020   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6021   unsigned NumBytes = LinkageSize;
6022   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6023   unsigned &QFPR_idx = FPR_idx;
6024 
6025   static const MCPhysReg GPR[] = {
6026     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6027     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6028   };
6029   static const MCPhysReg VR[] = {
6030     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6031     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6032   };
6033 
6034   const unsigned NumGPRs = array_lengthof(GPR);
6035   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6036   const unsigned NumVRs  = array_lengthof(VR);
6037   const unsigned NumQFPRs = NumFPRs;
6038 
6039   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6040   // can be passed to the callee in registers.
6041   // For the fast calling convention, there is another check below.
6042   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6043   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6044   if (!HasParameterArea) {
6045     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6046     unsigned AvailableFPRs = NumFPRs;
6047     unsigned AvailableVRs = NumVRs;
6048     unsigned NumBytesTmp = NumBytes;
6049     for (unsigned i = 0; i != NumOps; ++i) {
6050       if (Outs[i].Flags.isNest()) continue;
6051       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6052                                 PtrByteSize, LinkageSize, ParamAreaSize,
6053                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
6054                                 Subtarget.hasQPX()))
6055         HasParameterArea = true;
6056     }
6057   }
6058 
6059   // When using the fast calling convention, we don't provide backing for
6060   // arguments that will be in registers.
6061   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6062 
6063   // Avoid allocating parameter area for fastcc functions if all the arguments
6064   // can be passed in the registers.
6065   if (IsFastCall)
6066     HasParameterArea = false;
6067 
6068   // Add up all the space actually used.
6069   for (unsigned i = 0; i != NumOps; ++i) {
6070     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6071     EVT ArgVT = Outs[i].VT;
6072     EVT OrigVT = Outs[i].ArgVT;
6073 
6074     if (Flags.isNest())
6075       continue;
6076 
6077     if (IsFastCall) {
6078       if (Flags.isByVal()) {
6079         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6080         if (NumGPRsUsed > NumGPRs)
6081           HasParameterArea = true;
6082       } else {
6083         switch (ArgVT.getSimpleVT().SimpleTy) {
6084         default: llvm_unreachable("Unexpected ValueType for argument!");
6085         case MVT::i1:
6086         case MVT::i32:
6087         case MVT::i64:
6088           if (++NumGPRsUsed <= NumGPRs)
6089             continue;
6090           break;
6091         case MVT::v4i32:
6092         case MVT::v8i16:
6093         case MVT::v16i8:
6094         case MVT::v2f64:
6095         case MVT::v2i64:
6096         case MVT::v1i128:
6097         case MVT::f128:
6098           if (++NumVRsUsed <= NumVRs)
6099             continue;
6100           break;
6101         case MVT::v4f32:
6102           // When using QPX, this is handled like a FP register, otherwise, it
6103           // is an Altivec register.
6104           if (Subtarget.hasQPX()) {
6105             if (++NumFPRsUsed <= NumFPRs)
6106               continue;
6107           } else {
6108             if (++NumVRsUsed <= NumVRs)
6109               continue;
6110           }
6111           break;
6112         case MVT::f32:
6113         case MVT::f64:
6114         case MVT::v4f64: // QPX
6115         case MVT::v4i1:  // QPX
6116           if (++NumFPRsUsed <= NumFPRs)
6117             continue;
6118           break;
6119         }
6120         HasParameterArea = true;
6121       }
6122     }
6123 
6124     /* Respect alignment of argument on the stack.  */
6125     auto Alignement =
6126         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6127     NumBytes = alignTo(NumBytes, Alignement);
6128 
6129     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6130     if (Flags.isInConsecutiveRegsLast())
6131       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6132   }
6133 
6134   unsigned NumBytesActuallyUsed = NumBytes;
6135 
6136   // In the old ELFv1 ABI,
6137   // the prolog code of the callee may store up to 8 GPR argument registers to
6138   // the stack, allowing va_start to index over them in memory if its varargs.
6139   // Because we cannot tell if this is needed on the caller side, we have to
6140   // conservatively assume that it is needed.  As such, make sure we have at
6141   // least enough stack space for the caller to store the 8 GPRs.
6142   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6143   // really requires memory operands, e.g. a vararg function.
6144   if (HasParameterArea)
6145     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6146   else
6147     NumBytes = LinkageSize;
6148 
6149   // Tail call needs the stack to be aligned.
6150   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6151     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6152 
6153   int SPDiff = 0;
6154 
6155   // Calculate by how many bytes the stack has to be adjusted in case of tail
6156   // call optimization.
6157   if (!IsSibCall)
6158     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6159 
6160   // To protect arguments on the stack from being clobbered in a tail call,
6161   // force all the loads to happen before doing any other lowering.
6162   if (CFlags.IsTailCall)
6163     Chain = DAG.getStackArgumentTokenFactor(Chain);
6164 
6165   // Adjust the stack pointer for the new arguments...
6166   // These operations are automatically eliminated by the prolog/epilog pass
6167   if (!IsSibCall)
6168     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6169   SDValue CallSeqStart = Chain;
6170 
6171   // Load the return address and frame pointer so it can be move somewhere else
6172   // later.
6173   SDValue LROp, FPOp;
6174   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6175 
6176   // Set up a copy of the stack pointer for use loading and storing any
6177   // arguments that may not fit in the registers available for argument
6178   // passing.
6179   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6180 
6181   // Figure out which arguments are going to go in registers, and which in
6182   // memory.  Also, if this is a vararg function, floating point operations
6183   // must be stored to our stack, and loaded into integer regs as well, if
6184   // any integer regs are available for argument passing.
6185   unsigned ArgOffset = LinkageSize;
6186 
6187   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6188   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6189 
6190   SmallVector<SDValue, 8> MemOpChains;
6191   for (unsigned i = 0; i != NumOps; ++i) {
6192     SDValue Arg = OutVals[i];
6193     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6194     EVT ArgVT = Outs[i].VT;
6195     EVT OrigVT = Outs[i].ArgVT;
6196 
6197     // PtrOff will be used to store the current argument to the stack if a
6198     // register cannot be found for it.
6199     SDValue PtrOff;
6200 
6201     // We re-align the argument offset for each argument, except when using the
6202     // fast calling convention, when we need to make sure we do that only when
6203     // we'll actually use a stack slot.
6204     auto ComputePtrOff = [&]() {
6205       /* Respect alignment of argument on the stack.  */
6206       auto Alignment =
6207           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6208       ArgOffset = alignTo(ArgOffset, Alignment);
6209 
6210       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6211 
6212       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6213     };
6214 
6215     if (!IsFastCall) {
6216       ComputePtrOff();
6217 
6218       /* Compute GPR index associated with argument offset.  */
6219       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6220       GPR_idx = std::min(GPR_idx, NumGPRs);
6221     }
6222 
6223     // Promote integers to 64-bit values.
6224     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6225       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6226       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6227       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6228     }
6229 
6230     // FIXME memcpy is used way more than necessary.  Correctness first.
6231     // Note: "by value" is code for passing a structure by value, not
6232     // basic types.
6233     if (Flags.isByVal()) {
6234       // Note: Size includes alignment padding, so
6235       //   struct x { short a; char b; }
6236       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6237       // These are the proper values we need for right-justifying the
6238       // aggregate in a parameter register.
6239       unsigned Size = Flags.getByValSize();
6240 
6241       // An empty aggregate parameter takes up no storage and no
6242       // registers.
6243       if (Size == 0)
6244         continue;
6245 
6246       if (IsFastCall)
6247         ComputePtrOff();
6248 
6249       // All aggregates smaller than 8 bytes must be passed right-justified.
6250       if (Size==1 || Size==2 || Size==4) {
6251         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6252         if (GPR_idx != NumGPRs) {
6253           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6254                                         MachinePointerInfo(), VT);
6255           MemOpChains.push_back(Load.getValue(1));
6256           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6257 
6258           ArgOffset += PtrByteSize;
6259           continue;
6260         }
6261       }
6262 
6263       if (GPR_idx == NumGPRs && Size < 8) {
6264         SDValue AddPtr = PtrOff;
6265         if (!isLittleEndian) {
6266           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6267                                           PtrOff.getValueType());
6268           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6269         }
6270         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6271                                                           CallSeqStart,
6272                                                           Flags, DAG, dl);
6273         ArgOffset += PtrByteSize;
6274         continue;
6275       }
6276       // Copy entire object into memory.  There are cases where gcc-generated
6277       // code assumes it is there, even if it could be put entirely into
6278       // registers.  (This is not what the doc says.)
6279 
6280       // FIXME: The above statement is likely due to a misunderstanding of the
6281       // documents.  All arguments must be copied into the parameter area BY
6282       // THE CALLEE in the event that the callee takes the address of any
6283       // formal argument.  That has not yet been implemented.  However, it is
6284       // reasonable to use the stack area as a staging area for the register
6285       // load.
6286 
6287       // Skip this for small aggregates, as we will use the same slot for a
6288       // right-justified copy, below.
6289       if (Size >= 8)
6290         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6291                                                           CallSeqStart,
6292                                                           Flags, DAG, dl);
6293 
6294       // When a register is available, pass a small aggregate right-justified.
6295       if (Size < 8 && GPR_idx != NumGPRs) {
6296         // The easiest way to get this right-justified in a register
6297         // is to copy the structure into the rightmost portion of a
6298         // local variable slot, then load the whole slot into the
6299         // register.
6300         // FIXME: The memcpy seems to produce pretty awful code for
6301         // small aggregates, particularly for packed ones.
6302         // FIXME: It would be preferable to use the slot in the
6303         // parameter save area instead of a new local variable.
6304         SDValue AddPtr = PtrOff;
6305         if (!isLittleEndian) {
6306           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6307           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6308         }
6309         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6310                                                           CallSeqStart,
6311                                                           Flags, DAG, dl);
6312 
6313         // Load the slot into the register.
6314         SDValue Load =
6315             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6316         MemOpChains.push_back(Load.getValue(1));
6317         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6318 
6319         // Done with this argument.
6320         ArgOffset += PtrByteSize;
6321         continue;
6322       }
6323 
6324       // For aggregates larger than PtrByteSize, copy the pieces of the
6325       // object that fit into registers from the parameter save area.
6326       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6327         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6328         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6329         if (GPR_idx != NumGPRs) {
6330           SDValue Load =
6331               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6332           MemOpChains.push_back(Load.getValue(1));
6333           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6334           ArgOffset += PtrByteSize;
6335         } else {
6336           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6337           break;
6338         }
6339       }
6340       continue;
6341     }
6342 
6343     switch (Arg.getSimpleValueType().SimpleTy) {
6344     default: llvm_unreachable("Unexpected ValueType for argument!");
6345     case MVT::i1:
6346     case MVT::i32:
6347     case MVT::i64:
6348       if (Flags.isNest()) {
6349         // The 'nest' parameter, if any, is passed in R11.
6350         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6351         break;
6352       }
6353 
6354       // These can be scalar arguments or elements of an integer array type
6355       // passed directly.  Clang may use those instead of "byval" aggregate
6356       // types to avoid forcing arguments to memory unnecessarily.
6357       if (GPR_idx != NumGPRs) {
6358         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6359       } else {
6360         if (IsFastCall)
6361           ComputePtrOff();
6362 
6363         assert(HasParameterArea &&
6364                "Parameter area must exist to pass an argument in memory.");
6365         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6366                          true, CFlags.IsTailCall, false, MemOpChains,
6367                          TailCallArguments, dl);
6368         if (IsFastCall)
6369           ArgOffset += PtrByteSize;
6370       }
6371       if (!IsFastCall)
6372         ArgOffset += PtrByteSize;
6373       break;
6374     case MVT::f32:
6375     case MVT::f64: {
6376       // These can be scalar arguments or elements of a float array type
6377       // passed directly.  The latter are used to implement ELFv2 homogenous
6378       // float aggregates.
6379 
6380       // Named arguments go into FPRs first, and once they overflow, the
6381       // remaining arguments go into GPRs and then the parameter save area.
6382       // Unnamed arguments for vararg functions always go to GPRs and
6383       // then the parameter save area.  For now, put all arguments to vararg
6384       // routines always in both locations (FPR *and* GPR or stack slot).
6385       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6386       bool NeededLoad = false;
6387 
6388       // First load the argument into the next available FPR.
6389       if (FPR_idx != NumFPRs)
6390         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6391 
6392       // Next, load the argument into GPR or stack slot if needed.
6393       if (!NeedGPROrStack)
6394         ;
6395       else if (GPR_idx != NumGPRs && !IsFastCall) {
6396         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6397         // once we support fp <-> gpr moves.
6398 
6399         // In the non-vararg case, this can only ever happen in the
6400         // presence of f32 array types, since otherwise we never run
6401         // out of FPRs before running out of GPRs.
6402         SDValue ArgVal;
6403 
6404         // Double values are always passed in a single GPR.
6405         if (Arg.getValueType() != MVT::f32) {
6406           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6407 
6408         // Non-array float values are extended and passed in a GPR.
6409         } else if (!Flags.isInConsecutiveRegs()) {
6410           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6411           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6412 
6413         // If we have an array of floats, we collect every odd element
6414         // together with its predecessor into one GPR.
6415         } else if (ArgOffset % PtrByteSize != 0) {
6416           SDValue Lo, Hi;
6417           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6418           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6419           if (!isLittleEndian)
6420             std::swap(Lo, Hi);
6421           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6422 
6423         // The final element, if even, goes into the first half of a GPR.
6424         } else if (Flags.isInConsecutiveRegsLast()) {
6425           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6426           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6427           if (!isLittleEndian)
6428             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6429                                  DAG.getConstant(32, dl, MVT::i32));
6430 
6431         // Non-final even elements are skipped; they will be handled
6432         // together the with subsequent argument on the next go-around.
6433         } else
6434           ArgVal = SDValue();
6435 
6436         if (ArgVal.getNode())
6437           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6438       } else {
6439         if (IsFastCall)
6440           ComputePtrOff();
6441 
6442         // Single-precision floating-point values are mapped to the
6443         // second (rightmost) word of the stack doubleword.
6444         if (Arg.getValueType() == MVT::f32 &&
6445             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6446           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6447           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6448         }
6449 
6450         assert(HasParameterArea &&
6451                "Parameter area must exist to pass an argument in memory.");
6452         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6453                          true, CFlags.IsTailCall, false, MemOpChains,
6454                          TailCallArguments, dl);
6455 
6456         NeededLoad = true;
6457       }
6458       // When passing an array of floats, the array occupies consecutive
6459       // space in the argument area; only round up to the next doubleword
6460       // at the end of the array.  Otherwise, each float takes 8 bytes.
6461       if (!IsFastCall || NeededLoad) {
6462         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6463                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6464         if (Flags.isInConsecutiveRegsLast())
6465           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6466       }
6467       break;
6468     }
6469     case MVT::v4f32:
6470     case MVT::v4i32:
6471     case MVT::v8i16:
6472     case MVT::v16i8:
6473     case MVT::v2f64:
6474     case MVT::v2i64:
6475     case MVT::v1i128:
6476     case MVT::f128:
6477       if (!Subtarget.hasQPX()) {
6478       // These can be scalar arguments or elements of a vector array type
6479       // passed directly.  The latter are used to implement ELFv2 homogenous
6480       // vector aggregates.
6481 
6482       // For a varargs call, named arguments go into VRs or on the stack as
6483       // usual; unnamed arguments always go to the stack or the corresponding
6484       // GPRs when within range.  For now, we always put the value in both
6485       // locations (or even all three).
6486       if (CFlags.IsVarArg) {
6487         assert(HasParameterArea &&
6488                "Parameter area must exist if we have a varargs call.");
6489         // We could elide this store in the case where the object fits
6490         // entirely in R registers.  Maybe later.
6491         SDValue Store =
6492             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6493         MemOpChains.push_back(Store);
6494         if (VR_idx != NumVRs) {
6495           SDValue Load =
6496               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6497           MemOpChains.push_back(Load.getValue(1));
6498           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6499         }
6500         ArgOffset += 16;
6501         for (unsigned i=0; i<16; i+=PtrByteSize) {
6502           if (GPR_idx == NumGPRs)
6503             break;
6504           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6505                                    DAG.getConstant(i, dl, PtrVT));
6506           SDValue Load =
6507               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6508           MemOpChains.push_back(Load.getValue(1));
6509           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6510         }
6511         break;
6512       }
6513 
6514       // Non-varargs Altivec params go into VRs or on the stack.
6515       if (VR_idx != NumVRs) {
6516         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6517       } else {
6518         if (IsFastCall)
6519           ComputePtrOff();
6520 
6521         assert(HasParameterArea &&
6522                "Parameter area must exist to pass an argument in memory.");
6523         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6524                          true, CFlags.IsTailCall, true, MemOpChains,
6525                          TailCallArguments, dl);
6526         if (IsFastCall)
6527           ArgOffset += 16;
6528       }
6529 
6530       if (!IsFastCall)
6531         ArgOffset += 16;
6532       break;
6533       } // not QPX
6534 
6535       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6536              "Invalid QPX parameter type");
6537 
6538       LLVM_FALLTHROUGH;
6539     case MVT::v4f64:
6540     case MVT::v4i1: {
6541       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6542       if (CFlags.IsVarArg) {
6543         assert(HasParameterArea &&
6544                "Parameter area must exist if we have a varargs call.");
6545         // We could elide this store in the case where the object fits
6546         // entirely in R registers.  Maybe later.
6547         SDValue Store =
6548             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6549         MemOpChains.push_back(Store);
6550         if (QFPR_idx != NumQFPRs) {
6551           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6552                                      PtrOff, MachinePointerInfo());
6553           MemOpChains.push_back(Load.getValue(1));
6554           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6555         }
6556         ArgOffset += (IsF32 ? 16 : 32);
6557         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6558           if (GPR_idx == NumGPRs)
6559             break;
6560           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6561                                    DAG.getConstant(i, dl, PtrVT));
6562           SDValue Load =
6563               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6564           MemOpChains.push_back(Load.getValue(1));
6565           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6566         }
6567         break;
6568       }
6569 
6570       // Non-varargs QPX params go into registers or on the stack.
6571       if (QFPR_idx != NumQFPRs) {
6572         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6573       } else {
6574         if (IsFastCall)
6575           ComputePtrOff();
6576 
6577         assert(HasParameterArea &&
6578                "Parameter area must exist to pass an argument in memory.");
6579         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6580                          true, CFlags.IsTailCall, true, MemOpChains,
6581                          TailCallArguments, dl);
6582         if (IsFastCall)
6583           ArgOffset += (IsF32 ? 16 : 32);
6584       }
6585 
6586       if (!IsFastCall)
6587         ArgOffset += (IsF32 ? 16 : 32);
6588       break;
6589       }
6590     }
6591   }
6592 
6593   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6594          "mismatch in size of parameter area");
6595   (void)NumBytesActuallyUsed;
6596 
6597   if (!MemOpChains.empty())
6598     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6599 
6600   // Check if this is an indirect call (MTCTR/BCTRL).
6601   // See prepareDescriptorIndirectCall and buildCallOperands for more
6602   // information about calls through function pointers in the 64-bit SVR4 ABI.
6603   if (CFlags.IsIndirect) {
6604     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6605     // caller in the TOC save area.
6606     if (isTOCSaveRestoreRequired(Subtarget)) {
6607       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6608       // Load r2 into a virtual register and store it to the TOC save area.
6609       setUsesTOCBasePtr(DAG);
6610       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6611       // TOC save area offset.
6612       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6613       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6614       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6615       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6616                            MachinePointerInfo::getStack(
6617                                DAG.getMachineFunction(), TOCSaveOffset));
6618     }
6619     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6620     // This does not mean the MTCTR instruction must use R12; it's easier
6621     // to model this as an extra parameter, so do that.
6622     if (isELFv2ABI && !CFlags.IsPatchPoint)
6623       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6624   }
6625 
6626   // Build a sequence of copy-to-reg nodes chained together with token chain
6627   // and flag operands which copy the outgoing args into the appropriate regs.
6628   SDValue InFlag;
6629   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6630     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6631                              RegsToPass[i].second, InFlag);
6632     InFlag = Chain.getValue(1);
6633   }
6634 
6635   if (CFlags.IsTailCall && !IsSibCall)
6636     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6637                     TailCallArguments);
6638 
6639   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6640                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6641 }
6642 
6643 SDValue PPCTargetLowering::LowerCall_Darwin(
6644     SDValue Chain, SDValue Callee, CallFlags CFlags,
6645     const SmallVectorImpl<ISD::OutputArg> &Outs,
6646     const SmallVectorImpl<SDValue> &OutVals,
6647     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6648     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6649     const CallBase *CB) const {
6650   unsigned NumOps = Outs.size();
6651 
6652   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6653   bool isPPC64 = PtrVT == MVT::i64;
6654   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6655 
6656   MachineFunction &MF = DAG.getMachineFunction();
6657 
6658   // Mark this function as potentially containing a function that contains a
6659   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6660   // and restoring the callers stack pointer in this functions epilog. This is
6661   // done because by tail calling the called function might overwrite the value
6662   // in this function's (MF) stack pointer stack slot 0(SP).
6663   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6664       CFlags.CallConv == CallingConv::Fast)
6665     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6666 
6667   // Count how many bytes are to be pushed on the stack, including the linkage
6668   // area, and parameter passing area.  We start with 24/48 bytes, which is
6669   // prereserved space for [SP][CR][LR][3 x unused].
6670   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6671   unsigned NumBytes = LinkageSize;
6672 
6673   // Add up all the space actually used.
6674   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6675   // they all go in registers, but we must reserve stack space for them for
6676   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6677   // assigned stack space in order, with padding so Altivec parameters are
6678   // 16-byte aligned.
6679   unsigned nAltivecParamsAtEnd = 0;
6680   for (unsigned i = 0; i != NumOps; ++i) {
6681     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6682     EVT ArgVT = Outs[i].VT;
6683     // Varargs Altivec parameters are padded to a 16 byte boundary.
6684     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6685         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6686         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6687       if (!CFlags.IsVarArg && !isPPC64) {
6688         // Non-varargs Altivec parameters go after all the non-Altivec
6689         // parameters; handle those later so we know how much padding we need.
6690         nAltivecParamsAtEnd++;
6691         continue;
6692       }
6693       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6694       NumBytes = ((NumBytes+15)/16)*16;
6695     }
6696     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6697   }
6698 
6699   // Allow for Altivec parameters at the end, if needed.
6700   if (nAltivecParamsAtEnd) {
6701     NumBytes = ((NumBytes+15)/16)*16;
6702     NumBytes += 16*nAltivecParamsAtEnd;
6703   }
6704 
6705   // The prolog code of the callee may store up to 8 GPR argument registers to
6706   // the stack, allowing va_start to index over them in memory if its varargs.
6707   // Because we cannot tell if this is needed on the caller side, we have to
6708   // conservatively assume that it is needed.  As such, make sure we have at
6709   // least enough stack space for the caller to store the 8 GPRs.
6710   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6711 
6712   // Tail call needs the stack to be aligned.
6713   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6714       CFlags.CallConv == CallingConv::Fast)
6715     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6716 
6717   // Calculate by how many bytes the stack has to be adjusted in case of tail
6718   // call optimization.
6719   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6720 
6721   // To protect arguments on the stack from being clobbered in a tail call,
6722   // force all the loads to happen before doing any other lowering.
6723   if (CFlags.IsTailCall)
6724     Chain = DAG.getStackArgumentTokenFactor(Chain);
6725 
6726   // Adjust the stack pointer for the new arguments...
6727   // These operations are automatically eliminated by the prolog/epilog pass
6728   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6729   SDValue CallSeqStart = Chain;
6730 
6731   // Load the return address and frame pointer so it can be move somewhere else
6732   // later.
6733   SDValue LROp, FPOp;
6734   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6735 
6736   // Set up a copy of the stack pointer for use loading and storing any
6737   // arguments that may not fit in the registers available for argument
6738   // passing.
6739   SDValue StackPtr;
6740   if (isPPC64)
6741     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6742   else
6743     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6744 
6745   // Figure out which arguments are going to go in registers, and which in
6746   // memory.  Also, if this is a vararg function, floating point operations
6747   // must be stored to our stack, and loaded into integer regs as well, if
6748   // any integer regs are available for argument passing.
6749   unsigned ArgOffset = LinkageSize;
6750   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6751 
6752   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6753     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6754     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6755   };
6756   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6757     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6758     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6759   };
6760   static const MCPhysReg VR[] = {
6761     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6762     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6763   };
6764   const unsigned NumGPRs = array_lengthof(GPR_32);
6765   const unsigned NumFPRs = 13;
6766   const unsigned NumVRs  = array_lengthof(VR);
6767 
6768   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6769 
6770   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6771   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6772 
6773   SmallVector<SDValue, 8> MemOpChains;
6774   for (unsigned i = 0; i != NumOps; ++i) {
6775     SDValue Arg = OutVals[i];
6776     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6777 
6778     // PtrOff will be used to store the current argument to the stack if a
6779     // register cannot be found for it.
6780     SDValue PtrOff;
6781 
6782     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6783 
6784     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6785 
6786     // On PPC64, promote integers to 64-bit values.
6787     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6788       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6789       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6790       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6791     }
6792 
6793     // FIXME memcpy is used way more than necessary.  Correctness first.
6794     // Note: "by value" is code for passing a structure by value, not
6795     // basic types.
6796     if (Flags.isByVal()) {
6797       unsigned Size = Flags.getByValSize();
6798       // Very small objects are passed right-justified.  Everything else is
6799       // passed left-justified.
6800       if (Size==1 || Size==2) {
6801         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6802         if (GPR_idx != NumGPRs) {
6803           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6804                                         MachinePointerInfo(), VT);
6805           MemOpChains.push_back(Load.getValue(1));
6806           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6807 
6808           ArgOffset += PtrByteSize;
6809         } else {
6810           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6811                                           PtrOff.getValueType());
6812           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6813           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6814                                                             CallSeqStart,
6815                                                             Flags, DAG, dl);
6816           ArgOffset += PtrByteSize;
6817         }
6818         continue;
6819       }
6820       // Copy entire object into memory.  There are cases where gcc-generated
6821       // code assumes it is there, even if it could be put entirely into
6822       // registers.  (This is not what the doc says.)
6823       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6824                                                         CallSeqStart,
6825                                                         Flags, DAG, dl);
6826 
6827       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6828       // copy the pieces of the object that fit into registers from the
6829       // parameter save area.
6830       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6831         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6832         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6833         if (GPR_idx != NumGPRs) {
6834           SDValue Load =
6835               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6836           MemOpChains.push_back(Load.getValue(1));
6837           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6838           ArgOffset += PtrByteSize;
6839         } else {
6840           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6841           break;
6842         }
6843       }
6844       continue;
6845     }
6846 
6847     switch (Arg.getSimpleValueType().SimpleTy) {
6848     default: llvm_unreachable("Unexpected ValueType for argument!");
6849     case MVT::i1:
6850     case MVT::i32:
6851     case MVT::i64:
6852       if (GPR_idx != NumGPRs) {
6853         if (Arg.getValueType() == MVT::i1)
6854           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6855 
6856         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6857       } else {
6858         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6859                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6860                          TailCallArguments, dl);
6861       }
6862       ArgOffset += PtrByteSize;
6863       break;
6864     case MVT::f32:
6865     case MVT::f64:
6866       if (FPR_idx != NumFPRs) {
6867         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6868 
6869         if (CFlags.IsVarArg) {
6870           SDValue Store =
6871               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6872           MemOpChains.push_back(Store);
6873 
6874           // Float varargs are always shadowed in available integer registers
6875           if (GPR_idx != NumGPRs) {
6876             SDValue Load =
6877                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6878             MemOpChains.push_back(Load.getValue(1));
6879             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6880           }
6881           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6882             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6883             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6884             SDValue Load =
6885                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6886             MemOpChains.push_back(Load.getValue(1));
6887             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6888           }
6889         } else {
6890           // If we have any FPRs remaining, we may also have GPRs remaining.
6891           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6892           // GPRs.
6893           if (GPR_idx != NumGPRs)
6894             ++GPR_idx;
6895           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6896               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6897             ++GPR_idx;
6898         }
6899       } else
6900         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6901                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6902                          TailCallArguments, dl);
6903       if (isPPC64)
6904         ArgOffset += 8;
6905       else
6906         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6907       break;
6908     case MVT::v4f32:
6909     case MVT::v4i32:
6910     case MVT::v8i16:
6911     case MVT::v16i8:
6912       if (CFlags.IsVarArg) {
6913         // These go aligned on the stack, or in the corresponding R registers
6914         // when within range.  The Darwin PPC ABI doc claims they also go in
6915         // V registers; in fact gcc does this only for arguments that are
6916         // prototyped, not for those that match the ...  We do it for all
6917         // arguments, seems to work.
6918         while (ArgOffset % 16 !=0) {
6919           ArgOffset += PtrByteSize;
6920           if (GPR_idx != NumGPRs)
6921             GPR_idx++;
6922         }
6923         // We could elide this store in the case where the object fits
6924         // entirely in R registers.  Maybe later.
6925         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6926                              DAG.getConstant(ArgOffset, dl, PtrVT));
6927         SDValue Store =
6928             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6929         MemOpChains.push_back(Store);
6930         if (VR_idx != NumVRs) {
6931           SDValue Load =
6932               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6933           MemOpChains.push_back(Load.getValue(1));
6934           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6935         }
6936         ArgOffset += 16;
6937         for (unsigned i=0; i<16; i+=PtrByteSize) {
6938           if (GPR_idx == NumGPRs)
6939             break;
6940           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6941                                    DAG.getConstant(i, dl, PtrVT));
6942           SDValue Load =
6943               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6944           MemOpChains.push_back(Load.getValue(1));
6945           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6946         }
6947         break;
6948       }
6949 
6950       // Non-varargs Altivec params generally go in registers, but have
6951       // stack space allocated at the end.
6952       if (VR_idx != NumVRs) {
6953         // Doesn't have GPR space allocated.
6954         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6955       } else if (nAltivecParamsAtEnd==0) {
6956         // We are emitting Altivec params in order.
6957         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6958                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6959                          TailCallArguments, dl);
6960         ArgOffset += 16;
6961       }
6962       break;
6963     }
6964   }
6965   // If all Altivec parameters fit in registers, as they usually do,
6966   // they get stack space following the non-Altivec parameters.  We
6967   // don't track this here because nobody below needs it.
6968   // If there are more Altivec parameters than fit in registers emit
6969   // the stores here.
6970   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6971     unsigned j = 0;
6972     // Offset is aligned; skip 1st 12 params which go in V registers.
6973     ArgOffset = ((ArgOffset+15)/16)*16;
6974     ArgOffset += 12*16;
6975     for (unsigned i = 0; i != NumOps; ++i) {
6976       SDValue Arg = OutVals[i];
6977       EVT ArgType = Outs[i].VT;
6978       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6979           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6980         if (++j > NumVRs) {
6981           SDValue PtrOff;
6982           // We are emitting Altivec params in order.
6983           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6984                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6985                            TailCallArguments, dl);
6986           ArgOffset += 16;
6987         }
6988       }
6989     }
6990   }
6991 
6992   if (!MemOpChains.empty())
6993     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6994 
6995   // On Darwin, R12 must contain the address of an indirect callee.  This does
6996   // not mean the MTCTR instruction must use R12; it's easier to model this as
6997   // an extra parameter, so do that.
6998   if (CFlags.IsIndirect) {
6999     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7000     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
7001                                                    PPC::R12), Callee));
7002   }
7003 
7004   // Build a sequence of copy-to-reg nodes chained together with token chain
7005   // and flag operands which copy the outgoing args into the appropriate regs.
7006   SDValue InFlag;
7007   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
7008     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
7009                              RegsToPass[i].second, InFlag);
7010     InFlag = Chain.getValue(1);
7011   }
7012 
7013   if (CFlags.IsTailCall)
7014     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
7015                     TailCallArguments);
7016 
7017   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7018                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7019 }
7020 
7021 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
7022                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
7023                    CCState &State) {
7024 
7025   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
7026       State.getMachineFunction().getSubtarget());
7027   const bool IsPPC64 = Subtarget.isPPC64();
7028   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
7029   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
7030 
7031   assert((!ValVT.isInteger() ||
7032           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
7033          "Integer argument exceeds register size: should have been legalized");
7034 
7035   if (ValVT == MVT::f128)
7036     report_fatal_error("f128 is unimplemented on AIX.");
7037 
7038   if (ArgFlags.isNest())
7039     report_fatal_error("Nest arguments are unimplemented.");
7040 
7041   if (ValVT.isVector() || LocVT.isVector())
7042     report_fatal_error("Vector arguments are unimplemented on AIX.");
7043 
7044   static const MCPhysReg GPR_32[] = {// 32-bit registers.
7045                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7046                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7047   static const MCPhysReg GPR_64[] = {// 64-bit registers.
7048                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7049                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7050 
7051   if (ArgFlags.isByVal()) {
7052     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
7053       report_fatal_error("Pass-by-value arguments with alignment greater than "
7054                          "register width are not supported.");
7055 
7056     const unsigned ByValSize = ArgFlags.getByValSize();
7057 
7058     // An empty aggregate parameter takes up no storage and no registers,
7059     // but needs a MemLoc for a stack slot for the formal arguments side.
7060     if (ByValSize == 0) {
7061       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7062                                        State.getNextStackOffset(), RegVT,
7063                                        LocInfo));
7064       return false;
7065     }
7066 
7067     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
7068     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
7069     for (const unsigned E = Offset + StackSize; Offset < E;
7070          Offset += PtrAlign.value()) {
7071       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7072         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7073       else {
7074         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7075                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
7076                                          LocInfo));
7077         break;
7078       }
7079     }
7080     return false;
7081   }
7082 
7083   // Arguments always reserve parameter save area.
7084   switch (ValVT.SimpleTy) {
7085   default:
7086     report_fatal_error("Unhandled value type for argument.");
7087   case MVT::i64:
7088     // i64 arguments should have been split to i32 for PPC32.
7089     assert(IsPPC64 && "PPC32 should have split i64 values.");
7090     LLVM_FALLTHROUGH;
7091   case MVT::i1:
7092   case MVT::i32: {
7093     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
7094     // AIX integer arguments are always passed in register width.
7095     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
7096       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
7097                                   : CCValAssign::LocInfo::ZExt;
7098     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7099       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7100     else
7101       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
7102 
7103     return false;
7104   }
7105   case MVT::f32:
7106   case MVT::f64: {
7107     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7108     const unsigned StoreSize = LocVT.getStoreSize();
7109     // Floats are always 4-byte aligned in the PSA on AIX.
7110     // This includes f64 in 64-bit mode for ABI compatibility.
7111     const unsigned Offset =
7112         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
7113     unsigned FReg = State.AllocateReg(FPR);
7114     if (FReg)
7115       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7116 
7117     // Reserve and initialize GPRs or initialize the PSA as required.
7118     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
7119       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7120         assert(FReg && "An FPR should be available when a GPR is reserved.");
7121         if (State.isVarArg()) {
7122           // Successfully reserved GPRs are only initialized for vararg calls.
7123           // Custom handling is required for:
7124           //   f64 in PPC32 needs to be split into 2 GPRs.
7125           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7126           State.addLoc(
7127               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7128         }
7129       } else {
7130         // If there are insufficient GPRs, the PSA needs to be initialized.
7131         // Initialization occurs even if an FPR was initialized for
7132         // compatibility with the AIX XL compiler. The full memory for the
7133         // argument will be initialized even if a prior word is saved in GPR.
7134         // A custom memLoc is used when the argument also passes in FPR so
7135         // that the callee handling can skip over it easily.
7136         State.addLoc(
7137             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7138                                              LocInfo)
7139                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7140         break;
7141       }
7142     }
7143 
7144     return false;
7145   }
7146   }
7147   return true;
7148 }
7149 
7150 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7151                                                     bool IsPPC64) {
7152   assert((IsPPC64 || SVT != MVT::i64) &&
7153          "i64 should have been split for 32-bit codegen.");
7154 
7155   switch (SVT) {
7156   default:
7157     report_fatal_error("Unexpected value type for formal argument");
7158   case MVT::i1:
7159   case MVT::i32:
7160   case MVT::i64:
7161     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7162   case MVT::f32:
7163     return &PPC::F4RCRegClass;
7164   case MVT::f64:
7165     return &PPC::F8RCRegClass;
7166   }
7167 }
7168 
7169 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7170                                         SelectionDAG &DAG, SDValue ArgValue,
7171                                         MVT LocVT, const SDLoc &dl) {
7172   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7173   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7174 
7175   if (Flags.isSExt())
7176     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7177                            DAG.getValueType(ValVT));
7178   else if (Flags.isZExt())
7179     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7180                            DAG.getValueType(ValVT));
7181 
7182   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7183 }
7184 
7185 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7186   const unsigned LASize = FL->getLinkageSize();
7187 
7188   if (PPC::GPRCRegClass.contains(Reg)) {
7189     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7190            "Reg must be a valid argument register!");
7191     return LASize + 4 * (Reg - PPC::R3);
7192   }
7193 
7194   if (PPC::G8RCRegClass.contains(Reg)) {
7195     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7196            "Reg must be a valid argument register!");
7197     return LASize + 8 * (Reg - PPC::X3);
7198   }
7199 
7200   llvm_unreachable("Only general purpose registers expected.");
7201 }
7202 
7203 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7204     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7205     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7206     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7207 
7208   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7209           CallConv == CallingConv::Fast) &&
7210          "Unexpected calling convention!");
7211 
7212   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7213     report_fatal_error("Tail call support is unimplemented on AIX.");
7214 
7215   if (useSoftFloat())
7216     report_fatal_error("Soft float support is unimplemented on AIX.");
7217 
7218   const PPCSubtarget &Subtarget =
7219       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7220   if (Subtarget.hasQPX())
7221     report_fatal_error("QPX support is not supported on AIX.");
7222 
7223   const bool IsPPC64 = Subtarget.isPPC64();
7224   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7225 
7226   // Assign locations to all of the incoming arguments.
7227   SmallVector<CCValAssign, 16> ArgLocs;
7228   MachineFunction &MF = DAG.getMachineFunction();
7229   MachineFrameInfo &MFI = MF.getFrameInfo();
7230   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7231 
7232   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7233   // Reserve space for the linkage area on the stack.
7234   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7235   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7236   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7237 
7238   SmallVector<SDValue, 8> MemOps;
7239 
7240   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7241     CCValAssign &VA = ArgLocs[I++];
7242     MVT LocVT = VA.getLocVT();
7243     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7244 
7245     // For compatibility with the AIX XL compiler, the float args in the
7246     // parameter save area are initialized even if the argument is available
7247     // in register.  The caller is required to initialize both the register
7248     // and memory, however, the callee can choose to expect it in either.
7249     // The memloc is dismissed here because the argument is retrieved from
7250     // the register.
7251     if (VA.isMemLoc() && VA.needsCustom())
7252       continue;
7253 
7254     if (Flags.isByVal() && VA.isMemLoc()) {
7255       const unsigned Size =
7256           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7257                   PtrByteSize);
7258       const int FI = MF.getFrameInfo().CreateFixedObject(
7259           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7260           /* IsAliased */ true);
7261       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7262       InVals.push_back(FIN);
7263 
7264       continue;
7265     }
7266 
7267     if (Flags.isByVal()) {
7268       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7269 
7270       const MCPhysReg ArgReg = VA.getLocReg();
7271       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7272 
7273       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7274         report_fatal_error("Over aligned byvals not supported yet.");
7275 
7276       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7277       const int FI = MF.getFrameInfo().CreateFixedObject(
7278           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7279           /* IsAliased */ true);
7280       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7281       InVals.push_back(FIN);
7282 
7283       // Add live ins for all the RegLocs for the same ByVal.
7284       const TargetRegisterClass *RegClass =
7285           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7286 
7287       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7288                                                unsigned Offset) {
7289         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7290         // Since the callers side has left justified the aggregate in the
7291         // register, we can simply store the entire register into the stack
7292         // slot.
7293         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7294         // The store to the fixedstack object is needed becuase accessing a
7295         // field of the ByVal will use a gep and load. Ideally we will optimize
7296         // to extracting the value from the register directly, and elide the
7297         // stores when the arguments address is not taken, but that will need to
7298         // be future work.
7299         SDValue Store =
7300             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7301                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7302                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7303 
7304         MemOps.push_back(Store);
7305       };
7306 
7307       unsigned Offset = 0;
7308       HandleRegLoc(VA.getLocReg(), Offset);
7309       Offset += PtrByteSize;
7310       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7311            Offset += PtrByteSize) {
7312         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7313                "RegLocs should be for ByVal argument.");
7314 
7315         const CCValAssign RL = ArgLocs[I++];
7316         HandleRegLoc(RL.getLocReg(), Offset);
7317       }
7318 
7319       if (Offset != StackSize) {
7320         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7321                "Expected MemLoc for remaining bytes.");
7322         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7323         // Consume the MemLoc.The InVal has already been emitted, so nothing
7324         // more needs to be done.
7325         ++I;
7326       }
7327 
7328       continue;
7329     }
7330 
7331     EVT ValVT = VA.getValVT();
7332     if (VA.isRegLoc() && !VA.needsCustom()) {
7333       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7334       unsigned VReg =
7335           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7336       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7337       if (ValVT.isScalarInteger() &&
7338           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7339         ArgValue =
7340             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7341       }
7342       InVals.push_back(ArgValue);
7343       continue;
7344     }
7345     if (VA.isMemLoc()) {
7346       const unsigned LocSize = LocVT.getStoreSize();
7347       const unsigned ValSize = ValVT.getStoreSize();
7348       assert((ValSize <= LocSize) &&
7349              "Object size is larger than size of MemLoc");
7350       int CurArgOffset = VA.getLocMemOffset();
7351       // Objects are right-justified because AIX is big-endian.
7352       if (LocSize > ValSize)
7353         CurArgOffset += LocSize - ValSize;
7354       // Potential tail calls could cause overwriting of argument stack slots.
7355       const bool IsImmutable =
7356           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7357             (CallConv == CallingConv::Fast));
7358       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7359       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7360       SDValue ArgValue =
7361           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7362       InVals.push_back(ArgValue);
7363       continue;
7364     }
7365   }
7366 
7367   // On AIX a minimum of 8 words is saved to the parameter save area.
7368   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7369   // Area that is at least reserved in the caller of this function.
7370   unsigned CallerReservedArea =
7371       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7372 
7373   // Set the size that is at least reserved in caller of this function. Tail
7374   // call optimized function's reserved stack space needs to be aligned so
7375   // that taking the difference between two stack areas will result in an
7376   // aligned stack.
7377   CallerReservedArea =
7378       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7379   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7380   FuncInfo->setMinReservedArea(CallerReservedArea);
7381 
7382   if (isVarArg) {
7383     FuncInfo->setVarArgsFrameIndex(
7384         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7385     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7386 
7387     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7388                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7389 
7390     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7391                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7392     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7393 
7394     // The fixed integer arguments of a variadic function are stored to the
7395     // VarArgsFrameIndex on the stack so that they may be loaded by
7396     // dereferencing the result of va_next.
7397     for (unsigned GPRIndex =
7398              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7399          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7400 
7401       const unsigned VReg =
7402           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7403                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7404 
7405       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7406       SDValue Store =
7407           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7408       MemOps.push_back(Store);
7409       // Increment the address for the next argument to store.
7410       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7411       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7412     }
7413   }
7414 
7415   if (!MemOps.empty())
7416     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7417 
7418   return Chain;
7419 }
7420 
7421 SDValue PPCTargetLowering::LowerCall_AIX(
7422     SDValue Chain, SDValue Callee, CallFlags CFlags,
7423     const SmallVectorImpl<ISD::OutputArg> &Outs,
7424     const SmallVectorImpl<SDValue> &OutVals,
7425     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7426     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7427     const CallBase *CB) const {
7428 
7429   assert((CFlags.CallConv == CallingConv::C ||
7430           CFlags.CallConv == CallingConv::Cold ||
7431           CFlags.CallConv == CallingConv::Fast) &&
7432          "Unexpected calling convention!");
7433 
7434   if (CFlags.IsPatchPoint)
7435     report_fatal_error("This call type is unimplemented on AIX.");
7436 
7437   const PPCSubtarget& Subtarget =
7438       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7439   if (Subtarget.hasQPX())
7440     report_fatal_error("QPX is not supported on AIX.");
7441   if (Subtarget.hasAltivec())
7442     report_fatal_error("Altivec support is unimplemented on AIX.");
7443 
7444   MachineFunction &MF = DAG.getMachineFunction();
7445   SmallVector<CCValAssign, 16> ArgLocs;
7446   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7447                  *DAG.getContext());
7448 
7449   // Reserve space for the linkage save area (LSA) on the stack.
7450   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7451   //   [SP][CR][LR][2 x reserved][TOC].
7452   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7453   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7454   const bool IsPPC64 = Subtarget.isPPC64();
7455   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7456   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7457   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7458   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7459 
7460   // The prolog code of the callee may store up to 8 GPR argument registers to
7461   // the stack, allowing va_start to index over them in memory if the callee
7462   // is variadic.
7463   // Because we cannot tell if this is needed on the caller side, we have to
7464   // conservatively assume that it is needed.  As such, make sure we have at
7465   // least enough stack space for the caller to store the 8 GPRs.
7466   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7467   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7468                                      CCInfo.getNextStackOffset());
7469 
7470   // Adjust the stack pointer for the new arguments...
7471   // These operations are automatically eliminated by the prolog/epilog pass.
7472   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7473   SDValue CallSeqStart = Chain;
7474 
7475   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7476   SmallVector<SDValue, 8> MemOpChains;
7477 
7478   // Set up a copy of the stack pointer for loading and storing any
7479   // arguments that may not fit in the registers available for argument
7480   // passing.
7481   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7482                                    : DAG.getRegister(PPC::R1, MVT::i32);
7483 
7484   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7485     const unsigned ValNo = ArgLocs[I].getValNo();
7486     SDValue Arg = OutVals[ValNo];
7487     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7488 
7489     if (Flags.isByVal()) {
7490       const unsigned ByValSize = Flags.getByValSize();
7491 
7492       // Nothing to do for zero-sized ByVals on the caller side.
7493       if (!ByValSize) {
7494         ++I;
7495         continue;
7496       }
7497 
7498       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7499         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7500                               (LoadOffset != 0)
7501                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7502                                   : Arg,
7503                               MachinePointerInfo(), VT);
7504       };
7505 
7506       unsigned LoadOffset = 0;
7507 
7508       // Initialize registers, which are fully occupied by the by-val argument.
7509       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7510         SDValue Load = GetLoad(PtrVT, LoadOffset);
7511         MemOpChains.push_back(Load.getValue(1));
7512         LoadOffset += PtrByteSize;
7513         const CCValAssign &ByValVA = ArgLocs[I++];
7514         assert(ByValVA.getValNo() == ValNo &&
7515                "Unexpected location for pass-by-value argument.");
7516         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7517       }
7518 
7519       if (LoadOffset == ByValSize)
7520         continue;
7521 
7522       // There must be one more loc to handle the remainder.
7523       assert(ArgLocs[I].getValNo() == ValNo &&
7524              "Expected additional location for by-value argument.");
7525 
7526       if (ArgLocs[I].isMemLoc()) {
7527         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7528         const CCValAssign &ByValVA = ArgLocs[I++];
7529         ISD::ArgFlagsTy MemcpyFlags = Flags;
7530         // Only memcpy the bytes that don't pass in register.
7531         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7532         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7533             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7534                               : Arg,
7535             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7536             CallSeqStart, MemcpyFlags, DAG, dl);
7537         continue;
7538       }
7539 
7540       // Initialize the final register residue.
7541       // Any residue that occupies the final by-val arg register must be
7542       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7543       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7544       // 2 and 1 byte loads.
7545       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7546       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7547              "Unexpected register residue for by-value argument.");
7548       SDValue ResidueVal;
7549       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7550         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7551         const MVT VT =
7552             N == 1 ? MVT::i8
7553                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7554         SDValue Load = GetLoad(VT, LoadOffset);
7555         MemOpChains.push_back(Load.getValue(1));
7556         LoadOffset += N;
7557         Bytes += N;
7558 
7559         // By-val arguments are passed left-justfied in register.
7560         // Every load here needs to be shifted, otherwise a full register load
7561         // should have been used.
7562         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7563                "Unexpected load emitted during handling of pass-by-value "
7564                "argument.");
7565         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7566         EVT ShiftAmountTy =
7567             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7568         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7569         SDValue ShiftedLoad =
7570             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7571         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7572                                               ShiftedLoad)
7573                                 : ShiftedLoad;
7574       }
7575 
7576       const CCValAssign &ByValVA = ArgLocs[I++];
7577       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7578       continue;
7579     }
7580 
7581     CCValAssign &VA = ArgLocs[I++];
7582     const MVT LocVT = VA.getLocVT();
7583     const MVT ValVT = VA.getValVT();
7584 
7585     switch (VA.getLocInfo()) {
7586     default:
7587       report_fatal_error("Unexpected argument extension type.");
7588     case CCValAssign::Full:
7589       break;
7590     case CCValAssign::ZExt:
7591       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7592       break;
7593     case CCValAssign::SExt:
7594       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7595       break;
7596     }
7597 
7598     if (VA.isRegLoc() && !VA.needsCustom()) {
7599       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7600       continue;
7601     }
7602 
7603     if (VA.isMemLoc()) {
7604       SDValue PtrOff =
7605           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7606       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7607       MemOpChains.push_back(
7608           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7609 
7610       continue;
7611     }
7612 
7613     // Custom handling is used for GPR initializations for vararg float
7614     // arguments.
7615     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7616            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7617            "Unexpected register handling for calling convention.");
7618 
7619     SDValue ArgAsInt =
7620         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7621 
7622     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7623       // f32 in 32-bit GPR
7624       // f64 in 64-bit GPR
7625       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7626     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7627       // f32 in 64-bit GPR.
7628       RegsToPass.push_back(std::make_pair(
7629           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7630     else {
7631       // f64 in two 32-bit GPRs
7632       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7633       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7634              "Unexpected custom register for argument!");
7635       CCValAssign &GPR1 = VA;
7636       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7637                                      DAG.getConstant(32, dl, MVT::i8));
7638       RegsToPass.push_back(std::make_pair(
7639           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7640 
7641       if (I != E) {
7642         // If only 1 GPR was available, there will only be one custom GPR and
7643         // the argument will also pass in memory.
7644         CCValAssign &PeekArg = ArgLocs[I];
7645         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7646           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7647           CCValAssign &GPR2 = ArgLocs[I++];
7648           RegsToPass.push_back(std::make_pair(
7649               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7650         }
7651       }
7652     }
7653   }
7654 
7655   if (!MemOpChains.empty())
7656     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7657 
7658   // For indirect calls, we need to save the TOC base to the stack for
7659   // restoration after the call.
7660   if (CFlags.IsIndirect) {
7661     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7662     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7663     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7664     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7665     const unsigned TOCSaveOffset =
7666         Subtarget.getFrameLowering()->getTOCSaveOffset();
7667 
7668     setUsesTOCBasePtr(DAG);
7669     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7670     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7671     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7672     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7673     Chain = DAG.getStore(
7674         Val.getValue(1), dl, Val, AddPtr,
7675         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7676   }
7677 
7678   // Build a sequence of copy-to-reg nodes chained together with token chain
7679   // and flag operands which copy the outgoing args into the appropriate regs.
7680   SDValue InFlag;
7681   for (auto Reg : RegsToPass) {
7682     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7683     InFlag = Chain.getValue(1);
7684   }
7685 
7686   const int SPDiff = 0;
7687   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7688                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7689 }
7690 
7691 bool
7692 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7693                                   MachineFunction &MF, bool isVarArg,
7694                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7695                                   LLVMContext &Context) const {
7696   SmallVector<CCValAssign, 16> RVLocs;
7697   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7698   return CCInfo.CheckReturn(
7699       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7700                 ? RetCC_PPC_Cold
7701                 : RetCC_PPC);
7702 }
7703 
7704 SDValue
7705 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7706                                bool isVarArg,
7707                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7708                                const SmallVectorImpl<SDValue> &OutVals,
7709                                const SDLoc &dl, SelectionDAG &DAG) const {
7710   SmallVector<CCValAssign, 16> RVLocs;
7711   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7712                  *DAG.getContext());
7713   CCInfo.AnalyzeReturn(Outs,
7714                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7715                            ? RetCC_PPC_Cold
7716                            : RetCC_PPC);
7717 
7718   SDValue Flag;
7719   SmallVector<SDValue, 4> RetOps(1, Chain);
7720 
7721   // Copy the result values into the output registers.
7722   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7723     CCValAssign &VA = RVLocs[i];
7724     assert(VA.isRegLoc() && "Can only return in registers!");
7725 
7726     SDValue Arg = OutVals[RealResIdx];
7727 
7728     switch (VA.getLocInfo()) {
7729     default: llvm_unreachable("Unknown loc info!");
7730     case CCValAssign::Full: break;
7731     case CCValAssign::AExt:
7732       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7733       break;
7734     case CCValAssign::ZExt:
7735       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7736       break;
7737     case CCValAssign::SExt:
7738       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7739       break;
7740     }
7741     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7742       bool isLittleEndian = Subtarget.isLittleEndian();
7743       // Legalize ret f64 -> ret 2 x i32.
7744       SDValue SVal =
7745           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7746                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7747       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7748       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7749       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7750                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7751       Flag = Chain.getValue(1);
7752       VA = RVLocs[++i]; // skip ahead to next loc
7753       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7754     } else
7755       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7756     Flag = Chain.getValue(1);
7757     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7758   }
7759 
7760   RetOps[0] = Chain;  // Update chain.
7761 
7762   // Add the flag if we have it.
7763   if (Flag.getNode())
7764     RetOps.push_back(Flag);
7765 
7766   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7767 }
7768 
7769 SDValue
7770 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7771                                                 SelectionDAG &DAG) const {
7772   SDLoc dl(Op);
7773 
7774   // Get the correct type for integers.
7775   EVT IntVT = Op.getValueType();
7776 
7777   // Get the inputs.
7778   SDValue Chain = Op.getOperand(0);
7779   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7780   // Build a DYNAREAOFFSET node.
7781   SDValue Ops[2] = {Chain, FPSIdx};
7782   SDVTList VTs = DAG.getVTList(IntVT);
7783   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7784 }
7785 
7786 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7787                                              SelectionDAG &DAG) const {
7788   // When we pop the dynamic allocation we need to restore the SP link.
7789   SDLoc dl(Op);
7790 
7791   // Get the correct type for pointers.
7792   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7793 
7794   // Construct the stack pointer operand.
7795   bool isPPC64 = Subtarget.isPPC64();
7796   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7797   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7798 
7799   // Get the operands for the STACKRESTORE.
7800   SDValue Chain = Op.getOperand(0);
7801   SDValue SaveSP = Op.getOperand(1);
7802 
7803   // Load the old link SP.
7804   SDValue LoadLinkSP =
7805       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7806 
7807   // Restore the stack pointer.
7808   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7809 
7810   // Store the old link SP.
7811   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7812 }
7813 
7814 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7815   MachineFunction &MF = DAG.getMachineFunction();
7816   bool isPPC64 = Subtarget.isPPC64();
7817   EVT PtrVT = getPointerTy(MF.getDataLayout());
7818 
7819   // Get current frame pointer save index.  The users of this index will be
7820   // primarily DYNALLOC instructions.
7821   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7822   int RASI = FI->getReturnAddrSaveIndex();
7823 
7824   // If the frame pointer save index hasn't been defined yet.
7825   if (!RASI) {
7826     // Find out what the fix offset of the frame pointer save area.
7827     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7828     // Allocate the frame index for frame pointer save area.
7829     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7830     // Save the result.
7831     FI->setReturnAddrSaveIndex(RASI);
7832   }
7833   return DAG.getFrameIndex(RASI, PtrVT);
7834 }
7835 
7836 SDValue
7837 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7838   MachineFunction &MF = DAG.getMachineFunction();
7839   bool isPPC64 = Subtarget.isPPC64();
7840   EVT PtrVT = getPointerTy(MF.getDataLayout());
7841 
7842   // Get current frame pointer save index.  The users of this index will be
7843   // primarily DYNALLOC instructions.
7844   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7845   int FPSI = FI->getFramePointerSaveIndex();
7846 
7847   // If the frame pointer save index hasn't been defined yet.
7848   if (!FPSI) {
7849     // Find out what the fix offset of the frame pointer save area.
7850     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7851     // Allocate the frame index for frame pointer save area.
7852     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7853     // Save the result.
7854     FI->setFramePointerSaveIndex(FPSI);
7855   }
7856   return DAG.getFrameIndex(FPSI, PtrVT);
7857 }
7858 
7859 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7860                                                    SelectionDAG &DAG) const {
7861   // Get the inputs.
7862   SDValue Chain = Op.getOperand(0);
7863   SDValue Size  = Op.getOperand(1);
7864   SDLoc dl(Op);
7865 
7866   // Get the correct type for pointers.
7867   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7868   // Negate the size.
7869   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7870                                 DAG.getConstant(0, dl, PtrVT), Size);
7871   // Construct a node for the frame pointer save index.
7872   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7873   // Build a DYNALLOC node.
7874   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7875   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7876   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7877 }
7878 
7879 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7880                                                      SelectionDAG &DAG) const {
7881   MachineFunction &MF = DAG.getMachineFunction();
7882 
7883   bool isPPC64 = Subtarget.isPPC64();
7884   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7885 
7886   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7887   return DAG.getFrameIndex(FI, PtrVT);
7888 }
7889 
7890 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7891                                                SelectionDAG &DAG) const {
7892   SDLoc DL(Op);
7893   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7894                      DAG.getVTList(MVT::i32, MVT::Other),
7895                      Op.getOperand(0), Op.getOperand(1));
7896 }
7897 
7898 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7899                                                 SelectionDAG &DAG) const {
7900   SDLoc DL(Op);
7901   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7902                      Op.getOperand(0), Op.getOperand(1));
7903 }
7904 
7905 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7906   if (Op.getValueType().isVector())
7907     return LowerVectorLoad(Op, DAG);
7908 
7909   assert(Op.getValueType() == MVT::i1 &&
7910          "Custom lowering only for i1 loads");
7911 
7912   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7913 
7914   SDLoc dl(Op);
7915   LoadSDNode *LD = cast<LoadSDNode>(Op);
7916 
7917   SDValue Chain = LD->getChain();
7918   SDValue BasePtr = LD->getBasePtr();
7919   MachineMemOperand *MMO = LD->getMemOperand();
7920 
7921   SDValue NewLD =
7922       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7923                      BasePtr, MVT::i8, MMO);
7924   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7925 
7926   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7927   return DAG.getMergeValues(Ops, dl);
7928 }
7929 
7930 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7931   if (Op.getOperand(1).getValueType().isVector())
7932     return LowerVectorStore(Op, DAG);
7933 
7934   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7935          "Custom lowering only for i1 stores");
7936 
7937   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7938 
7939   SDLoc dl(Op);
7940   StoreSDNode *ST = cast<StoreSDNode>(Op);
7941 
7942   SDValue Chain = ST->getChain();
7943   SDValue BasePtr = ST->getBasePtr();
7944   SDValue Value = ST->getValue();
7945   MachineMemOperand *MMO = ST->getMemOperand();
7946 
7947   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7948                       Value);
7949   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7950 }
7951 
7952 // FIXME: Remove this once the ANDI glue bug is fixed:
7953 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7954   assert(Op.getValueType() == MVT::i1 &&
7955          "Custom lowering only for i1 results");
7956 
7957   SDLoc DL(Op);
7958   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7959 }
7960 
7961 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7962                                                SelectionDAG &DAG) const {
7963 
7964   // Implements a vector truncate that fits in a vector register as a shuffle.
7965   // We want to legalize vector truncates down to where the source fits in
7966   // a vector register (and target is therefore smaller than vector register
7967   // size).  At that point legalization will try to custom lower the sub-legal
7968   // result and get here - where we can contain the truncate as a single target
7969   // operation.
7970 
7971   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7972   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7973   //
7974   // We will implement it for big-endian ordering as this (where x denotes
7975   // undefined):
7976   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7977   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7978   //
7979   // The same operation in little-endian ordering will be:
7980   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7981   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7982 
7983   assert(Op.getValueType().isVector() && "Vector type expected.");
7984 
7985   SDLoc DL(Op);
7986   SDValue N1 = Op.getOperand(0);
7987   unsigned SrcSize = N1.getValueType().getSizeInBits();
7988   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7989   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7990 
7991   EVT TrgVT = Op.getValueType();
7992   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7993   EVT EltVT = TrgVT.getVectorElementType();
7994   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7995   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7996 
7997   // First list the elements we want to keep.
7998   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7999   SmallVector<int, 16> ShuffV;
8000   if (Subtarget.isLittleEndian())
8001     for (unsigned i = 0; i < TrgNumElts; ++i)
8002       ShuffV.push_back(i * SizeMult);
8003   else
8004     for (unsigned i = 1; i <= TrgNumElts; ++i)
8005       ShuffV.push_back(i * SizeMult - 1);
8006 
8007   // Populate the remaining elements with undefs.
8008   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8009     // ShuffV.push_back(i + WideNumElts);
8010     ShuffV.push_back(WideNumElts + 1);
8011 
8012   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
8013   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
8014 }
8015 
8016 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8017 /// possible.
8018 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8019   // Not FP? Not a fsel.
8020   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
8021       !Op.getOperand(2).getValueType().isFloatingPoint())
8022     return Op;
8023 
8024   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8025 
8026   EVT ResVT = Op.getValueType();
8027   EVT CmpVT = Op.getOperand(0).getValueType();
8028   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8029   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
8030   SDLoc dl(Op);
8031   SDNodeFlags Flags = Op.getNode()->getFlags();
8032 
8033   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
8034   // presence of infinities.
8035   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8036     switch (CC) {
8037     default:
8038       break;
8039     case ISD::SETOGT:
8040     case ISD::SETGT:
8041       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
8042     case ISD::SETOLT:
8043     case ISD::SETLT:
8044       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
8045     }
8046   }
8047 
8048   // We might be able to do better than this under some circumstances, but in
8049   // general, fsel-based lowering of select is a finite-math-only optimization.
8050   // For more information, see section F.3 of the 2.06 ISA specification.
8051   // With ISA 3.0
8052   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
8053       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
8054     return Op;
8055 
8056   // If the RHS of the comparison is a 0.0, we don't need to do the
8057   // subtraction at all.
8058   SDValue Sel1;
8059   if (isFloatingPointZero(RHS))
8060     switch (CC) {
8061     default: break;       // SETUO etc aren't handled by fsel.
8062     case ISD::SETNE:
8063       std::swap(TV, FV);
8064       LLVM_FALLTHROUGH;
8065     case ISD::SETEQ:
8066       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8067         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8068       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8069       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8070         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8071       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8072                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8073     case ISD::SETULT:
8074     case ISD::SETLT:
8075       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8076       LLVM_FALLTHROUGH;
8077     case ISD::SETOGE:
8078     case ISD::SETGE:
8079       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8080         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8081       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8082     case ISD::SETUGT:
8083     case ISD::SETGT:
8084       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8085       LLVM_FALLTHROUGH;
8086     case ISD::SETOLE:
8087     case ISD::SETLE:
8088       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8089         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8090       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8091                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8092     }
8093 
8094   SDValue Cmp;
8095   switch (CC) {
8096   default: break;       // SETUO etc aren't handled by fsel.
8097   case ISD::SETNE:
8098     std::swap(TV, FV);
8099     LLVM_FALLTHROUGH;
8100   case ISD::SETEQ:
8101     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8102     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8103       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8104     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8105     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8106       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8107     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8108                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8109   case ISD::SETULT:
8110   case ISD::SETLT:
8111     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8112     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8113       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8114     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8115   case ISD::SETOGE:
8116   case ISD::SETGE:
8117     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8118     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8119       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8120     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8121   case ISD::SETUGT:
8122   case ISD::SETGT:
8123     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8124     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8125       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8126     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8127   case ISD::SETOLE:
8128   case ISD::SETLE:
8129     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8130     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8131       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8132     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8133   }
8134   return Op;
8135 }
8136 
8137 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8138                                                SelectionDAG &DAG,
8139                                                const SDLoc &dl) const {
8140   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8141   SDValue Src = Op.getOperand(0);
8142   if (Src.getValueType() == MVT::f32)
8143     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8144 
8145   SDValue Tmp;
8146   switch (Op.getSimpleValueType().SimpleTy) {
8147   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8148   case MVT::i32:
8149     Tmp = DAG.getNode(
8150         Op.getOpcode() == ISD::FP_TO_SINT
8151             ? PPCISD::FCTIWZ
8152             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8153         dl, MVT::f64, Src);
8154     break;
8155   case MVT::i64:
8156     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8157            "i64 FP_TO_UINT is supported only with FPCVT");
8158     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8159                                                         PPCISD::FCTIDUZ,
8160                       dl, MVT::f64, Src);
8161     break;
8162   }
8163 
8164   // Convert the FP value to an int value through memory.
8165   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8166     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
8167   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8168   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8169   MachinePointerInfo MPI =
8170       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8171 
8172   // Emit a store to the stack slot.
8173   SDValue Chain;
8174   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8175   if (i32Stack) {
8176     MachineFunction &MF = DAG.getMachineFunction();
8177     Alignment = Align(4);
8178     MachineMemOperand *MMO =
8179         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8180     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
8181     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8182               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8183   } else
8184     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
8185 
8186   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8187   // add in a bias on big endian.
8188   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8189     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8190                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8191     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8192   }
8193 
8194   RLI.Chain = Chain;
8195   RLI.Ptr = FIPtr;
8196   RLI.MPI = MPI;
8197   RLI.Alignment = Alignment;
8198 }
8199 
8200 /// Custom lowers floating point to integer conversions to use
8201 /// the direct move instructions available in ISA 2.07 to avoid the
8202 /// need for load/store combinations.
8203 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8204                                                     SelectionDAG &DAG,
8205                                                     const SDLoc &dl) const {
8206   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8207   SDValue Src = Op.getOperand(0);
8208 
8209   if (Src.getValueType() == MVT::f32)
8210     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8211 
8212   SDValue Tmp;
8213   switch (Op.getSimpleValueType().SimpleTy) {
8214   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8215   case MVT::i32:
8216     Tmp = DAG.getNode(
8217         Op.getOpcode() == ISD::FP_TO_SINT
8218             ? PPCISD::FCTIWZ
8219             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8220         dl, MVT::f64, Src);
8221     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
8222     break;
8223   case MVT::i64:
8224     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8225            "i64 FP_TO_UINT is supported only with FPCVT");
8226     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8227                                                         PPCISD::FCTIDUZ,
8228                       dl, MVT::f64, Src);
8229     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
8230     break;
8231   }
8232   return Tmp;
8233 }
8234 
8235 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8236                                           const SDLoc &dl) const {
8237 
8238   // FP to INT conversions are legal for f128.
8239   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
8240     return Op;
8241 
8242   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8243   // PPC (the libcall is not available).
8244   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
8245     if (Op.getValueType() == MVT::i32) {
8246       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8247         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8248                                  MVT::f64, Op.getOperand(0),
8249                                  DAG.getIntPtrConstant(0, dl));
8250         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8251                                  MVT::f64, Op.getOperand(0),
8252                                  DAG.getIntPtrConstant(1, dl));
8253 
8254         // Add the two halves of the long double in round-to-zero mode.
8255         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8256 
8257         // Now use a smaller FP_TO_SINT.
8258         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8259       }
8260       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8261         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8262         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8263         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8264         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8265         // FIXME: generated code sucks.
8266         // TODO: Are there fast-math-flags to propagate to this FSUB?
8267         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
8268                                    Op.getOperand(0), Tmp);
8269         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8270         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8271                            DAG.getConstant(0x80000000, dl, MVT::i32));
8272         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
8273                                     Op.getOperand(0));
8274         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8275                                ISD::SETGE);
8276       }
8277     }
8278 
8279     return SDValue();
8280   }
8281 
8282   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8283     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8284 
8285   ReuseLoadInfo RLI;
8286   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8287 
8288   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8289                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8290 }
8291 
8292 // We're trying to insert a regular store, S, and then a load, L. If the
8293 // incoming value, O, is a load, we might just be able to have our load use the
8294 // address used by O. However, we don't know if anything else will store to
8295 // that address before we can load from it. To prevent this situation, we need
8296 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8297 // the same chain operand as O, we create a token factor from the chain results
8298 // of O and L, and we replace all uses of O's chain result with that token
8299 // factor (see spliceIntoChain below for this last part).
8300 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8301                                             ReuseLoadInfo &RLI,
8302                                             SelectionDAG &DAG,
8303                                             ISD::LoadExtType ET) const {
8304   SDLoc dl(Op);
8305   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8306                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8307   if (ET == ISD::NON_EXTLOAD &&
8308       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8309       isOperationLegalOrCustom(Op.getOpcode(),
8310                                Op.getOperand(0).getValueType())) {
8311 
8312     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8313     return true;
8314   }
8315 
8316   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8317   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8318       LD->isNonTemporal())
8319     return false;
8320   if (LD->getMemoryVT() != MemVT)
8321     return false;
8322 
8323   RLI.Ptr = LD->getBasePtr();
8324   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8325     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8326            "Non-pre-inc AM on PPC?");
8327     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8328                           LD->getOffset());
8329   }
8330 
8331   RLI.Chain = LD->getChain();
8332   RLI.MPI = LD->getPointerInfo();
8333   RLI.IsDereferenceable = LD->isDereferenceable();
8334   RLI.IsInvariant = LD->isInvariant();
8335   RLI.Alignment = LD->getAlign();
8336   RLI.AAInfo = LD->getAAInfo();
8337   RLI.Ranges = LD->getRanges();
8338 
8339   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8340   return true;
8341 }
8342 
8343 // Given the head of the old chain, ResChain, insert a token factor containing
8344 // it and NewResChain, and make users of ResChain now be users of that token
8345 // factor.
8346 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8347 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8348                                         SDValue NewResChain,
8349                                         SelectionDAG &DAG) const {
8350   if (!ResChain)
8351     return;
8352 
8353   SDLoc dl(NewResChain);
8354 
8355   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8356                            NewResChain, DAG.getUNDEF(MVT::Other));
8357   assert(TF.getNode() != NewResChain.getNode() &&
8358          "A new TF really is required here");
8359 
8360   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8361   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8362 }
8363 
8364 /// Analyze profitability of direct move
8365 /// prefer float load to int load plus direct move
8366 /// when there is no integer use of int load
8367 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8368   SDNode *Origin = Op.getOperand(0).getNode();
8369   if (Origin->getOpcode() != ISD::LOAD)
8370     return true;
8371 
8372   // If there is no LXSIBZX/LXSIHZX, like Power8,
8373   // prefer direct move if the memory size is 1 or 2 bytes.
8374   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8375   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8376     return true;
8377 
8378   for (SDNode::use_iterator UI = Origin->use_begin(),
8379                             UE = Origin->use_end();
8380        UI != UE; ++UI) {
8381 
8382     // Only look at the users of the loaded value.
8383     if (UI.getUse().get().getResNo() != 0)
8384       continue;
8385 
8386     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8387         UI->getOpcode() != ISD::UINT_TO_FP)
8388       return true;
8389   }
8390 
8391   return false;
8392 }
8393 
8394 /// Custom lowers integer to floating point conversions to use
8395 /// the direct move instructions available in ISA 2.07 to avoid the
8396 /// need for load/store combinations.
8397 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8398                                                     SelectionDAG &DAG,
8399                                                     const SDLoc &dl) const {
8400   assert((Op.getValueType() == MVT::f32 ||
8401           Op.getValueType() == MVT::f64) &&
8402          "Invalid floating point type as target of conversion");
8403   assert(Subtarget.hasFPCVT() &&
8404          "Int to FP conversions with direct moves require FPCVT");
8405   SDValue FP;
8406   SDValue Src = Op.getOperand(0);
8407   bool SinglePrec = Op.getValueType() == MVT::f32;
8408   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8409   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8410   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8411                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8412 
8413   if (WordInt) {
8414     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8415                      dl, MVT::f64, Src);
8416     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8417   }
8418   else {
8419     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8420     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8421   }
8422 
8423   return FP;
8424 }
8425 
8426 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8427 
8428   EVT VecVT = Vec.getValueType();
8429   assert(VecVT.isVector() && "Expected a vector type.");
8430   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8431 
8432   EVT EltVT = VecVT.getVectorElementType();
8433   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8434   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8435 
8436   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8437   SmallVector<SDValue, 16> Ops(NumConcat);
8438   Ops[0] = Vec;
8439   SDValue UndefVec = DAG.getUNDEF(VecVT);
8440   for (unsigned i = 1; i < NumConcat; ++i)
8441     Ops[i] = UndefVec;
8442 
8443   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8444 }
8445 
8446 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8447                                                 const SDLoc &dl) const {
8448 
8449   unsigned Opc = Op.getOpcode();
8450   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8451          "Unexpected conversion type");
8452   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8453          "Supports conversions to v2f64/v4f32 only.");
8454 
8455   bool SignedConv = Opc == ISD::SINT_TO_FP;
8456   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8457 
8458   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8459   EVT WideVT = Wide.getValueType();
8460   unsigned WideNumElts = WideVT.getVectorNumElements();
8461   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8462 
8463   SmallVector<int, 16> ShuffV;
8464   for (unsigned i = 0; i < WideNumElts; ++i)
8465     ShuffV.push_back(i + WideNumElts);
8466 
8467   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8468   int SaveElts = FourEltRes ? 4 : 2;
8469   if (Subtarget.isLittleEndian())
8470     for (int i = 0; i < SaveElts; i++)
8471       ShuffV[i * Stride] = i;
8472   else
8473     for (int i = 1; i <= SaveElts; i++)
8474       ShuffV[i * Stride - 1] = i - 1;
8475 
8476   SDValue ShuffleSrc2 =
8477       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8478   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8479 
8480   SDValue Extend;
8481   if (SignedConv) {
8482     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8483     EVT ExtVT = Op.getOperand(0).getValueType();
8484     if (Subtarget.hasP9Altivec())
8485       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8486                                IntermediateVT.getVectorNumElements());
8487 
8488     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8489                          DAG.getValueType(ExtVT));
8490   } else
8491     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8492 
8493   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8494 }
8495 
8496 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8497                                           SelectionDAG &DAG) const {
8498   SDLoc dl(Op);
8499 
8500   EVT InVT = Op.getOperand(0).getValueType();
8501   EVT OutVT = Op.getValueType();
8502   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8503       isOperationCustom(Op.getOpcode(), InVT))
8504     return LowerINT_TO_FPVector(Op, DAG, dl);
8505 
8506   // Conversions to f128 are legal.
8507   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8508     return Op;
8509 
8510   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8511     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8512       return SDValue();
8513 
8514     SDValue Value = Op.getOperand(0);
8515     // The values are now known to be -1 (false) or 1 (true). To convert this
8516     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8517     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8518     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8519 
8520     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8521 
8522     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8523 
8524     if (Op.getValueType() != MVT::v4f64)
8525       Value = DAG.getNode(ISD::FP_ROUND, dl,
8526                           Op.getValueType(), Value,
8527                           DAG.getIntPtrConstant(1, dl));
8528     return Value;
8529   }
8530 
8531   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8532   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8533     return SDValue();
8534 
8535   if (Op.getOperand(0).getValueType() == MVT::i1)
8536     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8537                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8538                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8539 
8540   // If we have direct moves, we can do all the conversion, skip the store/load
8541   // however, without FPCVT we can't do most conversions.
8542   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8543       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8544     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8545 
8546   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8547          "UINT_TO_FP is supported only with FPCVT");
8548 
8549   // If we have FCFIDS, then use it when converting to single-precision.
8550   // Otherwise, convert to double-precision and then round.
8551   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8552                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8553                                                             : PPCISD::FCFIDS)
8554                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8555                                                             : PPCISD::FCFID);
8556   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8557                   ? MVT::f32
8558                   : MVT::f64;
8559 
8560   if (Op.getOperand(0).getValueType() == MVT::i64) {
8561     SDValue SINT = Op.getOperand(0);
8562     // When converting to single-precision, we actually need to convert
8563     // to double-precision first and then round to single-precision.
8564     // To avoid double-rounding effects during that operation, we have
8565     // to prepare the input operand.  Bits that might be truncated when
8566     // converting to double-precision are replaced by a bit that won't
8567     // be lost at this stage, but is below the single-precision rounding
8568     // position.
8569     //
8570     // However, if -enable-unsafe-fp-math is in effect, accept double
8571     // rounding to avoid the extra overhead.
8572     if (Op.getValueType() == MVT::f32 &&
8573         !Subtarget.hasFPCVT() &&
8574         !DAG.getTarget().Options.UnsafeFPMath) {
8575 
8576       // Twiddle input to make sure the low 11 bits are zero.  (If this
8577       // is the case, we are guaranteed the value will fit into the 53 bit
8578       // mantissa of an IEEE double-precision value without rounding.)
8579       // If any of those low 11 bits were not zero originally, make sure
8580       // bit 12 (value 2048) is set instead, so that the final rounding
8581       // to single-precision gets the correct result.
8582       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8583                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8584       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8585                           Round, DAG.getConstant(2047, dl, MVT::i64));
8586       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8587       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8588                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8589 
8590       // However, we cannot use that value unconditionally: if the magnitude
8591       // of the input value is small, the bit-twiddling we did above might
8592       // end up visibly changing the output.  Fortunately, in that case, we
8593       // don't need to twiddle bits since the original input will convert
8594       // exactly to double-precision floating-point already.  Therefore,
8595       // construct a conditional to use the original value if the top 11
8596       // bits are all sign-bit copies, and use the rounded value computed
8597       // above otherwise.
8598       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8599                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8600       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8601                          Cond, DAG.getConstant(1, dl, MVT::i64));
8602       Cond = DAG.getSetCC(
8603           dl,
8604           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8605           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8606 
8607       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8608     }
8609 
8610     ReuseLoadInfo RLI;
8611     SDValue Bits;
8612 
8613     MachineFunction &MF = DAG.getMachineFunction();
8614     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8615       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8616                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8617       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8618     } else if (Subtarget.hasLFIWAX() &&
8619                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8620       MachineMemOperand *MMO =
8621         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8622                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8623       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8624       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8625                                      DAG.getVTList(MVT::f64, MVT::Other),
8626                                      Ops, MVT::i32, MMO);
8627       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8628     } else if (Subtarget.hasFPCVT() &&
8629                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8630       MachineMemOperand *MMO =
8631         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8632                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8633       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8634       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8635                                      DAG.getVTList(MVT::f64, MVT::Other),
8636                                      Ops, MVT::i32, MMO);
8637       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8638     } else if (((Subtarget.hasLFIWAX() &&
8639                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8640                 (Subtarget.hasFPCVT() &&
8641                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8642                SINT.getOperand(0).getValueType() == MVT::i32) {
8643       MachineFrameInfo &MFI = MF.getFrameInfo();
8644       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8645 
8646       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8647       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8648 
8649       SDValue Store =
8650           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8651                        MachinePointerInfo::getFixedStack(
8652                            DAG.getMachineFunction(), FrameIdx));
8653 
8654       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8655              "Expected an i32 store");
8656 
8657       RLI.Ptr = FIdx;
8658       RLI.Chain = Store;
8659       RLI.MPI =
8660           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8661       RLI.Alignment = Align(4);
8662 
8663       MachineMemOperand *MMO =
8664         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8665                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8666       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8667       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8668                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8669                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8670                                      Ops, MVT::i32, MMO);
8671     } else
8672       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8673 
8674     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8675 
8676     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8677       FP = DAG.getNode(ISD::FP_ROUND, dl,
8678                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8679     return FP;
8680   }
8681 
8682   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8683          "Unhandled INT_TO_FP type in custom expander!");
8684   // Since we only generate this in 64-bit mode, we can take advantage of
8685   // 64-bit registers.  In particular, sign extend the input value into the
8686   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8687   // then lfd it and fcfid it.
8688   MachineFunction &MF = DAG.getMachineFunction();
8689   MachineFrameInfo &MFI = MF.getFrameInfo();
8690   EVT PtrVT = getPointerTy(MF.getDataLayout());
8691 
8692   SDValue Ld;
8693   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8694     ReuseLoadInfo RLI;
8695     bool ReusingLoad;
8696     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8697                                             DAG))) {
8698       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8699       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8700 
8701       SDValue Store =
8702           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8703                        MachinePointerInfo::getFixedStack(
8704                            DAG.getMachineFunction(), FrameIdx));
8705 
8706       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8707              "Expected an i32 store");
8708 
8709       RLI.Ptr = FIdx;
8710       RLI.Chain = Store;
8711       RLI.MPI =
8712           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8713       RLI.Alignment = Align(4);
8714     }
8715 
8716     MachineMemOperand *MMO =
8717       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8718                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8719     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8720     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8721                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8722                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8723                                  Ops, MVT::i32, MMO);
8724     if (ReusingLoad)
8725       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8726   } else {
8727     assert(Subtarget.isPPC64() &&
8728            "i32->FP without LFIWAX supported only on PPC64");
8729 
8730     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8731     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8732 
8733     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8734                                 Op.getOperand(0));
8735 
8736     // STD the extended value into the stack slot.
8737     SDValue Store = DAG.getStore(
8738         DAG.getEntryNode(), dl, Ext64, FIdx,
8739         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8740 
8741     // Load the value as a double.
8742     Ld = DAG.getLoad(
8743         MVT::f64, dl, Store, FIdx,
8744         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8745   }
8746 
8747   // FCFID it and return it.
8748   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8749   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8750     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8751                      DAG.getIntPtrConstant(0, dl));
8752   return FP;
8753 }
8754 
8755 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8756                                             SelectionDAG &DAG) const {
8757   SDLoc dl(Op);
8758   /*
8759    The rounding mode is in bits 30:31 of FPSR, and has the following
8760    settings:
8761      00 Round to nearest
8762      01 Round to 0
8763      10 Round to +inf
8764      11 Round to -inf
8765 
8766   FLT_ROUNDS, on the other hand, expects the following:
8767     -1 Undefined
8768      0 Round to 0
8769      1 Round to nearest
8770      2 Round to +inf
8771      3 Round to -inf
8772 
8773   To perform the conversion, we do:
8774     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8775   */
8776 
8777   MachineFunction &MF = DAG.getMachineFunction();
8778   EVT VT = Op.getValueType();
8779   EVT PtrVT = getPointerTy(MF.getDataLayout());
8780 
8781   // Save FP Control Word to register
8782   SDValue Chain = Op.getOperand(0);
8783   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8784   Chain = MFFS.getValue(1);
8785 
8786   // Save FP register to stack slot
8787   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8788   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8789   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8790 
8791   // Load FP Control Word from low 32 bits of stack slot.
8792   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8793   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8794   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8795   Chain = CWD.getValue(1);
8796 
8797   // Transform as necessary
8798   SDValue CWD1 =
8799     DAG.getNode(ISD::AND, dl, MVT::i32,
8800                 CWD, DAG.getConstant(3, dl, MVT::i32));
8801   SDValue CWD2 =
8802     DAG.getNode(ISD::SRL, dl, MVT::i32,
8803                 DAG.getNode(ISD::AND, dl, MVT::i32,
8804                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8805                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8806                             DAG.getConstant(3, dl, MVT::i32)),
8807                 DAG.getConstant(1, dl, MVT::i32));
8808 
8809   SDValue RetVal =
8810     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8811 
8812   RetVal =
8813       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8814                   dl, VT, RetVal);
8815 
8816   return DAG.getMergeValues({RetVal, Chain}, dl);
8817 }
8818 
8819 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8820   EVT VT = Op.getValueType();
8821   unsigned BitWidth = VT.getSizeInBits();
8822   SDLoc dl(Op);
8823   assert(Op.getNumOperands() == 3 &&
8824          VT == Op.getOperand(1).getValueType() &&
8825          "Unexpected SHL!");
8826 
8827   // Expand into a bunch of logical ops.  Note that these ops
8828   // depend on the PPC behavior for oversized shift amounts.
8829   SDValue Lo = Op.getOperand(0);
8830   SDValue Hi = Op.getOperand(1);
8831   SDValue Amt = Op.getOperand(2);
8832   EVT AmtVT = Amt.getValueType();
8833 
8834   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8835                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8836   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8837   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8838   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8839   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8840                              DAG.getConstant(-BitWidth, dl, AmtVT));
8841   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8842   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8843   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8844   SDValue OutOps[] = { OutLo, OutHi };
8845   return DAG.getMergeValues(OutOps, dl);
8846 }
8847 
8848 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8849   EVT VT = Op.getValueType();
8850   SDLoc dl(Op);
8851   unsigned BitWidth = VT.getSizeInBits();
8852   assert(Op.getNumOperands() == 3 &&
8853          VT == Op.getOperand(1).getValueType() &&
8854          "Unexpected SRL!");
8855 
8856   // Expand into a bunch of logical ops.  Note that these ops
8857   // depend on the PPC behavior for oversized shift amounts.
8858   SDValue Lo = Op.getOperand(0);
8859   SDValue Hi = Op.getOperand(1);
8860   SDValue Amt = Op.getOperand(2);
8861   EVT AmtVT = Amt.getValueType();
8862 
8863   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8864                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8865   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8866   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8867   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8868   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8869                              DAG.getConstant(-BitWidth, dl, AmtVT));
8870   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8871   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8872   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8873   SDValue OutOps[] = { OutLo, OutHi };
8874   return DAG.getMergeValues(OutOps, dl);
8875 }
8876 
8877 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8878   SDLoc dl(Op);
8879   EVT VT = Op.getValueType();
8880   unsigned BitWidth = VT.getSizeInBits();
8881   assert(Op.getNumOperands() == 3 &&
8882          VT == Op.getOperand(1).getValueType() &&
8883          "Unexpected SRA!");
8884 
8885   // Expand into a bunch of logical ops, followed by a select_cc.
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::SRA, dl, VT, Hi, Tmp5);
8899   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8900   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8901                                   Tmp4, Tmp6, ISD::SETLE);
8902   SDValue OutOps[] = { OutLo, OutHi };
8903   return DAG.getMergeValues(OutOps, dl);
8904 }
8905 
8906 //===----------------------------------------------------------------------===//
8907 // Vector related lowering.
8908 //
8909 
8910 /// BuildSplatI - Build a canonical splati of Val with an element size of
8911 /// SplatSize.  Cast the result to VT.
8912 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8913                            SelectionDAG &DAG, const SDLoc &dl) {
8914   static const MVT VTys[] = { // canonical VT to use for each size.
8915     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8916   };
8917 
8918   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8919 
8920   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8921   if (Val == -1)
8922     SplatSize = 1;
8923 
8924   EVT CanonicalVT = VTys[SplatSize-1];
8925 
8926   // Build a canonical splat for this value.
8927   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8928 }
8929 
8930 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8931 /// specified intrinsic ID.
8932 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8933                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8934   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8935   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8936                      DAG.getConstant(IID, dl, MVT::i32), Op);
8937 }
8938 
8939 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8940 /// specified intrinsic ID.
8941 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8942                                 SelectionDAG &DAG, const SDLoc &dl,
8943                                 EVT DestVT = MVT::Other) {
8944   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8945   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8946                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8947 }
8948 
8949 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8950 /// specified intrinsic ID.
8951 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8952                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8953                                 EVT DestVT = MVT::Other) {
8954   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8955   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8956                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8957 }
8958 
8959 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8960 /// amount.  The result has the specified value type.
8961 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8962                            SelectionDAG &DAG, const SDLoc &dl) {
8963   // Force LHS/RHS to be the right type.
8964   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8965   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8966 
8967   int Ops[16];
8968   for (unsigned i = 0; i != 16; ++i)
8969     Ops[i] = i + Amt;
8970   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8971   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8972 }
8973 
8974 /// Do we have an efficient pattern in a .td file for this node?
8975 ///
8976 /// \param V - pointer to the BuildVectorSDNode being matched
8977 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8978 ///
8979 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8980 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8981 /// the opposite is true (expansion is beneficial) are:
8982 /// - The node builds a vector out of integers that are not 32 or 64-bits
8983 /// - The node builds a vector out of constants
8984 /// - The node is a "load-and-splat"
8985 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8986 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8987                                             bool HasDirectMove,
8988                                             bool HasP8Vector) {
8989   EVT VecVT = V->getValueType(0);
8990   bool RightType = VecVT == MVT::v2f64 ||
8991     (HasP8Vector && VecVT == MVT::v4f32) ||
8992     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8993   if (!RightType)
8994     return false;
8995 
8996   bool IsSplat = true;
8997   bool IsLoad = false;
8998   SDValue Op0 = V->getOperand(0);
8999 
9000   // This function is called in a block that confirms the node is not a constant
9001   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9002   // different constants.
9003   if (V->isConstant())
9004     return false;
9005   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9006     if (V->getOperand(i).isUndef())
9007       return false;
9008     // We want to expand nodes that represent load-and-splat even if the
9009     // loaded value is a floating point truncation or conversion to int.
9010     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9011         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9012          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9013         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9014          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9015         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9016          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9017       IsLoad = true;
9018     // If the operands are different or the input is not a load and has more
9019     // uses than just this BV node, then it isn't a splat.
9020     if (V->getOperand(i) != Op0 ||
9021         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9022       IsSplat = false;
9023   }
9024   return !(IsSplat && IsLoad);
9025 }
9026 
9027 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9028 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9029 
9030   SDLoc dl(Op);
9031   SDValue Op0 = Op->getOperand(0);
9032 
9033   if (!EnableQuadPrecision ||
9034       (Op.getValueType() != MVT::f128 ) ||
9035       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9036       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
9037       (Op0.getOperand(1).getValueType() != MVT::i64))
9038     return SDValue();
9039 
9040   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9041                      Op0.getOperand(1));
9042 }
9043 
9044 static const SDValue *getNormalLoadInput(const SDValue &Op) {
9045   const SDValue *InputLoad = &Op;
9046   if (InputLoad->getOpcode() == ISD::BITCAST)
9047     InputLoad = &InputLoad->getOperand(0);
9048   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9049       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED)
9050     InputLoad = &InputLoad->getOperand(0);
9051   if (InputLoad->getOpcode() != ISD::LOAD)
9052     return nullptr;
9053   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9054   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9055 }
9056 
9057 // If this is a case we can't handle, return null and let the default
9058 // expansion code take care of it.  If we CAN select this case, and if it
9059 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9060 // this case more efficiently than a constant pool load, lower it to the
9061 // sequence of ops that should be used.
9062 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9063                                              SelectionDAG &DAG) const {
9064   SDLoc dl(Op);
9065   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9066   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9067 
9068   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
9069     // We first build an i32 vector, load it into a QPX register,
9070     // then convert it to a floating-point vector and compare it
9071     // to a zero vector to get the boolean result.
9072     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9073     int FrameIdx = MFI.CreateStackObject(16, 16, false);
9074     MachinePointerInfo PtrInfo =
9075         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9076     EVT PtrVT = getPointerTy(DAG.getDataLayout());
9077     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9078 
9079     assert(BVN->getNumOperands() == 4 &&
9080       "BUILD_VECTOR for v4i1 does not have 4 operands");
9081 
9082     bool IsConst = true;
9083     for (unsigned i = 0; i < 4; ++i) {
9084       if (BVN->getOperand(i).isUndef()) continue;
9085       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
9086         IsConst = false;
9087         break;
9088       }
9089     }
9090 
9091     if (IsConst) {
9092       Constant *One =
9093         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
9094       Constant *NegOne =
9095         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
9096 
9097       Constant *CV[4];
9098       for (unsigned i = 0; i < 4; ++i) {
9099         if (BVN->getOperand(i).isUndef())
9100           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
9101         else if (isNullConstant(BVN->getOperand(i)))
9102           CV[i] = NegOne;
9103         else
9104           CV[i] = One;
9105       }
9106 
9107       Constant *CP = ConstantVector::get(CV);
9108       SDValue CPIdx =
9109           DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16));
9110 
9111       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
9112       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
9113       return DAG.getMemIntrinsicNode(
9114           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
9115           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
9116     }
9117 
9118     SmallVector<SDValue, 4> Stores;
9119     for (unsigned i = 0; i < 4; ++i) {
9120       if (BVN->getOperand(i).isUndef()) continue;
9121 
9122       unsigned Offset = 4*i;
9123       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9124       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9125 
9126       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
9127       if (StoreSize > 4) {
9128         Stores.push_back(
9129             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
9130                               PtrInfo.getWithOffset(Offset), MVT::i32));
9131       } else {
9132         SDValue StoreValue = BVN->getOperand(i);
9133         if (StoreSize < 4)
9134           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
9135 
9136         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
9137                                       PtrInfo.getWithOffset(Offset)));
9138       }
9139     }
9140 
9141     SDValue StoreChain;
9142     if (!Stores.empty())
9143       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9144     else
9145       StoreChain = DAG.getEntryNode();
9146 
9147     // Now load from v4i32 into the QPX register; this will extend it to
9148     // v4i64 but not yet convert it to a floating point. Nevertheless, this
9149     // is typed as v4f64 because the QPX register integer states are not
9150     // explicitly represented.
9151 
9152     SDValue Ops[] = {StoreChain,
9153                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
9154                      FIdx};
9155     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
9156 
9157     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
9158       dl, VTs, Ops, MVT::v4i32, PtrInfo);
9159     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9160       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
9161       LoadedVect);
9162 
9163     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
9164 
9165     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
9166   }
9167 
9168   // All other QPX vectors are handled by generic code.
9169   if (Subtarget.hasQPX())
9170     return SDValue();
9171 
9172   // Check if this is a splat of a constant value.
9173   APInt APSplatBits, APSplatUndef;
9174   unsigned SplatBitSize;
9175   bool HasAnyUndefs;
9176   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9177                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9178       SplatBitSize > 32) {
9179 
9180     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
9181     // Handle load-and-splat patterns as we have instructions that will do this
9182     // in one go.
9183     if (InputLoad && DAG.isSplatValue(Op, true)) {
9184       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9185 
9186       // We have handling for 4 and 8 byte elements.
9187       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9188 
9189       // Checking for a single use of this load, we have to check for vector
9190       // width (128 bits) / ElementSize uses (since each operand of the
9191       // BUILD_VECTOR is a separate use of the value.
9192       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9193           ((Subtarget.hasVSX() && ElementSize == 64) ||
9194            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9195         SDValue Ops[] = {
9196           LD->getChain(),    // Chain
9197           LD->getBasePtr(),  // Ptr
9198           DAG.getValueType(Op.getValueType()) // VT
9199         };
9200         return
9201           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9202                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9203                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9204       }
9205     }
9206 
9207     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9208     // lowered to VSX instructions under certain conditions.
9209     // Without VSX, there is no pattern more efficient than expanding the node.
9210     if (Subtarget.hasVSX() &&
9211         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9212                                         Subtarget.hasP8Vector()))
9213       return Op;
9214     return SDValue();
9215   }
9216 
9217   unsigned SplatBits = APSplatBits.getZExtValue();
9218   unsigned SplatUndef = APSplatUndef.getZExtValue();
9219   unsigned SplatSize = SplatBitSize / 8;
9220 
9221   // First, handle single instruction cases.
9222 
9223   // All zeros?
9224   if (SplatBits == 0) {
9225     // Canonicalize all zero vectors to be v4i32.
9226     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9227       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9228       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9229     }
9230     return Op;
9231   }
9232 
9233   // We have XXSPLTIB for constant splats one byte wide
9234   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
9235   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
9236   if (Subtarget.hasP9Vector() && SplatSize == 1)
9237     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
9238 
9239   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9240   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9241                     (32-SplatBitSize));
9242   if (SextVal >= -16 && SextVal <= 15)
9243     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
9244 
9245   // Two instruction sequences.
9246 
9247   // If this value is in the range [-32,30] and is even, use:
9248   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9249   // If this value is in the range [17,31] and is odd, use:
9250   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9251   // If this value is in the range [-31,-17] and is odd, use:
9252   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9253   // Note the last two are three-instruction sequences.
9254   if (SextVal >= -32 && SextVal <= 31) {
9255     // To avoid having these optimizations undone by constant folding,
9256     // we convert to a pseudo that will be expanded later into one of
9257     // the above forms.
9258     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9259     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9260               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9261     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9262     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9263     if (VT == Op.getValueType())
9264       return RetVal;
9265     else
9266       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9267   }
9268 
9269   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9270   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9271   // for fneg/fabs.
9272   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9273     // Make -1 and vspltisw -1:
9274     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
9275 
9276     // Make the VSLW intrinsic, computing 0x8000_0000.
9277     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9278                                    OnesV, DAG, dl);
9279 
9280     // xor by OnesV to invert it.
9281     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9282     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9283   }
9284 
9285   // Check to see if this is a wide variety of vsplti*, binop self cases.
9286   static const signed char SplatCsts[] = {
9287     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9288     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9289   };
9290 
9291   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9292     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9293     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9294     int i = SplatCsts[idx];
9295 
9296     // Figure out what shift amount will be used by altivec if shifted by i in
9297     // this splat size.
9298     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9299 
9300     // vsplti + shl self.
9301     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9302       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9303       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9304         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9305         Intrinsic::ppc_altivec_vslw
9306       };
9307       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9308       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9309     }
9310 
9311     // vsplti + srl self.
9312     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9313       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9314       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9315         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9316         Intrinsic::ppc_altivec_vsrw
9317       };
9318       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9319       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9320     }
9321 
9322     // vsplti + sra self.
9323     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9324       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9325       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9326         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9327         Intrinsic::ppc_altivec_vsraw
9328       };
9329       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9330       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9331     }
9332 
9333     // vsplti + rol self.
9334     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9335                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9336       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9337       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9338         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9339         Intrinsic::ppc_altivec_vrlw
9340       };
9341       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9342       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9343     }
9344 
9345     // t = vsplti c, result = vsldoi t, t, 1
9346     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9347       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9348       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9349       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9350     }
9351     // t = vsplti c, result = vsldoi t, t, 2
9352     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9353       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9354       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9355       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9356     }
9357     // t = vsplti c, result = vsldoi t, t, 3
9358     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9359       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9360       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9361       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9362     }
9363   }
9364 
9365   return SDValue();
9366 }
9367 
9368 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9369 /// the specified operations to build the shuffle.
9370 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9371                                       SDValue RHS, SelectionDAG &DAG,
9372                                       const SDLoc &dl) {
9373   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9374   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9375   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9376 
9377   enum {
9378     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9379     OP_VMRGHW,
9380     OP_VMRGLW,
9381     OP_VSPLTISW0,
9382     OP_VSPLTISW1,
9383     OP_VSPLTISW2,
9384     OP_VSPLTISW3,
9385     OP_VSLDOI4,
9386     OP_VSLDOI8,
9387     OP_VSLDOI12
9388   };
9389 
9390   if (OpNum == OP_COPY) {
9391     if (LHSID == (1*9+2)*9+3) return LHS;
9392     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9393     return RHS;
9394   }
9395 
9396   SDValue OpLHS, OpRHS;
9397   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9398   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9399 
9400   int ShufIdxs[16];
9401   switch (OpNum) {
9402   default: llvm_unreachable("Unknown i32 permute!");
9403   case OP_VMRGHW:
9404     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9405     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9406     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9407     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9408     break;
9409   case OP_VMRGLW:
9410     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9411     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9412     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9413     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9414     break;
9415   case OP_VSPLTISW0:
9416     for (unsigned i = 0; i != 16; ++i)
9417       ShufIdxs[i] = (i&3)+0;
9418     break;
9419   case OP_VSPLTISW1:
9420     for (unsigned i = 0; i != 16; ++i)
9421       ShufIdxs[i] = (i&3)+4;
9422     break;
9423   case OP_VSPLTISW2:
9424     for (unsigned i = 0; i != 16; ++i)
9425       ShufIdxs[i] = (i&3)+8;
9426     break;
9427   case OP_VSPLTISW3:
9428     for (unsigned i = 0; i != 16; ++i)
9429       ShufIdxs[i] = (i&3)+12;
9430     break;
9431   case OP_VSLDOI4:
9432     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9433   case OP_VSLDOI8:
9434     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9435   case OP_VSLDOI12:
9436     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9437   }
9438   EVT VT = OpLHS.getValueType();
9439   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9440   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9441   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9442   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9443 }
9444 
9445 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9446 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9447 /// SDValue.
9448 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9449                                            SelectionDAG &DAG) const {
9450   const unsigned BytesInVector = 16;
9451   bool IsLE = Subtarget.isLittleEndian();
9452   SDLoc dl(N);
9453   SDValue V1 = N->getOperand(0);
9454   SDValue V2 = N->getOperand(1);
9455   unsigned ShiftElts = 0, InsertAtByte = 0;
9456   bool Swap = false;
9457 
9458   // Shifts required to get the byte we want at element 7.
9459   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9460                                    0, 15, 14, 13, 12, 11, 10, 9};
9461   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9462                                 1, 2,  3,  4,  5,  6,  7,  8};
9463 
9464   ArrayRef<int> Mask = N->getMask();
9465   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9466 
9467   // For each mask element, find out if we're just inserting something
9468   // from V2 into V1 or vice versa.
9469   // Possible permutations inserting an element from V2 into V1:
9470   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9471   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9472   //   ...
9473   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9474   // Inserting from V1 into V2 will be similar, except mask range will be
9475   // [16,31].
9476 
9477   bool FoundCandidate = false;
9478   // If both vector operands for the shuffle are the same vector, the mask
9479   // will contain only elements from the first one and the second one will be
9480   // undef.
9481   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9482   // Go through the mask of half-words to find an element that's being moved
9483   // from one vector to the other.
9484   for (unsigned i = 0; i < BytesInVector; ++i) {
9485     unsigned CurrentElement = Mask[i];
9486     // If 2nd operand is undefined, we should only look for element 7 in the
9487     // Mask.
9488     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9489       continue;
9490 
9491     bool OtherElementsInOrder = true;
9492     // Examine the other elements in the Mask to see if they're in original
9493     // order.
9494     for (unsigned j = 0; j < BytesInVector; ++j) {
9495       if (j == i)
9496         continue;
9497       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9498       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9499       // in which we always assume we're always picking from the 1st operand.
9500       int MaskOffset =
9501           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9502       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9503         OtherElementsInOrder = false;
9504         break;
9505       }
9506     }
9507     // If other elements are in original order, we record the number of shifts
9508     // we need to get the element we want into element 7. Also record which byte
9509     // in the vector we should insert into.
9510     if (OtherElementsInOrder) {
9511       // If 2nd operand is undefined, we assume no shifts and no swapping.
9512       if (V2.isUndef()) {
9513         ShiftElts = 0;
9514         Swap = false;
9515       } else {
9516         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9517         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9518                          : BigEndianShifts[CurrentElement & 0xF];
9519         Swap = CurrentElement < BytesInVector;
9520       }
9521       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9522       FoundCandidate = true;
9523       break;
9524     }
9525   }
9526 
9527   if (!FoundCandidate)
9528     return SDValue();
9529 
9530   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9531   // optionally with VECSHL if shift is required.
9532   if (Swap)
9533     std::swap(V1, V2);
9534   if (V2.isUndef())
9535     V2 = V1;
9536   if (ShiftElts) {
9537     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9538                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9539     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9540                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9541   }
9542   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9543                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9544 }
9545 
9546 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9547 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9548 /// SDValue.
9549 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9550                                            SelectionDAG &DAG) const {
9551   const unsigned NumHalfWords = 8;
9552   const unsigned BytesInVector = NumHalfWords * 2;
9553   // Check that the shuffle is on half-words.
9554   if (!isNByteElemShuffleMask(N, 2, 1))
9555     return SDValue();
9556 
9557   bool IsLE = Subtarget.isLittleEndian();
9558   SDLoc dl(N);
9559   SDValue V1 = N->getOperand(0);
9560   SDValue V2 = N->getOperand(1);
9561   unsigned ShiftElts = 0, InsertAtByte = 0;
9562   bool Swap = false;
9563 
9564   // Shifts required to get the half-word we want at element 3.
9565   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9566   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9567 
9568   uint32_t Mask = 0;
9569   uint32_t OriginalOrderLow = 0x1234567;
9570   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9571   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9572   // 32-bit space, only need 4-bit nibbles per element.
9573   for (unsigned i = 0; i < NumHalfWords; ++i) {
9574     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9575     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9576   }
9577 
9578   // For each mask element, find out if we're just inserting something
9579   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9580   // from V2 into V1:
9581   //   X, 1, 2, 3, 4, 5, 6, 7
9582   //   0, X, 2, 3, 4, 5, 6, 7
9583   //   0, 1, X, 3, 4, 5, 6, 7
9584   //   0, 1, 2, X, 4, 5, 6, 7
9585   //   0, 1, 2, 3, X, 5, 6, 7
9586   //   0, 1, 2, 3, 4, X, 6, 7
9587   //   0, 1, 2, 3, 4, 5, X, 7
9588   //   0, 1, 2, 3, 4, 5, 6, X
9589   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9590 
9591   bool FoundCandidate = false;
9592   // Go through the mask of half-words to find an element that's being moved
9593   // from one vector to the other.
9594   for (unsigned i = 0; i < NumHalfWords; ++i) {
9595     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9596     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9597     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9598     uint32_t TargetOrder = 0x0;
9599 
9600     // If both vector operands for the shuffle are the same vector, the mask
9601     // will contain only elements from the first one and the second one will be
9602     // undef.
9603     if (V2.isUndef()) {
9604       ShiftElts = 0;
9605       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9606       TargetOrder = OriginalOrderLow;
9607       Swap = false;
9608       // Skip if not the correct element or mask of other elements don't equal
9609       // to our expected order.
9610       if (MaskOneElt == VINSERTHSrcElem &&
9611           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9612         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9613         FoundCandidate = true;
9614         break;
9615       }
9616     } else { // If both operands are defined.
9617       // Target order is [8,15] if the current mask is between [0,7].
9618       TargetOrder =
9619           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9620       // Skip if mask of other elements don't equal our expected order.
9621       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9622         // We only need the last 3 bits for the number of shifts.
9623         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9624                          : BigEndianShifts[MaskOneElt & 0x7];
9625         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9626         Swap = MaskOneElt < NumHalfWords;
9627         FoundCandidate = true;
9628         break;
9629       }
9630     }
9631   }
9632 
9633   if (!FoundCandidate)
9634     return SDValue();
9635 
9636   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9637   // optionally with VECSHL if shift is required.
9638   if (Swap)
9639     std::swap(V1, V2);
9640   if (V2.isUndef())
9641     V2 = V1;
9642   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9643   if (ShiftElts) {
9644     // Double ShiftElts because we're left shifting on v16i8 type.
9645     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9646                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9647     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9648     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9649                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9650     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9651   }
9652   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9653   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9654                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9655   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9656 }
9657 
9658 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9659 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9660 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9661 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9662 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9663   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9664   assert(Op.getValueType() == MVT::v1i128 &&
9665          "Only set v1i128 as custom, other type shouldn't reach here!");
9666   SDLoc dl(Op);
9667   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9668   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9669   unsigned SHLAmt = N1.getConstantOperandVal(0);
9670   if (SHLAmt % 8 == 0) {
9671     SmallVector<int, 16> Mask(16, 0);
9672     std::iota(Mask.begin(), Mask.end(), 0);
9673     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9674     if (SDValue Shuffle =
9675             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9676                                  DAG.getUNDEF(MVT::v16i8), Mask))
9677       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9678   }
9679   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9680   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9681                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9682   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9683                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9684   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9685   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9686 }
9687 
9688 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9689 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9690 /// return the code it can be lowered into.  Worst case, it can always be
9691 /// lowered into a vperm.
9692 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9693                                                SelectionDAG &DAG) const {
9694   SDLoc dl(Op);
9695   SDValue V1 = Op.getOperand(0);
9696   SDValue V2 = Op.getOperand(1);
9697   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9698 
9699   // Any nodes that were combined in the target-independent combiner prior
9700   // to vector legalization will not be sent to the target combine. Try to
9701   // combine it here.
9702   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9703     DAG.ReplaceAllUsesOfValueWith(Op, NewShuffle);
9704     Op = NewShuffle;
9705     SVOp = cast<ShuffleVectorSDNode>(Op);
9706   }
9707   EVT VT = Op.getValueType();
9708   bool isLittleEndian = Subtarget.isLittleEndian();
9709 
9710   unsigned ShiftElts, InsertAtByte;
9711   bool Swap = false;
9712 
9713   // If this is a load-and-splat, we can do that with a single instruction
9714   // in some cases. However if the load has multiple uses, we don't want to
9715   // combine it because that will just produce multiple loads.
9716   const SDValue *InputLoad = getNormalLoadInput(V1);
9717   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9718       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9719       InputLoad->hasOneUse()) {
9720     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9721     int SplatIdx =
9722       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9723 
9724     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9725     // For 4-byte load-and-splat, we need Power9.
9726     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9727       uint64_t Offset = 0;
9728       if (IsFourByte)
9729         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9730       else
9731         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9732 
9733       // If we are loading a partial vector, it does not make sense to adjust
9734       // the base pointer. This happens with (splat (s_to_v_permuted (ld))).
9735       if (LD->getMemoryVT().getSizeInBits() == (IsFourByte ? 32 : 64))
9736         Offset = 0;
9737       SDValue BasePtr = LD->getBasePtr();
9738       if (Offset != 0)
9739         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9740                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9741       SDValue Ops[] = {
9742         LD->getChain(),    // Chain
9743         BasePtr,           // BasePtr
9744         DAG.getValueType(Op.getValueType()) // VT
9745       };
9746       SDVTList VTL =
9747         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9748       SDValue LdSplt =
9749         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9750                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9751       if (LdSplt.getValueType() != SVOp->getValueType(0))
9752         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9753       return LdSplt;
9754     }
9755   }
9756   if (Subtarget.hasP9Vector() &&
9757       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9758                            isLittleEndian)) {
9759     if (Swap)
9760       std::swap(V1, V2);
9761     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9762     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9763     if (ShiftElts) {
9764       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9765                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9766       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9767                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9768       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9769     }
9770     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9771                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9772     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9773   }
9774 
9775   if (Subtarget.hasP9Altivec()) {
9776     SDValue NewISDNode;
9777     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9778       return NewISDNode;
9779 
9780     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9781       return NewISDNode;
9782   }
9783 
9784   if (Subtarget.hasVSX() &&
9785       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9786     if (Swap)
9787       std::swap(V1, V2);
9788     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9789     SDValue Conv2 =
9790         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9791 
9792     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9793                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9794     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9795   }
9796 
9797   if (Subtarget.hasVSX() &&
9798     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9799     if (Swap)
9800       std::swap(V1, V2);
9801     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9802     SDValue Conv2 =
9803         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9804 
9805     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9806                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9807     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9808   }
9809 
9810   if (Subtarget.hasP9Vector()) {
9811      if (PPC::isXXBRHShuffleMask(SVOp)) {
9812       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9813       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9814       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9815     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9816       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9817       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9818       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9819     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9820       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9821       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9822       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9823     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9824       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9825       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9826       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9827     }
9828   }
9829 
9830   if (Subtarget.hasVSX()) {
9831     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9832       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9833 
9834       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9835       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9836                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9837       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9838     }
9839 
9840     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9841     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9842       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9843       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9844       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9845     }
9846   }
9847 
9848   if (Subtarget.hasQPX()) {
9849     if (VT.getVectorNumElements() != 4)
9850       return SDValue();
9851 
9852     if (V2.isUndef()) V2 = V1;
9853 
9854     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9855     if (AlignIdx != -1) {
9856       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9857                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9858     } else if (SVOp->isSplat()) {
9859       int SplatIdx = SVOp->getSplatIndex();
9860       if (SplatIdx >= 4) {
9861         std::swap(V1, V2);
9862         SplatIdx -= 4;
9863       }
9864 
9865       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9866                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9867     }
9868 
9869     // Lower this into a qvgpci/qvfperm pair.
9870 
9871     // Compute the qvgpci literal
9872     unsigned idx = 0;
9873     for (unsigned i = 0; i < 4; ++i) {
9874       int m = SVOp->getMaskElt(i);
9875       unsigned mm = m >= 0 ? (unsigned) m : i;
9876       idx |= mm << (3-i)*3;
9877     }
9878 
9879     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9880                              DAG.getConstant(idx, dl, MVT::i32));
9881     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9882   }
9883 
9884   // Cases that are handled by instructions that take permute immediates
9885   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9886   // selected by the instruction selector.
9887   if (V2.isUndef()) {
9888     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9889         PPC::isSplatShuffleMask(SVOp, 2) ||
9890         PPC::isSplatShuffleMask(SVOp, 4) ||
9891         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9892         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9893         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9894         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9895         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9896         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9897         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9898         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9899         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9900         (Subtarget.hasP8Altivec() && (
9901          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9902          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9903          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9904       return Op;
9905     }
9906   }
9907 
9908   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9909   // and produce a fixed permutation.  If any of these match, do not lower to
9910   // VPERM.
9911   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9912   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9913       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9914       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9915       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9916       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9917       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9918       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9919       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9920       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9921       (Subtarget.hasP8Altivec() && (
9922        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9923        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9924        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9925     return Op;
9926 
9927   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9928   // perfect shuffle table to emit an optimal matching sequence.
9929   ArrayRef<int> PermMask = SVOp->getMask();
9930 
9931   unsigned PFIndexes[4];
9932   bool isFourElementShuffle = true;
9933   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9934     unsigned EltNo = 8;   // Start out undef.
9935     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9936       if (PermMask[i*4+j] < 0)
9937         continue;   // Undef, ignore it.
9938 
9939       unsigned ByteSource = PermMask[i*4+j];
9940       if ((ByteSource & 3) != j) {
9941         isFourElementShuffle = false;
9942         break;
9943       }
9944 
9945       if (EltNo == 8) {
9946         EltNo = ByteSource/4;
9947       } else if (EltNo != ByteSource/4) {
9948         isFourElementShuffle = false;
9949         break;
9950       }
9951     }
9952     PFIndexes[i] = EltNo;
9953   }
9954 
9955   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9956   // perfect shuffle vector to determine if it is cost effective to do this as
9957   // discrete instructions, or whether we should use a vperm.
9958   // For now, we skip this for little endian until such time as we have a
9959   // little-endian perfect shuffle table.
9960   if (isFourElementShuffle && !isLittleEndian) {
9961     // Compute the index in the perfect shuffle table.
9962     unsigned PFTableIndex =
9963       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9964 
9965     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9966     unsigned Cost  = (PFEntry >> 30);
9967 
9968     // Determining when to avoid vperm is tricky.  Many things affect the cost
9969     // of vperm, particularly how many times the perm mask needs to be computed.
9970     // For example, if the perm mask can be hoisted out of a loop or is already
9971     // used (perhaps because there are multiple permutes with the same shuffle
9972     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9973     // the loop requires an extra register.
9974     //
9975     // As a compromise, we only emit discrete instructions if the shuffle can be
9976     // generated in 3 or fewer operations.  When we have loop information
9977     // available, if this block is within a loop, we should avoid using vperm
9978     // for 3-operation perms and use a constant pool load instead.
9979     if (Cost < 3)
9980       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9981   }
9982 
9983   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9984   // vector that will get spilled to the constant pool.
9985   if (V2.isUndef()) V2 = V1;
9986 
9987   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9988   // that it is in input element units, not in bytes.  Convert now.
9989 
9990   // For little endian, the order of the input vectors is reversed, and
9991   // the permutation mask is complemented with respect to 31.  This is
9992   // necessary to produce proper semantics with the big-endian-biased vperm
9993   // instruction.
9994   EVT EltVT = V1.getValueType().getVectorElementType();
9995   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9996 
9997   SmallVector<SDValue, 16> ResultMask;
9998   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9999     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10000 
10001     for (unsigned j = 0; j != BytesPerElement; ++j)
10002       if (isLittleEndian)
10003         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10004                                              dl, MVT::i32));
10005       else
10006         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10007                                              MVT::i32));
10008   }
10009 
10010   ShufflesHandledWithVPERM++;
10011   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10012   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10013   LLVM_DEBUG(SVOp->dump());
10014   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10015   LLVM_DEBUG(VPermMask.dump());
10016 
10017   if (isLittleEndian)
10018     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10019                        V2, V1, VPermMask);
10020   else
10021     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10022                        V1, V2, VPermMask);
10023 }
10024 
10025 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10026 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10027 /// information about the intrinsic.
10028 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10029                                  bool &isDot, const PPCSubtarget &Subtarget) {
10030   unsigned IntrinsicID =
10031       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10032   CompareOpc = -1;
10033   isDot = false;
10034   switch (IntrinsicID) {
10035   default:
10036     return false;
10037   // Comparison predicates.
10038   case Intrinsic::ppc_altivec_vcmpbfp_p:
10039     CompareOpc = 966;
10040     isDot = true;
10041     break;
10042   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10043     CompareOpc = 198;
10044     isDot = true;
10045     break;
10046   case Intrinsic::ppc_altivec_vcmpequb_p:
10047     CompareOpc = 6;
10048     isDot = true;
10049     break;
10050   case Intrinsic::ppc_altivec_vcmpequh_p:
10051     CompareOpc = 70;
10052     isDot = true;
10053     break;
10054   case Intrinsic::ppc_altivec_vcmpequw_p:
10055     CompareOpc = 134;
10056     isDot = true;
10057     break;
10058   case Intrinsic::ppc_altivec_vcmpequd_p:
10059     if (Subtarget.hasP8Altivec()) {
10060       CompareOpc = 199;
10061       isDot = true;
10062     } else
10063       return false;
10064     break;
10065   case Intrinsic::ppc_altivec_vcmpneb_p:
10066   case Intrinsic::ppc_altivec_vcmpneh_p:
10067   case Intrinsic::ppc_altivec_vcmpnew_p:
10068   case Intrinsic::ppc_altivec_vcmpnezb_p:
10069   case Intrinsic::ppc_altivec_vcmpnezh_p:
10070   case Intrinsic::ppc_altivec_vcmpnezw_p:
10071     if (Subtarget.hasP9Altivec()) {
10072       switch (IntrinsicID) {
10073       default:
10074         llvm_unreachable("Unknown comparison intrinsic.");
10075       case Intrinsic::ppc_altivec_vcmpneb_p:
10076         CompareOpc = 7;
10077         break;
10078       case Intrinsic::ppc_altivec_vcmpneh_p:
10079         CompareOpc = 71;
10080         break;
10081       case Intrinsic::ppc_altivec_vcmpnew_p:
10082         CompareOpc = 135;
10083         break;
10084       case Intrinsic::ppc_altivec_vcmpnezb_p:
10085         CompareOpc = 263;
10086         break;
10087       case Intrinsic::ppc_altivec_vcmpnezh_p:
10088         CompareOpc = 327;
10089         break;
10090       case Intrinsic::ppc_altivec_vcmpnezw_p:
10091         CompareOpc = 391;
10092         break;
10093       }
10094       isDot = true;
10095     } else
10096       return false;
10097     break;
10098   case Intrinsic::ppc_altivec_vcmpgefp_p:
10099     CompareOpc = 454;
10100     isDot = true;
10101     break;
10102   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10103     CompareOpc = 710;
10104     isDot = true;
10105     break;
10106   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10107     CompareOpc = 774;
10108     isDot = true;
10109     break;
10110   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10111     CompareOpc = 838;
10112     isDot = true;
10113     break;
10114   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10115     CompareOpc = 902;
10116     isDot = true;
10117     break;
10118   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10119     if (Subtarget.hasP8Altivec()) {
10120       CompareOpc = 967;
10121       isDot = true;
10122     } else
10123       return false;
10124     break;
10125   case Intrinsic::ppc_altivec_vcmpgtub_p:
10126     CompareOpc = 518;
10127     isDot = true;
10128     break;
10129   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10130     CompareOpc = 582;
10131     isDot = true;
10132     break;
10133   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10134     CompareOpc = 646;
10135     isDot = true;
10136     break;
10137   case Intrinsic::ppc_altivec_vcmpgtud_p:
10138     if (Subtarget.hasP8Altivec()) {
10139       CompareOpc = 711;
10140       isDot = true;
10141     } else
10142       return false;
10143     break;
10144 
10145   // VSX predicate comparisons use the same infrastructure
10146   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10147   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10148   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10149   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10150   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10151   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10152     if (Subtarget.hasVSX()) {
10153       switch (IntrinsicID) {
10154       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10155         CompareOpc = 99;
10156         break;
10157       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10158         CompareOpc = 115;
10159         break;
10160       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10161         CompareOpc = 107;
10162         break;
10163       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10164         CompareOpc = 67;
10165         break;
10166       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10167         CompareOpc = 83;
10168         break;
10169       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10170         CompareOpc = 75;
10171         break;
10172       }
10173       isDot = true;
10174     } else
10175       return false;
10176     break;
10177 
10178   // Normal Comparisons.
10179   case Intrinsic::ppc_altivec_vcmpbfp:
10180     CompareOpc = 966;
10181     break;
10182   case Intrinsic::ppc_altivec_vcmpeqfp:
10183     CompareOpc = 198;
10184     break;
10185   case Intrinsic::ppc_altivec_vcmpequb:
10186     CompareOpc = 6;
10187     break;
10188   case Intrinsic::ppc_altivec_vcmpequh:
10189     CompareOpc = 70;
10190     break;
10191   case Intrinsic::ppc_altivec_vcmpequw:
10192     CompareOpc = 134;
10193     break;
10194   case Intrinsic::ppc_altivec_vcmpequd:
10195     if (Subtarget.hasP8Altivec())
10196       CompareOpc = 199;
10197     else
10198       return false;
10199     break;
10200   case Intrinsic::ppc_altivec_vcmpneb:
10201   case Intrinsic::ppc_altivec_vcmpneh:
10202   case Intrinsic::ppc_altivec_vcmpnew:
10203   case Intrinsic::ppc_altivec_vcmpnezb:
10204   case Intrinsic::ppc_altivec_vcmpnezh:
10205   case Intrinsic::ppc_altivec_vcmpnezw:
10206     if (Subtarget.hasP9Altivec())
10207       switch (IntrinsicID) {
10208       default:
10209         llvm_unreachable("Unknown comparison intrinsic.");
10210       case Intrinsic::ppc_altivec_vcmpneb:
10211         CompareOpc = 7;
10212         break;
10213       case Intrinsic::ppc_altivec_vcmpneh:
10214         CompareOpc = 71;
10215         break;
10216       case Intrinsic::ppc_altivec_vcmpnew:
10217         CompareOpc = 135;
10218         break;
10219       case Intrinsic::ppc_altivec_vcmpnezb:
10220         CompareOpc = 263;
10221         break;
10222       case Intrinsic::ppc_altivec_vcmpnezh:
10223         CompareOpc = 327;
10224         break;
10225       case Intrinsic::ppc_altivec_vcmpnezw:
10226         CompareOpc = 391;
10227         break;
10228       }
10229     else
10230       return false;
10231     break;
10232   case Intrinsic::ppc_altivec_vcmpgefp:
10233     CompareOpc = 454;
10234     break;
10235   case Intrinsic::ppc_altivec_vcmpgtfp:
10236     CompareOpc = 710;
10237     break;
10238   case Intrinsic::ppc_altivec_vcmpgtsb:
10239     CompareOpc = 774;
10240     break;
10241   case Intrinsic::ppc_altivec_vcmpgtsh:
10242     CompareOpc = 838;
10243     break;
10244   case Intrinsic::ppc_altivec_vcmpgtsw:
10245     CompareOpc = 902;
10246     break;
10247   case Intrinsic::ppc_altivec_vcmpgtsd:
10248     if (Subtarget.hasP8Altivec())
10249       CompareOpc = 967;
10250     else
10251       return false;
10252     break;
10253   case Intrinsic::ppc_altivec_vcmpgtub:
10254     CompareOpc = 518;
10255     break;
10256   case Intrinsic::ppc_altivec_vcmpgtuh:
10257     CompareOpc = 582;
10258     break;
10259   case Intrinsic::ppc_altivec_vcmpgtuw:
10260     CompareOpc = 646;
10261     break;
10262   case Intrinsic::ppc_altivec_vcmpgtud:
10263     if (Subtarget.hasP8Altivec())
10264       CompareOpc = 711;
10265     else
10266       return false;
10267     break;
10268   }
10269   return true;
10270 }
10271 
10272 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10273 /// lower, do it, otherwise return null.
10274 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10275                                                    SelectionDAG &DAG) const {
10276   unsigned IntrinsicID =
10277     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10278 
10279   SDLoc dl(Op);
10280 
10281   if (IntrinsicID == Intrinsic::thread_pointer) {
10282     // Reads the thread pointer register, used for __builtin_thread_pointer.
10283     if (Subtarget.isPPC64())
10284       return DAG.getRegister(PPC::X13, MVT::i64);
10285     return DAG.getRegister(PPC::R2, MVT::i32);
10286   }
10287 
10288   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10289   // opcode number of the comparison.
10290   int CompareOpc;
10291   bool isDot;
10292   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10293     return SDValue();    // Don't custom lower most intrinsics.
10294 
10295   // If this is a non-dot comparison, make the VCMP node and we are done.
10296   if (!isDot) {
10297     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10298                               Op.getOperand(1), Op.getOperand(2),
10299                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10300     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10301   }
10302 
10303   // Create the PPCISD altivec 'dot' comparison node.
10304   SDValue Ops[] = {
10305     Op.getOperand(2),  // LHS
10306     Op.getOperand(3),  // RHS
10307     DAG.getConstant(CompareOpc, dl, MVT::i32)
10308   };
10309   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10310   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10311 
10312   // Now that we have the comparison, emit a copy from the CR to a GPR.
10313   // This is flagged to the above dot comparison.
10314   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10315                                 DAG.getRegister(PPC::CR6, MVT::i32),
10316                                 CompNode.getValue(1));
10317 
10318   // Unpack the result based on how the target uses it.
10319   unsigned BitNo;   // Bit # of CR6.
10320   bool InvertBit;   // Invert result?
10321   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10322   default:  // Can't happen, don't crash on invalid number though.
10323   case 0:   // Return the value of the EQ bit of CR6.
10324     BitNo = 0; InvertBit = false;
10325     break;
10326   case 1:   // Return the inverted value of the EQ bit of CR6.
10327     BitNo = 0; InvertBit = true;
10328     break;
10329   case 2:   // Return the value of the LT bit of CR6.
10330     BitNo = 2; InvertBit = false;
10331     break;
10332   case 3:   // Return the inverted value of the LT bit of CR6.
10333     BitNo = 2; InvertBit = true;
10334     break;
10335   }
10336 
10337   // Shift the bit into the low position.
10338   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10339                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10340   // Isolate the bit.
10341   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10342                       DAG.getConstant(1, dl, MVT::i32));
10343 
10344   // If we are supposed to, toggle the bit.
10345   if (InvertBit)
10346     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10347                         DAG.getConstant(1, dl, MVT::i32));
10348   return Flags;
10349 }
10350 
10351 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10352                                                SelectionDAG &DAG) const {
10353   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10354   // the beginning of the argument list.
10355   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10356   SDLoc DL(Op);
10357   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10358   case Intrinsic::ppc_cfence: {
10359     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10360     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10361     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10362                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10363                                                   Op.getOperand(ArgStart + 1)),
10364                                       Op.getOperand(0)),
10365                    0);
10366   }
10367   default:
10368     break;
10369   }
10370   return SDValue();
10371 }
10372 
10373 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10374   // Check for a DIV with the same operands as this REM.
10375   for (auto UI : Op.getOperand(1)->uses()) {
10376     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10377         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10378       if (UI->getOperand(0) == Op.getOperand(0) &&
10379           UI->getOperand(1) == Op.getOperand(1))
10380         return SDValue();
10381   }
10382   return Op;
10383 }
10384 
10385 // Lower scalar BSWAP64 to xxbrd.
10386 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10387   SDLoc dl(Op);
10388   // MTVSRDD
10389   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10390                    Op.getOperand(0));
10391   // XXBRD
10392   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10393   // MFVSRD
10394   int VectorIndex = 0;
10395   if (Subtarget.isLittleEndian())
10396     VectorIndex = 1;
10397   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10398                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10399   return Op;
10400 }
10401 
10402 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10403 // compared to a value that is atomically loaded (atomic loads zero-extend).
10404 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10405                                                 SelectionDAG &DAG) const {
10406   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10407          "Expecting an atomic compare-and-swap here.");
10408   SDLoc dl(Op);
10409   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10410   EVT MemVT = AtomicNode->getMemoryVT();
10411   if (MemVT.getSizeInBits() >= 32)
10412     return Op;
10413 
10414   SDValue CmpOp = Op.getOperand(2);
10415   // If this is already correctly zero-extended, leave it alone.
10416   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10417   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10418     return Op;
10419 
10420   // Clear the high bits of the compare operand.
10421   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10422   SDValue NewCmpOp =
10423     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10424                 DAG.getConstant(MaskVal, dl, MVT::i32));
10425 
10426   // Replace the existing compare operand with the properly zero-extended one.
10427   SmallVector<SDValue, 4> Ops;
10428   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10429     Ops.push_back(AtomicNode->getOperand(i));
10430   Ops[2] = NewCmpOp;
10431   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10432   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10433   auto NodeTy =
10434     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10435   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10436 }
10437 
10438 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10439                                                  SelectionDAG &DAG) const {
10440   SDLoc dl(Op);
10441   // Create a stack slot that is 16-byte aligned.
10442   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10443   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10444   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10445   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10446 
10447   // Store the input value into Value#0 of the stack slot.
10448   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10449                                MachinePointerInfo());
10450   // Load it out.
10451   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10452 }
10453 
10454 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10455                                                   SelectionDAG &DAG) const {
10456   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10457          "Should only be called for ISD::INSERT_VECTOR_ELT");
10458 
10459   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10460   // We have legal lowering for constant indices but not for variable ones.
10461   if (!C)
10462     return SDValue();
10463 
10464   EVT VT = Op.getValueType();
10465   SDLoc dl(Op);
10466   SDValue V1 = Op.getOperand(0);
10467   SDValue V2 = Op.getOperand(1);
10468   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10469   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10470     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10471     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10472     unsigned InsertAtElement = C->getZExtValue();
10473     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10474     if (Subtarget.isLittleEndian()) {
10475       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10476     }
10477     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10478                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10479   }
10480   return Op;
10481 }
10482 
10483 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10484                                                    SelectionDAG &DAG) const {
10485   SDLoc dl(Op);
10486   SDNode *N = Op.getNode();
10487 
10488   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10489          "Unknown extract_vector_elt type");
10490 
10491   SDValue Value = N->getOperand(0);
10492 
10493   // The first part of this is like the store lowering except that we don't
10494   // need to track the chain.
10495 
10496   // The values are now known to be -1 (false) or 1 (true). To convert this
10497   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10498   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10499   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10500 
10501   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10502   // understand how to form the extending load.
10503   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10504 
10505   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10506 
10507   // Now convert to an integer and store.
10508   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10509     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10510     Value);
10511 
10512   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10513   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10514   MachinePointerInfo PtrInfo =
10515       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10516   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10517   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10518 
10519   SDValue StoreChain = DAG.getEntryNode();
10520   SDValue Ops[] = {StoreChain,
10521                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10522                    Value, FIdx};
10523   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10524 
10525   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10526     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10527 
10528   // Extract the value requested.
10529   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10530   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10531   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10532 
10533   SDValue IntVal =
10534       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10535 
10536   if (!Subtarget.useCRBits())
10537     return IntVal;
10538 
10539   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10540 }
10541 
10542 /// Lowering for QPX v4i1 loads
10543 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10544                                            SelectionDAG &DAG) const {
10545   SDLoc dl(Op);
10546   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10547   SDValue LoadChain = LN->getChain();
10548   SDValue BasePtr = LN->getBasePtr();
10549 
10550   if (Op.getValueType() == MVT::v4f64 ||
10551       Op.getValueType() == MVT::v4f32) {
10552     EVT MemVT = LN->getMemoryVT();
10553     unsigned Alignment = LN->getAlignment();
10554 
10555     // If this load is properly aligned, then it is legal.
10556     if (Alignment >= MemVT.getStoreSize())
10557       return Op;
10558 
10559     EVT ScalarVT = Op.getValueType().getScalarType(),
10560         ScalarMemVT = MemVT.getScalarType();
10561     unsigned Stride = ScalarMemVT.getStoreSize();
10562 
10563     SDValue Vals[4], LoadChains[4];
10564     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10565       SDValue Load;
10566       if (ScalarVT != ScalarMemVT)
10567         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10568                               BasePtr,
10569                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10570                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10571                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10572       else
10573         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10574                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10575                            MinAlign(Alignment, Idx * Stride),
10576                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10577 
10578       if (Idx == 0 && LN->isIndexed()) {
10579         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10580                "Unknown addressing mode on vector load");
10581         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10582                                   LN->getAddressingMode());
10583       }
10584 
10585       Vals[Idx] = Load;
10586       LoadChains[Idx] = Load.getValue(1);
10587 
10588       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10589                             DAG.getConstant(Stride, dl,
10590                                             BasePtr.getValueType()));
10591     }
10592 
10593     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10594     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10595 
10596     if (LN->isIndexed()) {
10597       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10598       return DAG.getMergeValues(RetOps, dl);
10599     }
10600 
10601     SDValue RetOps[] = { Value, TF };
10602     return DAG.getMergeValues(RetOps, dl);
10603   }
10604 
10605   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10606   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10607 
10608   // To lower v4i1 from a byte array, we load the byte elements of the
10609   // vector and then reuse the BUILD_VECTOR logic.
10610 
10611   SDValue VectElmts[4], VectElmtChains[4];
10612   for (unsigned i = 0; i < 4; ++i) {
10613     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10614     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10615 
10616     VectElmts[i] = DAG.getExtLoad(
10617         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10618         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10619         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10620     VectElmtChains[i] = VectElmts[i].getValue(1);
10621   }
10622 
10623   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10624   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10625 
10626   SDValue RVals[] = { Value, LoadChain };
10627   return DAG.getMergeValues(RVals, dl);
10628 }
10629 
10630 /// Lowering for QPX v4i1 stores
10631 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10632                                             SelectionDAG &DAG) const {
10633   SDLoc dl(Op);
10634   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10635   SDValue StoreChain = SN->getChain();
10636   SDValue BasePtr = SN->getBasePtr();
10637   SDValue Value = SN->getValue();
10638 
10639   if (Value.getValueType() == MVT::v4f64 ||
10640       Value.getValueType() == MVT::v4f32) {
10641     EVT MemVT = SN->getMemoryVT();
10642     unsigned Alignment = SN->getAlignment();
10643 
10644     // If this store is properly aligned, then it is legal.
10645     if (Alignment >= MemVT.getStoreSize())
10646       return Op;
10647 
10648     EVT ScalarVT = Value.getValueType().getScalarType(),
10649         ScalarMemVT = MemVT.getScalarType();
10650     unsigned Stride = ScalarMemVT.getStoreSize();
10651 
10652     SDValue Stores[4];
10653     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10654       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10655                                DAG.getVectorIdxConstant(Idx, dl));
10656       SDValue Store;
10657       if (ScalarVT != ScalarMemVT)
10658         Store =
10659             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10660                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10661                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10662                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10663       else
10664         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10665                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10666                              MinAlign(Alignment, Idx * Stride),
10667                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10668 
10669       if (Idx == 0 && SN->isIndexed()) {
10670         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10671                "Unknown addressing mode on vector store");
10672         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10673                                     SN->getAddressingMode());
10674       }
10675 
10676       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10677                             DAG.getConstant(Stride, dl,
10678                                             BasePtr.getValueType()));
10679       Stores[Idx] = Store;
10680     }
10681 
10682     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10683 
10684     if (SN->isIndexed()) {
10685       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10686       return DAG.getMergeValues(RetOps, dl);
10687     }
10688 
10689     return TF;
10690   }
10691 
10692   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10693   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10694 
10695   // The values are now known to be -1 (false) or 1 (true). To convert this
10696   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10697   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10698   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10699 
10700   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10701   // understand how to form the extending load.
10702   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10703 
10704   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10705 
10706   // Now convert to an integer and store.
10707   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10708     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10709     Value);
10710 
10711   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10712   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10713   MachinePointerInfo PtrInfo =
10714       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10715   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10716   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10717 
10718   SDValue Ops[] = {StoreChain,
10719                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10720                    Value, FIdx};
10721   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10722 
10723   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10724     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10725 
10726   // Move data into the byte array.
10727   SDValue Loads[4], LoadChains[4];
10728   for (unsigned i = 0; i < 4; ++i) {
10729     unsigned Offset = 4*i;
10730     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10731     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10732 
10733     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10734                            PtrInfo.getWithOffset(Offset));
10735     LoadChains[i] = Loads[i].getValue(1);
10736   }
10737 
10738   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10739 
10740   SDValue Stores[4];
10741   for (unsigned i = 0; i < 4; ++i) {
10742     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10743     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10744 
10745     Stores[i] = DAG.getTruncStore(
10746         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10747         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10748         SN->getAAInfo());
10749   }
10750 
10751   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10752 
10753   return StoreChain;
10754 }
10755 
10756 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10757   SDLoc dl(Op);
10758   if (Op.getValueType() == MVT::v4i32) {
10759     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10760 
10761     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10762     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10763 
10764     SDValue RHSSwap =   // = vrlw RHS, 16
10765       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10766 
10767     // Shrinkify inputs to v8i16.
10768     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10769     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10770     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10771 
10772     // Low parts multiplied together, generating 32-bit results (we ignore the
10773     // top parts).
10774     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10775                                         LHS, RHS, DAG, dl, MVT::v4i32);
10776 
10777     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10778                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10779     // Shift the high parts up 16 bits.
10780     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10781                               Neg16, DAG, dl);
10782     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10783   } else if (Op.getValueType() == MVT::v16i8) {
10784     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10785     bool isLittleEndian = Subtarget.isLittleEndian();
10786 
10787     // Multiply the even 8-bit parts, producing 16-bit sums.
10788     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10789                                            LHS, RHS, DAG, dl, MVT::v8i16);
10790     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10791 
10792     // Multiply the odd 8-bit parts, producing 16-bit sums.
10793     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10794                                           LHS, RHS, DAG, dl, MVT::v8i16);
10795     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10796 
10797     // Merge the results together.  Because vmuleub and vmuloub are
10798     // instructions with a big-endian bias, we must reverse the
10799     // element numbering and reverse the meaning of "odd" and "even"
10800     // when generating little endian code.
10801     int Ops[16];
10802     for (unsigned i = 0; i != 8; ++i) {
10803       if (isLittleEndian) {
10804         Ops[i*2  ] = 2*i;
10805         Ops[i*2+1] = 2*i+16;
10806       } else {
10807         Ops[i*2  ] = 2*i+1;
10808         Ops[i*2+1] = 2*i+1+16;
10809       }
10810     }
10811     if (isLittleEndian)
10812       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10813     else
10814       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10815   } else {
10816     llvm_unreachable("Unknown mul to lower!");
10817   }
10818 }
10819 
10820 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10821 
10822   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10823 
10824   EVT VT = Op.getValueType();
10825   assert(VT.isVector() &&
10826          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10827   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10828           VT == MVT::v16i8) &&
10829          "Unexpected vector element type!");
10830   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10831          "Current subtarget doesn't support smax v2i64!");
10832 
10833   // For vector abs, it can be lowered to:
10834   // abs x
10835   // ==>
10836   // y = -x
10837   // smax(x, y)
10838 
10839   SDLoc dl(Op);
10840   SDValue X = Op.getOperand(0);
10841   SDValue Zero = DAG.getConstant(0, dl, VT);
10842   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10843 
10844   // SMAX patch https://reviews.llvm.org/D47332
10845   // hasn't landed yet, so use intrinsic first here.
10846   // TODO: Should use SMAX directly once SMAX patch landed
10847   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10848   if (VT == MVT::v2i64)
10849     BifID = Intrinsic::ppc_altivec_vmaxsd;
10850   else if (VT == MVT::v8i16)
10851     BifID = Intrinsic::ppc_altivec_vmaxsh;
10852   else if (VT == MVT::v16i8)
10853     BifID = Intrinsic::ppc_altivec_vmaxsb;
10854 
10855   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10856 }
10857 
10858 // Custom lowering for fpext vf32 to v2f64
10859 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10860 
10861   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10862          "Should only be called for ISD::FP_EXTEND");
10863 
10864   // FIXME: handle extends from half precision float vectors on P9.
10865   // We only want to custom lower an extend from v2f32 to v2f64.
10866   if (Op.getValueType() != MVT::v2f64 ||
10867       Op.getOperand(0).getValueType() != MVT::v2f32)
10868     return SDValue();
10869 
10870   SDLoc dl(Op);
10871   SDValue Op0 = Op.getOperand(0);
10872 
10873   switch (Op0.getOpcode()) {
10874   default:
10875     return SDValue();
10876   case ISD::EXTRACT_SUBVECTOR: {
10877     assert(Op0.getNumOperands() == 2 &&
10878            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10879            "Node should have 2 operands with second one being a constant!");
10880 
10881     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10882       return SDValue();
10883 
10884     // Custom lower is only done for high or low doubleword.
10885     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10886     if (Idx % 2 != 0)
10887       return SDValue();
10888 
10889     // Since input is v4f32, at this point Idx is either 0 or 2.
10890     // Shift to get the doubleword position we want.
10891     int DWord = Idx >> 1;
10892 
10893     // High and low word positions are different on little endian.
10894     if (Subtarget.isLittleEndian())
10895       DWord ^= 0x1;
10896 
10897     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10898                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10899   }
10900   case ISD::FADD:
10901   case ISD::FMUL:
10902   case ISD::FSUB: {
10903     SDValue NewLoad[2];
10904     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10905       // Ensure both input are loads.
10906       SDValue LdOp = Op0.getOperand(i);
10907       if (LdOp.getOpcode() != ISD::LOAD)
10908         return SDValue();
10909       // Generate new load node.
10910       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10911       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10912       NewLoad[i] = DAG.getMemIntrinsicNode(
10913           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10914           LD->getMemoryVT(), LD->getMemOperand());
10915     }
10916     SDValue NewOp =
10917         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10918                     NewLoad[1], Op0.getNode()->getFlags());
10919     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10920                        DAG.getConstant(0, dl, MVT::i32));
10921   }
10922   case ISD::LOAD: {
10923     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10924     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10925     SDValue NewLd = DAG.getMemIntrinsicNode(
10926         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10927         LD->getMemoryVT(), LD->getMemOperand());
10928     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10929                        DAG.getConstant(0, dl, MVT::i32));
10930   }
10931   }
10932   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10933 }
10934 
10935 /// LowerOperation - Provide custom lowering hooks for some operations.
10936 ///
10937 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10938   switch (Op.getOpcode()) {
10939   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10940   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10941   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10942   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10943   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10944   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10945   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10946   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10947   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10948 
10949   // Variable argument lowering.
10950   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10951   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10952   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10953 
10954   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10955   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10956   case ISD::GET_DYNAMIC_AREA_OFFSET:
10957     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10958 
10959   // Exception handling lowering.
10960   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10961   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10962   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10963 
10964   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10965   case ISD::STORE:              return LowerSTORE(Op, DAG);
10966   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10967   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10968   case ISD::FP_TO_UINT:
10969   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10970   case ISD::UINT_TO_FP:
10971   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10972   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10973 
10974   // Lower 64-bit shifts.
10975   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10976   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10977   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10978 
10979   // Vector-related lowering.
10980   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10981   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10982   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10983   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10984   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10985   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10986   case ISD::MUL:                return LowerMUL(Op, DAG);
10987   case ISD::ABS:                return LowerABS(Op, DAG);
10988   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10989   case ISD::ROTL:               return LowerROTL(Op, DAG);
10990 
10991   // For counter-based loop handling.
10992   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10993 
10994   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10995 
10996   // Frame & Return address.
10997   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10998   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10999 
11000   case ISD::INTRINSIC_VOID:
11001     return LowerINTRINSIC_VOID(Op, DAG);
11002   case ISD::SREM:
11003   case ISD::UREM:
11004     return LowerREM(Op, DAG);
11005   case ISD::BSWAP:
11006     return LowerBSWAP(Op, DAG);
11007   case ISD::ATOMIC_CMP_SWAP:
11008     return LowerATOMIC_CMP_SWAP(Op, DAG);
11009   }
11010 }
11011 
11012 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11013                                            SmallVectorImpl<SDValue>&Results,
11014                                            SelectionDAG &DAG) const {
11015   SDLoc dl(N);
11016   switch (N->getOpcode()) {
11017   default:
11018     llvm_unreachable("Do not know how to custom type legalize this operation!");
11019   case ISD::READCYCLECOUNTER: {
11020     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11021     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11022 
11023     Results.push_back(
11024         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11025     Results.push_back(RTB.getValue(2));
11026     break;
11027   }
11028   case ISD::INTRINSIC_W_CHAIN: {
11029     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11030         Intrinsic::loop_decrement)
11031       break;
11032 
11033     assert(N->getValueType(0) == MVT::i1 &&
11034            "Unexpected result type for CTR decrement intrinsic");
11035     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11036                                  N->getValueType(0));
11037     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11038     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11039                                  N->getOperand(1));
11040 
11041     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11042     Results.push_back(NewInt.getValue(1));
11043     break;
11044   }
11045   case ISD::VAARG: {
11046     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11047       return;
11048 
11049     EVT VT = N->getValueType(0);
11050 
11051     if (VT == MVT::i64) {
11052       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11053 
11054       Results.push_back(NewNode);
11055       Results.push_back(NewNode.getValue(1));
11056     }
11057     return;
11058   }
11059   case ISD::FP_TO_SINT:
11060   case ISD::FP_TO_UINT:
11061     // LowerFP_TO_INT() can only handle f32 and f64.
11062     if (N->getOperand(0).getValueType() == MVT::ppcf128)
11063       return;
11064     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11065     return;
11066   case ISD::TRUNCATE: {
11067     EVT TrgVT = N->getValueType(0);
11068     EVT OpVT = N->getOperand(0).getValueType();
11069     if (TrgVT.isVector() &&
11070         isOperationCustom(N->getOpcode(), TrgVT) &&
11071         OpVT.getSizeInBits() <= 128 &&
11072         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
11073       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
11074     return;
11075   }
11076   case ISD::BITCAST:
11077     // Don't handle bitcast here.
11078     return;
11079   case ISD::FP_EXTEND:
11080     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11081     if (Lowered)
11082       Results.push_back(Lowered);
11083     return;
11084   }
11085 }
11086 
11087 //===----------------------------------------------------------------------===//
11088 //  Other Lowering Code
11089 //===----------------------------------------------------------------------===//
11090 
11091 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
11092   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11093   Function *Func = Intrinsic::getDeclaration(M, Id);
11094   return Builder.CreateCall(Func, {});
11095 }
11096 
11097 // The mappings for emitLeading/TrailingFence is taken from
11098 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11099 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11100                                                  Instruction *Inst,
11101                                                  AtomicOrdering Ord) const {
11102   if (Ord == AtomicOrdering::SequentiallyConsistent)
11103     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11104   if (isReleaseOrStronger(Ord))
11105     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11106   return nullptr;
11107 }
11108 
11109 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11110                                                   Instruction *Inst,
11111                                                   AtomicOrdering Ord) const {
11112   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11113     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11114     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11115     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11116     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11117       return Builder.CreateCall(
11118           Intrinsic::getDeclaration(
11119               Builder.GetInsertBlock()->getParent()->getParent(),
11120               Intrinsic::ppc_cfence, {Inst->getType()}),
11121           {Inst});
11122     // FIXME: Can use isync for rmw operation.
11123     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11124   }
11125   return nullptr;
11126 }
11127 
11128 MachineBasicBlock *
11129 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11130                                     unsigned AtomicSize,
11131                                     unsigned BinOpcode,
11132                                     unsigned CmpOpcode,
11133                                     unsigned CmpPred) const {
11134   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11135   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11136 
11137   auto LoadMnemonic = PPC::LDARX;
11138   auto StoreMnemonic = PPC::STDCX;
11139   switch (AtomicSize) {
11140   default:
11141     llvm_unreachable("Unexpected size of atomic entity");
11142   case 1:
11143     LoadMnemonic = PPC::LBARX;
11144     StoreMnemonic = PPC::STBCX;
11145     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11146     break;
11147   case 2:
11148     LoadMnemonic = PPC::LHARX;
11149     StoreMnemonic = PPC::STHCX;
11150     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11151     break;
11152   case 4:
11153     LoadMnemonic = PPC::LWARX;
11154     StoreMnemonic = PPC::STWCX;
11155     break;
11156   case 8:
11157     LoadMnemonic = PPC::LDARX;
11158     StoreMnemonic = PPC::STDCX;
11159     break;
11160   }
11161 
11162   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11163   MachineFunction *F = BB->getParent();
11164   MachineFunction::iterator It = ++BB->getIterator();
11165 
11166   Register dest = MI.getOperand(0).getReg();
11167   Register ptrA = MI.getOperand(1).getReg();
11168   Register ptrB = MI.getOperand(2).getReg();
11169   Register incr = MI.getOperand(3).getReg();
11170   DebugLoc dl = MI.getDebugLoc();
11171 
11172   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11173   MachineBasicBlock *loop2MBB =
11174     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11175   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11176   F->insert(It, loopMBB);
11177   if (CmpOpcode)
11178     F->insert(It, loop2MBB);
11179   F->insert(It, exitMBB);
11180   exitMBB->splice(exitMBB->begin(), BB,
11181                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11182   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11183 
11184   MachineRegisterInfo &RegInfo = F->getRegInfo();
11185   Register TmpReg = (!BinOpcode) ? incr :
11186     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11187                                            : &PPC::GPRCRegClass);
11188 
11189   //  thisMBB:
11190   //   ...
11191   //   fallthrough --> loopMBB
11192   BB->addSuccessor(loopMBB);
11193 
11194   //  loopMBB:
11195   //   l[wd]arx dest, ptr
11196   //   add r0, dest, incr
11197   //   st[wd]cx. r0, ptr
11198   //   bne- loopMBB
11199   //   fallthrough --> exitMBB
11200 
11201   // For max/min...
11202   //  loopMBB:
11203   //   l[wd]arx dest, ptr
11204   //   cmpl?[wd] incr, dest
11205   //   bgt exitMBB
11206   //  loop2MBB:
11207   //   st[wd]cx. dest, ptr
11208   //   bne- loopMBB
11209   //   fallthrough --> exitMBB
11210 
11211   BB = loopMBB;
11212   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11213     .addReg(ptrA).addReg(ptrB);
11214   if (BinOpcode)
11215     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11216   if (CmpOpcode) {
11217     // Signed comparisons of byte or halfword values must be sign-extended.
11218     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11219       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11220       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11221               ExtReg).addReg(dest);
11222       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11223         .addReg(incr).addReg(ExtReg);
11224     } else
11225       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11226         .addReg(incr).addReg(dest);
11227 
11228     BuildMI(BB, dl, TII->get(PPC::BCC))
11229       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11230     BB->addSuccessor(loop2MBB);
11231     BB->addSuccessor(exitMBB);
11232     BB = loop2MBB;
11233   }
11234   BuildMI(BB, dl, TII->get(StoreMnemonic))
11235     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11236   BuildMI(BB, dl, TII->get(PPC::BCC))
11237     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11238   BB->addSuccessor(loopMBB);
11239   BB->addSuccessor(exitMBB);
11240 
11241   //  exitMBB:
11242   //   ...
11243   BB = exitMBB;
11244   return BB;
11245 }
11246 
11247 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11248     MachineInstr &MI, MachineBasicBlock *BB,
11249     bool is8bit, // operation
11250     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11251   // If we support part-word atomic mnemonics, just use them
11252   if (Subtarget.hasPartwordAtomics())
11253     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11254                             CmpPred);
11255 
11256   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11257   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11258   // In 64 bit mode we have to use 64 bits for addresses, even though the
11259   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11260   // registers without caring whether they're 32 or 64, but here we're
11261   // doing actual arithmetic on the addresses.
11262   bool is64bit = Subtarget.isPPC64();
11263   bool isLittleEndian = Subtarget.isLittleEndian();
11264   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11265 
11266   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11267   MachineFunction *F = BB->getParent();
11268   MachineFunction::iterator It = ++BB->getIterator();
11269 
11270   Register dest = MI.getOperand(0).getReg();
11271   Register ptrA = MI.getOperand(1).getReg();
11272   Register ptrB = MI.getOperand(2).getReg();
11273   Register incr = MI.getOperand(3).getReg();
11274   DebugLoc dl = MI.getDebugLoc();
11275 
11276   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11277   MachineBasicBlock *loop2MBB =
11278       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11279   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11280   F->insert(It, loopMBB);
11281   if (CmpOpcode)
11282     F->insert(It, loop2MBB);
11283   F->insert(It, exitMBB);
11284   exitMBB->splice(exitMBB->begin(), BB,
11285                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11286   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11287 
11288   MachineRegisterInfo &RegInfo = F->getRegInfo();
11289   const TargetRegisterClass *RC =
11290       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11291   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11292 
11293   Register PtrReg = RegInfo.createVirtualRegister(RC);
11294   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11295   Register ShiftReg =
11296       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11297   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11298   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11299   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11300   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11301   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11302   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11303   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11304   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11305   Register Ptr1Reg;
11306   Register TmpReg =
11307       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11308 
11309   //  thisMBB:
11310   //   ...
11311   //   fallthrough --> loopMBB
11312   BB->addSuccessor(loopMBB);
11313 
11314   // The 4-byte load must be aligned, while a char or short may be
11315   // anywhere in the word.  Hence all this nasty bookkeeping code.
11316   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11317   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11318   //   xori shift, shift1, 24 [16]
11319   //   rlwinm ptr, ptr1, 0, 0, 29
11320   //   slw incr2, incr, shift
11321   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11322   //   slw mask, mask2, shift
11323   //  loopMBB:
11324   //   lwarx tmpDest, ptr
11325   //   add tmp, tmpDest, incr2
11326   //   andc tmp2, tmpDest, mask
11327   //   and tmp3, tmp, mask
11328   //   or tmp4, tmp3, tmp2
11329   //   stwcx. tmp4, ptr
11330   //   bne- loopMBB
11331   //   fallthrough --> exitMBB
11332   //   srw dest, tmpDest, shift
11333   if (ptrA != ZeroReg) {
11334     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11335     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11336         .addReg(ptrA)
11337         .addReg(ptrB);
11338   } else {
11339     Ptr1Reg = ptrB;
11340   }
11341   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11342   // mode.
11343   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11344       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11345       .addImm(3)
11346       .addImm(27)
11347       .addImm(is8bit ? 28 : 27);
11348   if (!isLittleEndian)
11349     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11350         .addReg(Shift1Reg)
11351         .addImm(is8bit ? 24 : 16);
11352   if (is64bit)
11353     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11354         .addReg(Ptr1Reg)
11355         .addImm(0)
11356         .addImm(61);
11357   else
11358     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11359         .addReg(Ptr1Reg)
11360         .addImm(0)
11361         .addImm(0)
11362         .addImm(29);
11363   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11364   if (is8bit)
11365     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11366   else {
11367     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11368     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11369         .addReg(Mask3Reg)
11370         .addImm(65535);
11371   }
11372   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11373       .addReg(Mask2Reg)
11374       .addReg(ShiftReg);
11375 
11376   BB = loopMBB;
11377   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11378       .addReg(ZeroReg)
11379       .addReg(PtrReg);
11380   if (BinOpcode)
11381     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11382         .addReg(Incr2Reg)
11383         .addReg(TmpDestReg);
11384   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11385       .addReg(TmpDestReg)
11386       .addReg(MaskReg);
11387   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11388   if (CmpOpcode) {
11389     // For unsigned comparisons, we can directly compare the shifted values.
11390     // For signed comparisons we shift and sign extend.
11391     Register SReg = RegInfo.createVirtualRegister(GPRC);
11392     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11393         .addReg(TmpDestReg)
11394         .addReg(MaskReg);
11395     unsigned ValueReg = SReg;
11396     unsigned CmpReg = Incr2Reg;
11397     if (CmpOpcode == PPC::CMPW) {
11398       ValueReg = RegInfo.createVirtualRegister(GPRC);
11399       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11400           .addReg(SReg)
11401           .addReg(ShiftReg);
11402       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11403       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11404           .addReg(ValueReg);
11405       ValueReg = ValueSReg;
11406       CmpReg = incr;
11407     }
11408     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11409         .addReg(CmpReg)
11410         .addReg(ValueReg);
11411     BuildMI(BB, dl, TII->get(PPC::BCC))
11412         .addImm(CmpPred)
11413         .addReg(PPC::CR0)
11414         .addMBB(exitMBB);
11415     BB->addSuccessor(loop2MBB);
11416     BB->addSuccessor(exitMBB);
11417     BB = loop2MBB;
11418   }
11419   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11420   BuildMI(BB, dl, TII->get(PPC::STWCX))
11421       .addReg(Tmp4Reg)
11422       .addReg(ZeroReg)
11423       .addReg(PtrReg);
11424   BuildMI(BB, dl, TII->get(PPC::BCC))
11425       .addImm(PPC::PRED_NE)
11426       .addReg(PPC::CR0)
11427       .addMBB(loopMBB);
11428   BB->addSuccessor(loopMBB);
11429   BB->addSuccessor(exitMBB);
11430 
11431   //  exitMBB:
11432   //   ...
11433   BB = exitMBB;
11434   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11435       .addReg(TmpDestReg)
11436       .addReg(ShiftReg);
11437   return BB;
11438 }
11439 
11440 llvm::MachineBasicBlock *
11441 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11442                                     MachineBasicBlock *MBB) const {
11443   DebugLoc DL = MI.getDebugLoc();
11444   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11445   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11446 
11447   MachineFunction *MF = MBB->getParent();
11448   MachineRegisterInfo &MRI = MF->getRegInfo();
11449 
11450   const BasicBlock *BB = MBB->getBasicBlock();
11451   MachineFunction::iterator I = ++MBB->getIterator();
11452 
11453   Register DstReg = MI.getOperand(0).getReg();
11454   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11455   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11456   Register mainDstReg = MRI.createVirtualRegister(RC);
11457   Register restoreDstReg = MRI.createVirtualRegister(RC);
11458 
11459   MVT PVT = getPointerTy(MF->getDataLayout());
11460   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11461          "Invalid Pointer Size!");
11462   // For v = setjmp(buf), we generate
11463   //
11464   // thisMBB:
11465   //  SjLjSetup mainMBB
11466   //  bl mainMBB
11467   //  v_restore = 1
11468   //  b sinkMBB
11469   //
11470   // mainMBB:
11471   //  buf[LabelOffset] = LR
11472   //  v_main = 0
11473   //
11474   // sinkMBB:
11475   //  v = phi(main, restore)
11476   //
11477 
11478   MachineBasicBlock *thisMBB = MBB;
11479   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11480   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11481   MF->insert(I, mainMBB);
11482   MF->insert(I, sinkMBB);
11483 
11484   MachineInstrBuilder MIB;
11485 
11486   // Transfer the remainder of BB and its successor edges to sinkMBB.
11487   sinkMBB->splice(sinkMBB->begin(), MBB,
11488                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11489   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11490 
11491   // Note that the structure of the jmp_buf used here is not compatible
11492   // with that used by libc, and is not designed to be. Specifically, it
11493   // stores only those 'reserved' registers that LLVM does not otherwise
11494   // understand how to spill. Also, by convention, by the time this
11495   // intrinsic is called, Clang has already stored the frame address in the
11496   // first slot of the buffer and stack address in the third. Following the
11497   // X86 target code, we'll store the jump address in the second slot. We also
11498   // need to save the TOC pointer (R2) to handle jumps between shared
11499   // libraries, and that will be stored in the fourth slot. The thread
11500   // identifier (R13) is not affected.
11501 
11502   // thisMBB:
11503   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11504   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11505   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11506 
11507   // Prepare IP either in reg.
11508   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11509   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11510   Register BufReg = MI.getOperand(1).getReg();
11511 
11512   if (Subtarget.is64BitELFABI()) {
11513     setUsesTOCBasePtr(*MBB->getParent());
11514     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11515               .addReg(PPC::X2)
11516               .addImm(TOCOffset)
11517               .addReg(BufReg)
11518               .cloneMemRefs(MI);
11519   }
11520 
11521   // Naked functions never have a base pointer, and so we use r1. For all
11522   // other functions, this decision must be delayed until during PEI.
11523   unsigned BaseReg;
11524   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11525     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11526   else
11527     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11528 
11529   MIB = BuildMI(*thisMBB, MI, DL,
11530                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11531             .addReg(BaseReg)
11532             .addImm(BPOffset)
11533             .addReg(BufReg)
11534             .cloneMemRefs(MI);
11535 
11536   // Setup
11537   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11538   MIB.addRegMask(TRI->getNoPreservedMask());
11539 
11540   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11541 
11542   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11543           .addMBB(mainMBB);
11544   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11545 
11546   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11547   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11548 
11549   // mainMBB:
11550   //  mainDstReg = 0
11551   MIB =
11552       BuildMI(mainMBB, DL,
11553               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11554 
11555   // Store IP
11556   if (Subtarget.isPPC64()) {
11557     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11558             .addReg(LabelReg)
11559             .addImm(LabelOffset)
11560             .addReg(BufReg);
11561   } else {
11562     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11563             .addReg(LabelReg)
11564             .addImm(LabelOffset)
11565             .addReg(BufReg);
11566   }
11567   MIB.cloneMemRefs(MI);
11568 
11569   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11570   mainMBB->addSuccessor(sinkMBB);
11571 
11572   // sinkMBB:
11573   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11574           TII->get(PPC::PHI), DstReg)
11575     .addReg(mainDstReg).addMBB(mainMBB)
11576     .addReg(restoreDstReg).addMBB(thisMBB);
11577 
11578   MI.eraseFromParent();
11579   return sinkMBB;
11580 }
11581 
11582 MachineBasicBlock *
11583 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11584                                      MachineBasicBlock *MBB) const {
11585   DebugLoc DL = MI.getDebugLoc();
11586   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11587 
11588   MachineFunction *MF = MBB->getParent();
11589   MachineRegisterInfo &MRI = MF->getRegInfo();
11590 
11591   MVT PVT = getPointerTy(MF->getDataLayout());
11592   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11593          "Invalid Pointer Size!");
11594 
11595   const TargetRegisterClass *RC =
11596     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11597   Register Tmp = MRI.createVirtualRegister(RC);
11598   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11599   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11600   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11601   unsigned BP =
11602       (PVT == MVT::i64)
11603           ? PPC::X30
11604           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11605                                                               : PPC::R30);
11606 
11607   MachineInstrBuilder MIB;
11608 
11609   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11610   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11611   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11612   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11613 
11614   Register BufReg = MI.getOperand(0).getReg();
11615 
11616   // Reload FP (the jumped-to function may not have had a
11617   // frame pointer, and if so, then its r31 will be restored
11618   // as necessary).
11619   if (PVT == MVT::i64) {
11620     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11621             .addImm(0)
11622             .addReg(BufReg);
11623   } else {
11624     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11625             .addImm(0)
11626             .addReg(BufReg);
11627   }
11628   MIB.cloneMemRefs(MI);
11629 
11630   // Reload IP
11631   if (PVT == MVT::i64) {
11632     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11633             .addImm(LabelOffset)
11634             .addReg(BufReg);
11635   } else {
11636     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11637             .addImm(LabelOffset)
11638             .addReg(BufReg);
11639   }
11640   MIB.cloneMemRefs(MI);
11641 
11642   // Reload SP
11643   if (PVT == MVT::i64) {
11644     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11645             .addImm(SPOffset)
11646             .addReg(BufReg);
11647   } else {
11648     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11649             .addImm(SPOffset)
11650             .addReg(BufReg);
11651   }
11652   MIB.cloneMemRefs(MI);
11653 
11654   // Reload BP
11655   if (PVT == MVT::i64) {
11656     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11657             .addImm(BPOffset)
11658             .addReg(BufReg);
11659   } else {
11660     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11661             .addImm(BPOffset)
11662             .addReg(BufReg);
11663   }
11664   MIB.cloneMemRefs(MI);
11665 
11666   // Reload TOC
11667   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11668     setUsesTOCBasePtr(*MBB->getParent());
11669     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11670               .addImm(TOCOffset)
11671               .addReg(BufReg)
11672               .cloneMemRefs(MI);
11673   }
11674 
11675   // Jump
11676   BuildMI(*MBB, MI, DL,
11677           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11678   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11679 
11680   MI.eraseFromParent();
11681   return MBB;
11682 }
11683 
11684 MachineBasicBlock *
11685 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11686                                                MachineBasicBlock *BB) const {
11687   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11688       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11689     if (Subtarget.is64BitELFABI() &&
11690         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11691         !Subtarget.isUsingPCRelativeCalls()) {
11692       // Call lowering should have added an r2 operand to indicate a dependence
11693       // on the TOC base pointer value. It can't however, because there is no
11694       // way to mark the dependence as implicit there, and so the stackmap code
11695       // will confuse it with a regular operand. Instead, add the dependence
11696       // here.
11697       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11698     }
11699 
11700     return emitPatchPoint(MI, BB);
11701   }
11702 
11703   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11704       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11705     return emitEHSjLjSetJmp(MI, BB);
11706   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11707              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11708     return emitEHSjLjLongJmp(MI, BB);
11709   }
11710 
11711   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11712 
11713   // To "insert" these instructions we actually have to insert their
11714   // control-flow patterns.
11715   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11716   MachineFunction::iterator It = ++BB->getIterator();
11717 
11718   MachineFunction *F = BB->getParent();
11719 
11720   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11721       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11722       MI.getOpcode() == PPC::SELECT_I8) {
11723     SmallVector<MachineOperand, 2> Cond;
11724     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11725         MI.getOpcode() == PPC::SELECT_CC_I8)
11726       Cond.push_back(MI.getOperand(4));
11727     else
11728       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11729     Cond.push_back(MI.getOperand(1));
11730 
11731     DebugLoc dl = MI.getDebugLoc();
11732     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11733                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11734   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11735              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11736              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11737              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11738              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11739              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11740              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11741              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11742              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11743              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11744              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11745              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11746              MI.getOpcode() == PPC::SELECT_F4 ||
11747              MI.getOpcode() == PPC::SELECT_F8 ||
11748              MI.getOpcode() == PPC::SELECT_F16 ||
11749              MI.getOpcode() == PPC::SELECT_QFRC ||
11750              MI.getOpcode() == PPC::SELECT_QSRC ||
11751              MI.getOpcode() == PPC::SELECT_QBRC ||
11752              MI.getOpcode() == PPC::SELECT_SPE ||
11753              MI.getOpcode() == PPC::SELECT_SPE4 ||
11754              MI.getOpcode() == PPC::SELECT_VRRC ||
11755              MI.getOpcode() == PPC::SELECT_VSFRC ||
11756              MI.getOpcode() == PPC::SELECT_VSSRC ||
11757              MI.getOpcode() == PPC::SELECT_VSRC) {
11758     // The incoming instruction knows the destination vreg to set, the
11759     // condition code register to branch on, the true/false values to
11760     // select between, and a branch opcode to use.
11761 
11762     //  thisMBB:
11763     //  ...
11764     //   TrueVal = ...
11765     //   cmpTY ccX, r1, r2
11766     //   bCC copy1MBB
11767     //   fallthrough --> copy0MBB
11768     MachineBasicBlock *thisMBB = BB;
11769     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11770     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11771     DebugLoc dl = MI.getDebugLoc();
11772     F->insert(It, copy0MBB);
11773     F->insert(It, sinkMBB);
11774 
11775     // Transfer the remainder of BB and its successor edges to sinkMBB.
11776     sinkMBB->splice(sinkMBB->begin(), BB,
11777                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11778     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11779 
11780     // Next, add the true and fallthrough blocks as its successors.
11781     BB->addSuccessor(copy0MBB);
11782     BB->addSuccessor(sinkMBB);
11783 
11784     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11785         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11786         MI.getOpcode() == PPC::SELECT_F16 ||
11787         MI.getOpcode() == PPC::SELECT_SPE4 ||
11788         MI.getOpcode() == PPC::SELECT_SPE ||
11789         MI.getOpcode() == PPC::SELECT_QFRC ||
11790         MI.getOpcode() == PPC::SELECT_QSRC ||
11791         MI.getOpcode() == PPC::SELECT_QBRC ||
11792         MI.getOpcode() == PPC::SELECT_VRRC ||
11793         MI.getOpcode() == PPC::SELECT_VSFRC ||
11794         MI.getOpcode() == PPC::SELECT_VSSRC ||
11795         MI.getOpcode() == PPC::SELECT_VSRC) {
11796       BuildMI(BB, dl, TII->get(PPC::BC))
11797           .addReg(MI.getOperand(1).getReg())
11798           .addMBB(sinkMBB);
11799     } else {
11800       unsigned SelectPred = MI.getOperand(4).getImm();
11801       BuildMI(BB, dl, TII->get(PPC::BCC))
11802           .addImm(SelectPred)
11803           .addReg(MI.getOperand(1).getReg())
11804           .addMBB(sinkMBB);
11805     }
11806 
11807     //  copy0MBB:
11808     //   %FalseValue = ...
11809     //   # fallthrough to sinkMBB
11810     BB = copy0MBB;
11811 
11812     // Update machine-CFG edges
11813     BB->addSuccessor(sinkMBB);
11814 
11815     //  sinkMBB:
11816     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11817     //  ...
11818     BB = sinkMBB;
11819     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11820         .addReg(MI.getOperand(3).getReg())
11821         .addMBB(copy0MBB)
11822         .addReg(MI.getOperand(2).getReg())
11823         .addMBB(thisMBB);
11824   } else if (MI.getOpcode() == PPC::ReadTB) {
11825     // To read the 64-bit time-base register on a 32-bit target, we read the
11826     // two halves. Should the counter have wrapped while it was being read, we
11827     // need to try again.
11828     // ...
11829     // readLoop:
11830     // mfspr Rx,TBU # load from TBU
11831     // mfspr Ry,TB  # load from TB
11832     // mfspr Rz,TBU # load from TBU
11833     // cmpw crX,Rx,Rz # check if 'old'='new'
11834     // bne readLoop   # branch if they're not equal
11835     // ...
11836 
11837     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11838     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11839     DebugLoc dl = MI.getDebugLoc();
11840     F->insert(It, readMBB);
11841     F->insert(It, sinkMBB);
11842 
11843     // Transfer the remainder of BB and its successor edges to sinkMBB.
11844     sinkMBB->splice(sinkMBB->begin(), BB,
11845                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11846     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11847 
11848     BB->addSuccessor(readMBB);
11849     BB = readMBB;
11850 
11851     MachineRegisterInfo &RegInfo = F->getRegInfo();
11852     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11853     Register LoReg = MI.getOperand(0).getReg();
11854     Register HiReg = MI.getOperand(1).getReg();
11855 
11856     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11857     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11858     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11859 
11860     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11861 
11862     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11863         .addReg(HiReg)
11864         .addReg(ReadAgainReg);
11865     BuildMI(BB, dl, TII->get(PPC::BCC))
11866         .addImm(PPC::PRED_NE)
11867         .addReg(CmpReg)
11868         .addMBB(readMBB);
11869 
11870     BB->addSuccessor(readMBB);
11871     BB->addSuccessor(sinkMBB);
11872   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11873     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11874   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11875     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11876   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11877     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11878   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11879     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11880 
11881   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11882     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11883   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11884     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11885   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11886     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11887   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11888     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11889 
11890   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11891     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11892   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11893     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11894   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11895     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11896   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11897     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11898 
11899   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11900     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11901   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11902     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11903   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11904     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11905   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11906     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11907 
11908   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11909     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11910   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11911     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11912   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11913     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11914   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11915     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11916 
11917   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11918     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11919   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11920     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11921   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11922     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11923   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11924     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11925 
11926   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11927     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11928   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11929     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11930   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11931     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11932   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11933     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11934 
11935   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11936     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11937   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11938     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11939   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11940     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11941   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11942     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11943 
11944   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11945     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11946   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11947     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11948   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11949     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11950   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11951     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11952 
11953   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11954     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11955   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11956     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11957   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11958     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11959   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11960     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11961 
11962   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11963     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11964   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11965     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11966   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11967     BB = EmitAtomicBinary(MI, BB, 4, 0);
11968   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11969     BB = EmitAtomicBinary(MI, BB, 8, 0);
11970   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11971            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11972            (Subtarget.hasPartwordAtomics() &&
11973             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11974            (Subtarget.hasPartwordAtomics() &&
11975             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11976     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11977 
11978     auto LoadMnemonic = PPC::LDARX;
11979     auto StoreMnemonic = PPC::STDCX;
11980     switch (MI.getOpcode()) {
11981     default:
11982       llvm_unreachable("Compare and swap of unknown size");
11983     case PPC::ATOMIC_CMP_SWAP_I8:
11984       LoadMnemonic = PPC::LBARX;
11985       StoreMnemonic = PPC::STBCX;
11986       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11987       break;
11988     case PPC::ATOMIC_CMP_SWAP_I16:
11989       LoadMnemonic = PPC::LHARX;
11990       StoreMnemonic = PPC::STHCX;
11991       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11992       break;
11993     case PPC::ATOMIC_CMP_SWAP_I32:
11994       LoadMnemonic = PPC::LWARX;
11995       StoreMnemonic = PPC::STWCX;
11996       break;
11997     case PPC::ATOMIC_CMP_SWAP_I64:
11998       LoadMnemonic = PPC::LDARX;
11999       StoreMnemonic = PPC::STDCX;
12000       break;
12001     }
12002     Register dest = MI.getOperand(0).getReg();
12003     Register ptrA = MI.getOperand(1).getReg();
12004     Register ptrB = MI.getOperand(2).getReg();
12005     Register oldval = MI.getOperand(3).getReg();
12006     Register newval = MI.getOperand(4).getReg();
12007     DebugLoc dl = MI.getDebugLoc();
12008 
12009     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12010     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12011     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12012     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12013     F->insert(It, loop1MBB);
12014     F->insert(It, loop2MBB);
12015     F->insert(It, midMBB);
12016     F->insert(It, exitMBB);
12017     exitMBB->splice(exitMBB->begin(), BB,
12018                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12019     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12020 
12021     //  thisMBB:
12022     //   ...
12023     //   fallthrough --> loopMBB
12024     BB->addSuccessor(loop1MBB);
12025 
12026     // loop1MBB:
12027     //   l[bhwd]arx dest, ptr
12028     //   cmp[wd] dest, oldval
12029     //   bne- midMBB
12030     // loop2MBB:
12031     //   st[bhwd]cx. newval, ptr
12032     //   bne- loopMBB
12033     //   b exitBB
12034     // midMBB:
12035     //   st[bhwd]cx. dest, ptr
12036     // exitBB:
12037     BB = loop1MBB;
12038     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12039     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12040         .addReg(oldval)
12041         .addReg(dest);
12042     BuildMI(BB, dl, TII->get(PPC::BCC))
12043         .addImm(PPC::PRED_NE)
12044         .addReg(PPC::CR0)
12045         .addMBB(midMBB);
12046     BB->addSuccessor(loop2MBB);
12047     BB->addSuccessor(midMBB);
12048 
12049     BB = loop2MBB;
12050     BuildMI(BB, dl, TII->get(StoreMnemonic))
12051         .addReg(newval)
12052         .addReg(ptrA)
12053         .addReg(ptrB);
12054     BuildMI(BB, dl, TII->get(PPC::BCC))
12055         .addImm(PPC::PRED_NE)
12056         .addReg(PPC::CR0)
12057         .addMBB(loop1MBB);
12058     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12059     BB->addSuccessor(loop1MBB);
12060     BB->addSuccessor(exitMBB);
12061 
12062     BB = midMBB;
12063     BuildMI(BB, dl, TII->get(StoreMnemonic))
12064         .addReg(dest)
12065         .addReg(ptrA)
12066         .addReg(ptrB);
12067     BB->addSuccessor(exitMBB);
12068 
12069     //  exitMBB:
12070     //   ...
12071     BB = exitMBB;
12072   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12073              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12074     // We must use 64-bit registers for addresses when targeting 64-bit,
12075     // since we're actually doing arithmetic on them.  Other registers
12076     // can be 32-bit.
12077     bool is64bit = Subtarget.isPPC64();
12078     bool isLittleEndian = Subtarget.isLittleEndian();
12079     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12080 
12081     Register dest = MI.getOperand(0).getReg();
12082     Register ptrA = MI.getOperand(1).getReg();
12083     Register ptrB = MI.getOperand(2).getReg();
12084     Register oldval = MI.getOperand(3).getReg();
12085     Register newval = MI.getOperand(4).getReg();
12086     DebugLoc dl = MI.getDebugLoc();
12087 
12088     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12089     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12090     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12091     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12092     F->insert(It, loop1MBB);
12093     F->insert(It, loop2MBB);
12094     F->insert(It, midMBB);
12095     F->insert(It, exitMBB);
12096     exitMBB->splice(exitMBB->begin(), BB,
12097                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12098     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12099 
12100     MachineRegisterInfo &RegInfo = F->getRegInfo();
12101     const TargetRegisterClass *RC =
12102         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12103     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12104 
12105     Register PtrReg = RegInfo.createVirtualRegister(RC);
12106     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12107     Register ShiftReg =
12108         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12109     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12110     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12111     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12112     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12113     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12114     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12115     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12116     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12117     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12118     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12119     Register Ptr1Reg;
12120     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12121     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12122     //  thisMBB:
12123     //   ...
12124     //   fallthrough --> loopMBB
12125     BB->addSuccessor(loop1MBB);
12126 
12127     // The 4-byte load must be aligned, while a char or short may be
12128     // anywhere in the word.  Hence all this nasty bookkeeping code.
12129     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12130     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12131     //   xori shift, shift1, 24 [16]
12132     //   rlwinm ptr, ptr1, 0, 0, 29
12133     //   slw newval2, newval, shift
12134     //   slw oldval2, oldval,shift
12135     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12136     //   slw mask, mask2, shift
12137     //   and newval3, newval2, mask
12138     //   and oldval3, oldval2, mask
12139     // loop1MBB:
12140     //   lwarx tmpDest, ptr
12141     //   and tmp, tmpDest, mask
12142     //   cmpw tmp, oldval3
12143     //   bne- midMBB
12144     // loop2MBB:
12145     //   andc tmp2, tmpDest, mask
12146     //   or tmp4, tmp2, newval3
12147     //   stwcx. tmp4, ptr
12148     //   bne- loop1MBB
12149     //   b exitBB
12150     // midMBB:
12151     //   stwcx. tmpDest, ptr
12152     // exitBB:
12153     //   srw dest, tmpDest, shift
12154     if (ptrA != ZeroReg) {
12155       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12156       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12157           .addReg(ptrA)
12158           .addReg(ptrB);
12159     } else {
12160       Ptr1Reg = ptrB;
12161     }
12162 
12163     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12164     // mode.
12165     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12166         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12167         .addImm(3)
12168         .addImm(27)
12169         .addImm(is8bit ? 28 : 27);
12170     if (!isLittleEndian)
12171       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12172           .addReg(Shift1Reg)
12173           .addImm(is8bit ? 24 : 16);
12174     if (is64bit)
12175       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12176           .addReg(Ptr1Reg)
12177           .addImm(0)
12178           .addImm(61);
12179     else
12180       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12181           .addReg(Ptr1Reg)
12182           .addImm(0)
12183           .addImm(0)
12184           .addImm(29);
12185     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12186         .addReg(newval)
12187         .addReg(ShiftReg);
12188     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12189         .addReg(oldval)
12190         .addReg(ShiftReg);
12191     if (is8bit)
12192       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12193     else {
12194       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12195       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12196           .addReg(Mask3Reg)
12197           .addImm(65535);
12198     }
12199     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12200         .addReg(Mask2Reg)
12201         .addReg(ShiftReg);
12202     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12203         .addReg(NewVal2Reg)
12204         .addReg(MaskReg);
12205     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12206         .addReg(OldVal2Reg)
12207         .addReg(MaskReg);
12208 
12209     BB = loop1MBB;
12210     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12211         .addReg(ZeroReg)
12212         .addReg(PtrReg);
12213     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12214         .addReg(TmpDestReg)
12215         .addReg(MaskReg);
12216     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12217         .addReg(TmpReg)
12218         .addReg(OldVal3Reg);
12219     BuildMI(BB, dl, TII->get(PPC::BCC))
12220         .addImm(PPC::PRED_NE)
12221         .addReg(PPC::CR0)
12222         .addMBB(midMBB);
12223     BB->addSuccessor(loop2MBB);
12224     BB->addSuccessor(midMBB);
12225 
12226     BB = loop2MBB;
12227     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12228         .addReg(TmpDestReg)
12229         .addReg(MaskReg);
12230     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12231         .addReg(Tmp2Reg)
12232         .addReg(NewVal3Reg);
12233     BuildMI(BB, dl, TII->get(PPC::STWCX))
12234         .addReg(Tmp4Reg)
12235         .addReg(ZeroReg)
12236         .addReg(PtrReg);
12237     BuildMI(BB, dl, TII->get(PPC::BCC))
12238         .addImm(PPC::PRED_NE)
12239         .addReg(PPC::CR0)
12240         .addMBB(loop1MBB);
12241     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12242     BB->addSuccessor(loop1MBB);
12243     BB->addSuccessor(exitMBB);
12244 
12245     BB = midMBB;
12246     BuildMI(BB, dl, TII->get(PPC::STWCX))
12247         .addReg(TmpDestReg)
12248         .addReg(ZeroReg)
12249         .addReg(PtrReg);
12250     BB->addSuccessor(exitMBB);
12251 
12252     //  exitMBB:
12253     //   ...
12254     BB = exitMBB;
12255     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12256         .addReg(TmpReg)
12257         .addReg(ShiftReg);
12258   } else if (MI.getOpcode() == PPC::FADDrtz) {
12259     // This pseudo performs an FADD with rounding mode temporarily forced
12260     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12261     // is not modeled at the SelectionDAG level.
12262     Register Dest = MI.getOperand(0).getReg();
12263     Register Src1 = MI.getOperand(1).getReg();
12264     Register Src2 = MI.getOperand(2).getReg();
12265     DebugLoc dl = MI.getDebugLoc();
12266 
12267     MachineRegisterInfo &RegInfo = F->getRegInfo();
12268     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12269 
12270     // Save FPSCR value.
12271     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12272 
12273     // Set rounding mode to round-to-zero.
12274     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
12275     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
12276 
12277     // Perform addition.
12278     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12279 
12280     // Restore FPSCR value.
12281     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12282   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12283              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12284              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12285              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12286     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12287                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12288                           ? PPC::ANDI8_rec
12289                           : PPC::ANDI_rec;
12290     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12291                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12292 
12293     MachineRegisterInfo &RegInfo = F->getRegInfo();
12294     Register Dest = RegInfo.createVirtualRegister(
12295         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12296 
12297     DebugLoc Dl = MI.getDebugLoc();
12298     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12299         .addReg(MI.getOperand(1).getReg())
12300         .addImm(1);
12301     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12302             MI.getOperand(0).getReg())
12303         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12304   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12305     DebugLoc Dl = MI.getDebugLoc();
12306     MachineRegisterInfo &RegInfo = F->getRegInfo();
12307     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12308     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12309     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12310             MI.getOperand(0).getReg())
12311         .addReg(CRReg);
12312   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12313     DebugLoc Dl = MI.getDebugLoc();
12314     unsigned Imm = MI.getOperand(1).getImm();
12315     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12316     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12317             MI.getOperand(0).getReg())
12318         .addReg(PPC::CR0EQ);
12319   } else if (MI.getOpcode() == PPC::SETRNDi) {
12320     DebugLoc dl = MI.getDebugLoc();
12321     Register OldFPSCRReg = MI.getOperand(0).getReg();
12322 
12323     // Save FPSCR value.
12324     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12325 
12326     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12327     // the following settings:
12328     //   00 Round to nearest
12329     //   01 Round to 0
12330     //   10 Round to +inf
12331     //   11 Round to -inf
12332 
12333     // When the operand is immediate, using the two least significant bits of
12334     // the immediate to set the bits 62:63 of FPSCR.
12335     unsigned Mode = MI.getOperand(1).getImm();
12336     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12337       .addImm(31);
12338 
12339     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12340       .addImm(30);
12341   } else if (MI.getOpcode() == PPC::SETRND) {
12342     DebugLoc dl = MI.getDebugLoc();
12343 
12344     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12345     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12346     // If the target doesn't have DirectMove, we should use stack to do the
12347     // conversion, because the target doesn't have the instructions like mtvsrd
12348     // or mfvsrd to do this conversion directly.
12349     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12350       if (Subtarget.hasDirectMove()) {
12351         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12352           .addReg(SrcReg);
12353       } else {
12354         // Use stack to do the register copy.
12355         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12356         MachineRegisterInfo &RegInfo = F->getRegInfo();
12357         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12358         if (RC == &PPC::F8RCRegClass) {
12359           // Copy register from F8RCRegClass to G8RCRegclass.
12360           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12361                  "Unsupported RegClass.");
12362 
12363           StoreOp = PPC::STFD;
12364           LoadOp = PPC::LD;
12365         } else {
12366           // Copy register from G8RCRegClass to F8RCRegclass.
12367           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12368                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12369                  "Unsupported RegClass.");
12370         }
12371 
12372         MachineFrameInfo &MFI = F->getFrameInfo();
12373         int FrameIdx = MFI.CreateStackObject(8, 8, false);
12374 
12375         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12376             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12377             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12378             MFI.getObjectAlign(FrameIdx));
12379 
12380         // Store the SrcReg into the stack.
12381         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12382           .addReg(SrcReg)
12383           .addImm(0)
12384           .addFrameIndex(FrameIdx)
12385           .addMemOperand(MMOStore);
12386 
12387         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12388             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12389             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12390             MFI.getObjectAlign(FrameIdx));
12391 
12392         // Load from the stack where SrcReg is stored, and save to DestReg,
12393         // so we have done the RegClass conversion from RegClass::SrcReg to
12394         // RegClass::DestReg.
12395         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12396           .addImm(0)
12397           .addFrameIndex(FrameIdx)
12398           .addMemOperand(MMOLoad);
12399       }
12400     };
12401 
12402     Register OldFPSCRReg = MI.getOperand(0).getReg();
12403 
12404     // Save FPSCR value.
12405     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12406 
12407     // When the operand is gprc register, use two least significant bits of the
12408     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12409     //
12410     // copy OldFPSCRTmpReg, OldFPSCRReg
12411     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12412     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12413     // copy NewFPSCRReg, NewFPSCRTmpReg
12414     // mtfsf 255, NewFPSCRReg
12415     MachineOperand SrcOp = MI.getOperand(1);
12416     MachineRegisterInfo &RegInfo = F->getRegInfo();
12417     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12418 
12419     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12420 
12421     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12422     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12423 
12424     // The first operand of INSERT_SUBREG should be a register which has
12425     // subregisters, we only care about its RegClass, so we should use an
12426     // IMPLICIT_DEF register.
12427     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12428     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12429       .addReg(ImDefReg)
12430       .add(SrcOp)
12431       .addImm(1);
12432 
12433     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12434     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12435       .addReg(OldFPSCRTmpReg)
12436       .addReg(ExtSrcReg)
12437       .addImm(0)
12438       .addImm(62);
12439 
12440     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12441     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12442 
12443     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12444     // bits of FPSCR.
12445     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12446       .addImm(255)
12447       .addReg(NewFPSCRReg)
12448       .addImm(0)
12449       .addImm(0);
12450   } else {
12451     llvm_unreachable("Unexpected instr type to insert");
12452   }
12453 
12454   MI.eraseFromParent(); // The pseudo instruction is gone now.
12455   return BB;
12456 }
12457 
12458 //===----------------------------------------------------------------------===//
12459 // Target Optimization Hooks
12460 //===----------------------------------------------------------------------===//
12461 
12462 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12463   // For the estimates, convergence is quadratic, so we essentially double the
12464   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12465   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12466   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12467   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12468   if (VT.getScalarType() == MVT::f64)
12469     RefinementSteps++;
12470   return RefinementSteps;
12471 }
12472 
12473 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12474                                            int Enabled, int &RefinementSteps,
12475                                            bool &UseOneConstNR,
12476                                            bool Reciprocal) const {
12477   EVT VT = Operand.getValueType();
12478   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12479       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12480       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12481       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12482       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12483       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12484     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12485       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12486 
12487     // The Newton-Raphson computation with a single constant does not provide
12488     // enough accuracy on some CPUs.
12489     UseOneConstNR = !Subtarget.needsTwoConstNR();
12490     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12491   }
12492   return SDValue();
12493 }
12494 
12495 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12496                                             int Enabled,
12497                                             int &RefinementSteps) const {
12498   EVT VT = Operand.getValueType();
12499   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12500       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12501       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12502       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12503       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12504       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12505     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12506       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12507     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12508   }
12509   return SDValue();
12510 }
12511 
12512 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12513   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12514   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12515   // enabled for division), this functionality is redundant with the default
12516   // combiner logic (once the division -> reciprocal/multiply transformation
12517   // has taken place). As a result, this matters more for older cores than for
12518   // newer ones.
12519 
12520   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12521   // reciprocal if there are two or more FDIVs (for embedded cores with only
12522   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12523   switch (Subtarget.getCPUDirective()) {
12524   default:
12525     return 3;
12526   case PPC::DIR_440:
12527   case PPC::DIR_A2:
12528   case PPC::DIR_E500:
12529   case PPC::DIR_E500mc:
12530   case PPC::DIR_E5500:
12531     return 2;
12532   }
12533 }
12534 
12535 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12536 // collapsed, and so we need to look through chains of them.
12537 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12538                                      int64_t& Offset, SelectionDAG &DAG) {
12539   if (DAG.isBaseWithConstantOffset(Loc)) {
12540     Base = Loc.getOperand(0);
12541     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12542 
12543     // The base might itself be a base plus an offset, and if so, accumulate
12544     // that as well.
12545     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12546   }
12547 }
12548 
12549 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12550                             unsigned Bytes, int Dist,
12551                             SelectionDAG &DAG) {
12552   if (VT.getSizeInBits() / 8 != Bytes)
12553     return false;
12554 
12555   SDValue BaseLoc = Base->getBasePtr();
12556   if (Loc.getOpcode() == ISD::FrameIndex) {
12557     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12558       return false;
12559     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12560     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12561     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12562     int FS  = MFI.getObjectSize(FI);
12563     int BFS = MFI.getObjectSize(BFI);
12564     if (FS != BFS || FS != (int)Bytes) return false;
12565     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12566   }
12567 
12568   SDValue Base1 = Loc, Base2 = BaseLoc;
12569   int64_t Offset1 = 0, Offset2 = 0;
12570   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12571   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12572   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12573     return true;
12574 
12575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12576   const GlobalValue *GV1 = nullptr;
12577   const GlobalValue *GV2 = nullptr;
12578   Offset1 = 0;
12579   Offset2 = 0;
12580   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12581   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12582   if (isGA1 && isGA2 && GV1 == GV2)
12583     return Offset1 == (Offset2 + Dist*Bytes);
12584   return false;
12585 }
12586 
12587 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12588 // not enforce equality of the chain operands.
12589 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12590                             unsigned Bytes, int Dist,
12591                             SelectionDAG &DAG) {
12592   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12593     EVT VT = LS->getMemoryVT();
12594     SDValue Loc = LS->getBasePtr();
12595     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12596   }
12597 
12598   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12599     EVT VT;
12600     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12601     default: return false;
12602     case Intrinsic::ppc_qpx_qvlfd:
12603     case Intrinsic::ppc_qpx_qvlfda:
12604       VT = MVT::v4f64;
12605       break;
12606     case Intrinsic::ppc_qpx_qvlfs:
12607     case Intrinsic::ppc_qpx_qvlfsa:
12608       VT = MVT::v4f32;
12609       break;
12610     case Intrinsic::ppc_qpx_qvlfcd:
12611     case Intrinsic::ppc_qpx_qvlfcda:
12612       VT = MVT::v2f64;
12613       break;
12614     case Intrinsic::ppc_qpx_qvlfcs:
12615     case Intrinsic::ppc_qpx_qvlfcsa:
12616       VT = MVT::v2f32;
12617       break;
12618     case Intrinsic::ppc_qpx_qvlfiwa:
12619     case Intrinsic::ppc_qpx_qvlfiwz:
12620     case Intrinsic::ppc_altivec_lvx:
12621     case Intrinsic::ppc_altivec_lvxl:
12622     case Intrinsic::ppc_vsx_lxvw4x:
12623     case Intrinsic::ppc_vsx_lxvw4x_be:
12624       VT = MVT::v4i32;
12625       break;
12626     case Intrinsic::ppc_vsx_lxvd2x:
12627     case Intrinsic::ppc_vsx_lxvd2x_be:
12628       VT = MVT::v2f64;
12629       break;
12630     case Intrinsic::ppc_altivec_lvebx:
12631       VT = MVT::i8;
12632       break;
12633     case Intrinsic::ppc_altivec_lvehx:
12634       VT = MVT::i16;
12635       break;
12636     case Intrinsic::ppc_altivec_lvewx:
12637       VT = MVT::i32;
12638       break;
12639     }
12640 
12641     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12642   }
12643 
12644   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12645     EVT VT;
12646     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12647     default: return false;
12648     case Intrinsic::ppc_qpx_qvstfd:
12649     case Intrinsic::ppc_qpx_qvstfda:
12650       VT = MVT::v4f64;
12651       break;
12652     case Intrinsic::ppc_qpx_qvstfs:
12653     case Intrinsic::ppc_qpx_qvstfsa:
12654       VT = MVT::v4f32;
12655       break;
12656     case Intrinsic::ppc_qpx_qvstfcd:
12657     case Intrinsic::ppc_qpx_qvstfcda:
12658       VT = MVT::v2f64;
12659       break;
12660     case Intrinsic::ppc_qpx_qvstfcs:
12661     case Intrinsic::ppc_qpx_qvstfcsa:
12662       VT = MVT::v2f32;
12663       break;
12664     case Intrinsic::ppc_qpx_qvstfiw:
12665     case Intrinsic::ppc_qpx_qvstfiwa:
12666     case Intrinsic::ppc_altivec_stvx:
12667     case Intrinsic::ppc_altivec_stvxl:
12668     case Intrinsic::ppc_vsx_stxvw4x:
12669       VT = MVT::v4i32;
12670       break;
12671     case Intrinsic::ppc_vsx_stxvd2x:
12672       VT = MVT::v2f64;
12673       break;
12674     case Intrinsic::ppc_vsx_stxvw4x_be:
12675       VT = MVT::v4i32;
12676       break;
12677     case Intrinsic::ppc_vsx_stxvd2x_be:
12678       VT = MVT::v2f64;
12679       break;
12680     case Intrinsic::ppc_altivec_stvebx:
12681       VT = MVT::i8;
12682       break;
12683     case Intrinsic::ppc_altivec_stvehx:
12684       VT = MVT::i16;
12685       break;
12686     case Intrinsic::ppc_altivec_stvewx:
12687       VT = MVT::i32;
12688       break;
12689     }
12690 
12691     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12692   }
12693 
12694   return false;
12695 }
12696 
12697 // Return true is there is a nearyby consecutive load to the one provided
12698 // (regardless of alignment). We search up and down the chain, looking though
12699 // token factors and other loads (but nothing else). As a result, a true result
12700 // indicates that it is safe to create a new consecutive load adjacent to the
12701 // load provided.
12702 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12703   SDValue Chain = LD->getChain();
12704   EVT VT = LD->getMemoryVT();
12705 
12706   SmallSet<SDNode *, 16> LoadRoots;
12707   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12708   SmallSet<SDNode *, 16> Visited;
12709 
12710   // First, search up the chain, branching to follow all token-factor operands.
12711   // If we find a consecutive load, then we're done, otherwise, record all
12712   // nodes just above the top-level loads and token factors.
12713   while (!Queue.empty()) {
12714     SDNode *ChainNext = Queue.pop_back_val();
12715     if (!Visited.insert(ChainNext).second)
12716       continue;
12717 
12718     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12719       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12720         return true;
12721 
12722       if (!Visited.count(ChainLD->getChain().getNode()))
12723         Queue.push_back(ChainLD->getChain().getNode());
12724     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12725       for (const SDUse &O : ChainNext->ops())
12726         if (!Visited.count(O.getNode()))
12727           Queue.push_back(O.getNode());
12728     } else
12729       LoadRoots.insert(ChainNext);
12730   }
12731 
12732   // Second, search down the chain, starting from the top-level nodes recorded
12733   // in the first phase. These top-level nodes are the nodes just above all
12734   // loads and token factors. Starting with their uses, recursively look though
12735   // all loads (just the chain uses) and token factors to find a consecutive
12736   // load.
12737   Visited.clear();
12738   Queue.clear();
12739 
12740   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12741        IE = LoadRoots.end(); I != IE; ++I) {
12742     Queue.push_back(*I);
12743 
12744     while (!Queue.empty()) {
12745       SDNode *LoadRoot = Queue.pop_back_val();
12746       if (!Visited.insert(LoadRoot).second)
12747         continue;
12748 
12749       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12750         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12751           return true;
12752 
12753       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12754            UE = LoadRoot->use_end(); UI != UE; ++UI)
12755         if (((isa<MemSDNode>(*UI) &&
12756             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12757             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12758           Queue.push_back(*UI);
12759     }
12760   }
12761 
12762   return false;
12763 }
12764 
12765 /// This function is called when we have proved that a SETCC node can be replaced
12766 /// by subtraction (and other supporting instructions) so that the result of
12767 /// comparison is kept in a GPR instead of CR. This function is purely for
12768 /// codegen purposes and has some flags to guide the codegen process.
12769 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12770                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12771   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12772 
12773   // Zero extend the operands to the largest legal integer. Originally, they
12774   // must be of a strictly smaller size.
12775   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12776                          DAG.getConstant(Size, DL, MVT::i32));
12777   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12778                          DAG.getConstant(Size, DL, MVT::i32));
12779 
12780   // Swap if needed. Depends on the condition code.
12781   if (Swap)
12782     std::swap(Op0, Op1);
12783 
12784   // Subtract extended integers.
12785   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12786 
12787   // Move the sign bit to the least significant position and zero out the rest.
12788   // Now the least significant bit carries the result of original comparison.
12789   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12790                              DAG.getConstant(Size - 1, DL, MVT::i32));
12791   auto Final = Shifted;
12792 
12793   // Complement the result if needed. Based on the condition code.
12794   if (Complement)
12795     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12796                         DAG.getConstant(1, DL, MVT::i64));
12797 
12798   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12799 }
12800 
12801 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12802                                                   DAGCombinerInfo &DCI) const {
12803   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12804 
12805   SelectionDAG &DAG = DCI.DAG;
12806   SDLoc DL(N);
12807 
12808   // Size of integers being compared has a critical role in the following
12809   // analysis, so we prefer to do this when all types are legal.
12810   if (!DCI.isAfterLegalizeDAG())
12811     return SDValue();
12812 
12813   // If all users of SETCC extend its value to a legal integer type
12814   // then we replace SETCC with a subtraction
12815   for (SDNode::use_iterator UI = N->use_begin(),
12816        UE = N->use_end(); UI != UE; ++UI) {
12817     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12818       return SDValue();
12819   }
12820 
12821   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12822   auto OpSize = N->getOperand(0).getValueSizeInBits();
12823 
12824   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12825 
12826   if (OpSize < Size) {
12827     switch (CC) {
12828     default: break;
12829     case ISD::SETULT:
12830       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12831     case ISD::SETULE:
12832       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12833     case ISD::SETUGT:
12834       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12835     case ISD::SETUGE:
12836       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12837     }
12838   }
12839 
12840   return SDValue();
12841 }
12842 
12843 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12844                                                   DAGCombinerInfo &DCI) const {
12845   SelectionDAG &DAG = DCI.DAG;
12846   SDLoc dl(N);
12847 
12848   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12849   // If we're tracking CR bits, we need to be careful that we don't have:
12850   //   trunc(binary-ops(zext(x), zext(y)))
12851   // or
12852   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12853   // such that we're unnecessarily moving things into GPRs when it would be
12854   // better to keep them in CR bits.
12855 
12856   // Note that trunc here can be an actual i1 trunc, or can be the effective
12857   // truncation that comes from a setcc or select_cc.
12858   if (N->getOpcode() == ISD::TRUNCATE &&
12859       N->getValueType(0) != MVT::i1)
12860     return SDValue();
12861 
12862   if (N->getOperand(0).getValueType() != MVT::i32 &&
12863       N->getOperand(0).getValueType() != MVT::i64)
12864     return SDValue();
12865 
12866   if (N->getOpcode() == ISD::SETCC ||
12867       N->getOpcode() == ISD::SELECT_CC) {
12868     // If we're looking at a comparison, then we need to make sure that the
12869     // high bits (all except for the first) don't matter the result.
12870     ISD::CondCode CC =
12871       cast<CondCodeSDNode>(N->getOperand(
12872         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12873     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12874 
12875     if (ISD::isSignedIntSetCC(CC)) {
12876       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12877           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12878         return SDValue();
12879     } else if (ISD::isUnsignedIntSetCC(CC)) {
12880       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12881                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12882           !DAG.MaskedValueIsZero(N->getOperand(1),
12883                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12884         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12885                                              : SDValue());
12886     } else {
12887       // This is neither a signed nor an unsigned comparison, just make sure
12888       // that the high bits are equal.
12889       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12890       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12891 
12892       // We don't really care about what is known about the first bit (if
12893       // anything), so clear it in all masks prior to comparing them.
12894       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12895       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12896 
12897       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12898         return SDValue();
12899     }
12900   }
12901 
12902   // We now know that the higher-order bits are irrelevant, we just need to
12903   // make sure that all of the intermediate operations are bit operations, and
12904   // all inputs are extensions.
12905   if (N->getOperand(0).getOpcode() != ISD::AND &&
12906       N->getOperand(0).getOpcode() != ISD::OR  &&
12907       N->getOperand(0).getOpcode() != ISD::XOR &&
12908       N->getOperand(0).getOpcode() != ISD::SELECT &&
12909       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12910       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12911       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12912       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12913       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12914     return SDValue();
12915 
12916   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12917       N->getOperand(1).getOpcode() != ISD::AND &&
12918       N->getOperand(1).getOpcode() != ISD::OR  &&
12919       N->getOperand(1).getOpcode() != ISD::XOR &&
12920       N->getOperand(1).getOpcode() != ISD::SELECT &&
12921       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12922       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12923       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12924       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12925       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12926     return SDValue();
12927 
12928   SmallVector<SDValue, 4> Inputs;
12929   SmallVector<SDValue, 8> BinOps, PromOps;
12930   SmallPtrSet<SDNode *, 16> Visited;
12931 
12932   for (unsigned i = 0; i < 2; ++i) {
12933     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12934           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12935           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12936           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12937         isa<ConstantSDNode>(N->getOperand(i)))
12938       Inputs.push_back(N->getOperand(i));
12939     else
12940       BinOps.push_back(N->getOperand(i));
12941 
12942     if (N->getOpcode() == ISD::TRUNCATE)
12943       break;
12944   }
12945 
12946   // Visit all inputs, collect all binary operations (and, or, xor and
12947   // select) that are all fed by extensions.
12948   while (!BinOps.empty()) {
12949     SDValue BinOp = BinOps.back();
12950     BinOps.pop_back();
12951 
12952     if (!Visited.insert(BinOp.getNode()).second)
12953       continue;
12954 
12955     PromOps.push_back(BinOp);
12956 
12957     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12958       // The condition of the select is not promoted.
12959       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12960         continue;
12961       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12962         continue;
12963 
12964       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12965             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12966             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12967            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12968           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12969         Inputs.push_back(BinOp.getOperand(i));
12970       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12971                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12972                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12973                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12974                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12975                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12976                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12977                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12978                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12979         BinOps.push_back(BinOp.getOperand(i));
12980       } else {
12981         // We have an input that is not an extension or another binary
12982         // operation; we'll abort this transformation.
12983         return SDValue();
12984       }
12985     }
12986   }
12987 
12988   // Make sure that this is a self-contained cluster of operations (which
12989   // is not quite the same thing as saying that everything has only one
12990   // use).
12991   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12992     if (isa<ConstantSDNode>(Inputs[i]))
12993       continue;
12994 
12995     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12996                               UE = Inputs[i].getNode()->use_end();
12997          UI != UE; ++UI) {
12998       SDNode *User = *UI;
12999       if (User != N && !Visited.count(User))
13000         return SDValue();
13001 
13002       // Make sure that we're not going to promote the non-output-value
13003       // operand(s) or SELECT or SELECT_CC.
13004       // FIXME: Although we could sometimes handle this, and it does occur in
13005       // practice that one of the condition inputs to the select is also one of
13006       // the outputs, we currently can't deal with this.
13007       if (User->getOpcode() == ISD::SELECT) {
13008         if (User->getOperand(0) == Inputs[i])
13009           return SDValue();
13010       } else if (User->getOpcode() == ISD::SELECT_CC) {
13011         if (User->getOperand(0) == Inputs[i] ||
13012             User->getOperand(1) == Inputs[i])
13013           return SDValue();
13014       }
13015     }
13016   }
13017 
13018   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13019     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13020                               UE = PromOps[i].getNode()->use_end();
13021          UI != UE; ++UI) {
13022       SDNode *User = *UI;
13023       if (User != N && !Visited.count(User))
13024         return SDValue();
13025 
13026       // Make sure that we're not going to promote the non-output-value
13027       // operand(s) or SELECT or SELECT_CC.
13028       // FIXME: Although we could sometimes handle this, and it does occur in
13029       // practice that one of the condition inputs to the select is also one of
13030       // the outputs, we currently can't deal with this.
13031       if (User->getOpcode() == ISD::SELECT) {
13032         if (User->getOperand(0) == PromOps[i])
13033           return SDValue();
13034       } else if (User->getOpcode() == ISD::SELECT_CC) {
13035         if (User->getOperand(0) == PromOps[i] ||
13036             User->getOperand(1) == PromOps[i])
13037           return SDValue();
13038       }
13039     }
13040   }
13041 
13042   // Replace all inputs with the extension operand.
13043   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13044     // Constants may have users outside the cluster of to-be-promoted nodes,
13045     // and so we need to replace those as we do the promotions.
13046     if (isa<ConstantSDNode>(Inputs[i]))
13047       continue;
13048     else
13049       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13050   }
13051 
13052   std::list<HandleSDNode> PromOpHandles;
13053   for (auto &PromOp : PromOps)
13054     PromOpHandles.emplace_back(PromOp);
13055 
13056   // Replace all operations (these are all the same, but have a different
13057   // (i1) return type). DAG.getNode will validate that the types of
13058   // a binary operator match, so go through the list in reverse so that
13059   // we've likely promoted both operands first. Any intermediate truncations or
13060   // extensions disappear.
13061   while (!PromOpHandles.empty()) {
13062     SDValue PromOp = PromOpHandles.back().getValue();
13063     PromOpHandles.pop_back();
13064 
13065     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13066         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13067         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13068         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13069       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13070           PromOp.getOperand(0).getValueType() != MVT::i1) {
13071         // The operand is not yet ready (see comment below).
13072         PromOpHandles.emplace_front(PromOp);
13073         continue;
13074       }
13075 
13076       SDValue RepValue = PromOp.getOperand(0);
13077       if (isa<ConstantSDNode>(RepValue))
13078         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13079 
13080       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13081       continue;
13082     }
13083 
13084     unsigned C;
13085     switch (PromOp.getOpcode()) {
13086     default:             C = 0; break;
13087     case ISD::SELECT:    C = 1; break;
13088     case ISD::SELECT_CC: C = 2; break;
13089     }
13090 
13091     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13092          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13093         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13094          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13095       // The to-be-promoted operands of this node have not yet been
13096       // promoted (this should be rare because we're going through the
13097       // list backward, but if one of the operands has several users in
13098       // this cluster of to-be-promoted nodes, it is possible).
13099       PromOpHandles.emplace_front(PromOp);
13100       continue;
13101     }
13102 
13103     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13104                                 PromOp.getNode()->op_end());
13105 
13106     // If there are any constant inputs, make sure they're replaced now.
13107     for (unsigned i = 0; i < 2; ++i)
13108       if (isa<ConstantSDNode>(Ops[C+i]))
13109         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13110 
13111     DAG.ReplaceAllUsesOfValueWith(PromOp,
13112       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13113   }
13114 
13115   // Now we're left with the initial truncation itself.
13116   if (N->getOpcode() == ISD::TRUNCATE)
13117     return N->getOperand(0);
13118 
13119   // Otherwise, this is a comparison. The operands to be compared have just
13120   // changed type (to i1), but everything else is the same.
13121   return SDValue(N, 0);
13122 }
13123 
13124 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13125                                                   DAGCombinerInfo &DCI) const {
13126   SelectionDAG &DAG = DCI.DAG;
13127   SDLoc dl(N);
13128 
13129   // If we're tracking CR bits, we need to be careful that we don't have:
13130   //   zext(binary-ops(trunc(x), trunc(y)))
13131   // or
13132   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13133   // such that we're unnecessarily moving things into CR bits that can more
13134   // efficiently stay in GPRs. Note that if we're not certain that the high
13135   // bits are set as required by the final extension, we still may need to do
13136   // some masking to get the proper behavior.
13137 
13138   // This same functionality is important on PPC64 when dealing with
13139   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13140   // the return values of functions. Because it is so similar, it is handled
13141   // here as well.
13142 
13143   if (N->getValueType(0) != MVT::i32 &&
13144       N->getValueType(0) != MVT::i64)
13145     return SDValue();
13146 
13147   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13148         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13149     return SDValue();
13150 
13151   if (N->getOperand(0).getOpcode() != ISD::AND &&
13152       N->getOperand(0).getOpcode() != ISD::OR  &&
13153       N->getOperand(0).getOpcode() != ISD::XOR &&
13154       N->getOperand(0).getOpcode() != ISD::SELECT &&
13155       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13156     return SDValue();
13157 
13158   SmallVector<SDValue, 4> Inputs;
13159   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13160   SmallPtrSet<SDNode *, 16> Visited;
13161 
13162   // Visit all inputs, collect all binary operations (and, or, xor and
13163   // select) that are all fed by truncations.
13164   while (!BinOps.empty()) {
13165     SDValue BinOp = BinOps.back();
13166     BinOps.pop_back();
13167 
13168     if (!Visited.insert(BinOp.getNode()).second)
13169       continue;
13170 
13171     PromOps.push_back(BinOp);
13172 
13173     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13174       // The condition of the select is not promoted.
13175       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13176         continue;
13177       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13178         continue;
13179 
13180       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13181           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13182         Inputs.push_back(BinOp.getOperand(i));
13183       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13184                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13185                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13186                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13187                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13188         BinOps.push_back(BinOp.getOperand(i));
13189       } else {
13190         // We have an input that is not a truncation or another binary
13191         // operation; we'll abort this transformation.
13192         return SDValue();
13193       }
13194     }
13195   }
13196 
13197   // The operands of a select that must be truncated when the select is
13198   // promoted because the operand is actually part of the to-be-promoted set.
13199   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13200 
13201   // Make sure that this is a self-contained cluster of operations (which
13202   // is not quite the same thing as saying that everything has only one
13203   // use).
13204   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13205     if (isa<ConstantSDNode>(Inputs[i]))
13206       continue;
13207 
13208     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13209                               UE = Inputs[i].getNode()->use_end();
13210          UI != UE; ++UI) {
13211       SDNode *User = *UI;
13212       if (User != N && !Visited.count(User))
13213         return SDValue();
13214 
13215       // If we're going to promote the non-output-value operand(s) or SELECT or
13216       // SELECT_CC, record them for truncation.
13217       if (User->getOpcode() == ISD::SELECT) {
13218         if (User->getOperand(0) == Inputs[i])
13219           SelectTruncOp[0].insert(std::make_pair(User,
13220                                     User->getOperand(0).getValueType()));
13221       } else if (User->getOpcode() == ISD::SELECT_CC) {
13222         if (User->getOperand(0) == Inputs[i])
13223           SelectTruncOp[0].insert(std::make_pair(User,
13224                                     User->getOperand(0).getValueType()));
13225         if (User->getOperand(1) == Inputs[i])
13226           SelectTruncOp[1].insert(std::make_pair(User,
13227                                     User->getOperand(1).getValueType()));
13228       }
13229     }
13230   }
13231 
13232   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13233     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13234                               UE = PromOps[i].getNode()->use_end();
13235          UI != UE; ++UI) {
13236       SDNode *User = *UI;
13237       if (User != N && !Visited.count(User))
13238         return SDValue();
13239 
13240       // If we're going to promote the non-output-value operand(s) or SELECT or
13241       // SELECT_CC, record them for truncation.
13242       if (User->getOpcode() == ISD::SELECT) {
13243         if (User->getOperand(0) == PromOps[i])
13244           SelectTruncOp[0].insert(std::make_pair(User,
13245                                     User->getOperand(0).getValueType()));
13246       } else if (User->getOpcode() == ISD::SELECT_CC) {
13247         if (User->getOperand(0) == PromOps[i])
13248           SelectTruncOp[0].insert(std::make_pair(User,
13249                                     User->getOperand(0).getValueType()));
13250         if (User->getOperand(1) == PromOps[i])
13251           SelectTruncOp[1].insert(std::make_pair(User,
13252                                     User->getOperand(1).getValueType()));
13253       }
13254     }
13255   }
13256 
13257   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13258   bool ReallyNeedsExt = false;
13259   if (N->getOpcode() != ISD::ANY_EXTEND) {
13260     // If all of the inputs are not already sign/zero extended, then
13261     // we'll still need to do that at the end.
13262     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13263       if (isa<ConstantSDNode>(Inputs[i]))
13264         continue;
13265 
13266       unsigned OpBits =
13267         Inputs[i].getOperand(0).getValueSizeInBits();
13268       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13269 
13270       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13271            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13272                                   APInt::getHighBitsSet(OpBits,
13273                                                         OpBits-PromBits))) ||
13274           (N->getOpcode() == ISD::SIGN_EXTEND &&
13275            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13276              (OpBits-(PromBits-1)))) {
13277         ReallyNeedsExt = true;
13278         break;
13279       }
13280     }
13281   }
13282 
13283   // Replace all inputs, either with the truncation operand, or a
13284   // truncation or extension to the final output type.
13285   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13286     // Constant inputs need to be replaced with the to-be-promoted nodes that
13287     // use them because they might have users outside of the cluster of
13288     // promoted nodes.
13289     if (isa<ConstantSDNode>(Inputs[i]))
13290       continue;
13291 
13292     SDValue InSrc = Inputs[i].getOperand(0);
13293     if (Inputs[i].getValueType() == N->getValueType(0))
13294       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13295     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13296       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13297         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13298     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13299       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13300         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13301     else
13302       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13303         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13304   }
13305 
13306   std::list<HandleSDNode> PromOpHandles;
13307   for (auto &PromOp : PromOps)
13308     PromOpHandles.emplace_back(PromOp);
13309 
13310   // Replace all operations (these are all the same, but have a different
13311   // (promoted) return type). DAG.getNode will validate that the types of
13312   // a binary operator match, so go through the list in reverse so that
13313   // we've likely promoted both operands first.
13314   while (!PromOpHandles.empty()) {
13315     SDValue PromOp = PromOpHandles.back().getValue();
13316     PromOpHandles.pop_back();
13317 
13318     unsigned C;
13319     switch (PromOp.getOpcode()) {
13320     default:             C = 0; break;
13321     case ISD::SELECT:    C = 1; break;
13322     case ISD::SELECT_CC: C = 2; break;
13323     }
13324 
13325     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13326          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13327         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13328          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13329       // The to-be-promoted operands of this node have not yet been
13330       // promoted (this should be rare because we're going through the
13331       // list backward, but if one of the operands has several users in
13332       // this cluster of to-be-promoted nodes, it is possible).
13333       PromOpHandles.emplace_front(PromOp);
13334       continue;
13335     }
13336 
13337     // For SELECT and SELECT_CC nodes, we do a similar check for any
13338     // to-be-promoted comparison inputs.
13339     if (PromOp.getOpcode() == ISD::SELECT ||
13340         PromOp.getOpcode() == ISD::SELECT_CC) {
13341       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13342            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13343           (SelectTruncOp[1].count(PromOp.getNode()) &&
13344            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13345         PromOpHandles.emplace_front(PromOp);
13346         continue;
13347       }
13348     }
13349 
13350     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13351                                 PromOp.getNode()->op_end());
13352 
13353     // If this node has constant inputs, then they'll need to be promoted here.
13354     for (unsigned i = 0; i < 2; ++i) {
13355       if (!isa<ConstantSDNode>(Ops[C+i]))
13356         continue;
13357       if (Ops[C+i].getValueType() == N->getValueType(0))
13358         continue;
13359 
13360       if (N->getOpcode() == ISD::SIGN_EXTEND)
13361         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13362       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13363         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13364       else
13365         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13366     }
13367 
13368     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13369     // truncate them again to the original value type.
13370     if (PromOp.getOpcode() == ISD::SELECT ||
13371         PromOp.getOpcode() == ISD::SELECT_CC) {
13372       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13373       if (SI0 != SelectTruncOp[0].end())
13374         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13375       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13376       if (SI1 != SelectTruncOp[1].end())
13377         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13378     }
13379 
13380     DAG.ReplaceAllUsesOfValueWith(PromOp,
13381       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13382   }
13383 
13384   // Now we're left with the initial extension itself.
13385   if (!ReallyNeedsExt)
13386     return N->getOperand(0);
13387 
13388   // To zero extend, just mask off everything except for the first bit (in the
13389   // i1 case).
13390   if (N->getOpcode() == ISD::ZERO_EXTEND)
13391     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13392                        DAG.getConstant(APInt::getLowBitsSet(
13393                                          N->getValueSizeInBits(0), PromBits),
13394                                        dl, N->getValueType(0)));
13395 
13396   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13397          "Invalid extension type");
13398   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13399   SDValue ShiftCst =
13400       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13401   return DAG.getNode(
13402       ISD::SRA, dl, N->getValueType(0),
13403       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13404       ShiftCst);
13405 }
13406 
13407 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13408                                         DAGCombinerInfo &DCI) const {
13409   assert(N->getOpcode() == ISD::SETCC &&
13410          "Should be called with a SETCC node");
13411 
13412   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13413   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13414     SDValue LHS = N->getOperand(0);
13415     SDValue RHS = N->getOperand(1);
13416 
13417     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13418     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13419         LHS.hasOneUse())
13420       std::swap(LHS, RHS);
13421 
13422     // x == 0-y --> x+y == 0
13423     // x != 0-y --> x+y != 0
13424     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13425         RHS.hasOneUse()) {
13426       SDLoc DL(N);
13427       SelectionDAG &DAG = DCI.DAG;
13428       EVT VT = N->getValueType(0);
13429       EVT OpVT = LHS.getValueType();
13430       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13431       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13432     }
13433   }
13434 
13435   return DAGCombineTruncBoolExt(N, DCI);
13436 }
13437 
13438 // Is this an extending load from an f32 to an f64?
13439 static bool isFPExtLoad(SDValue Op) {
13440   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13441     return LD->getExtensionType() == ISD::EXTLOAD &&
13442       Op.getValueType() == MVT::f64;
13443   return false;
13444 }
13445 
13446 /// Reduces the number of fp-to-int conversion when building a vector.
13447 ///
13448 /// If this vector is built out of floating to integer conversions,
13449 /// transform it to a vector built out of floating point values followed by a
13450 /// single floating to integer conversion of the vector.
13451 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13452 /// becomes (fptosi (build_vector ($A, $B, ...)))
13453 SDValue PPCTargetLowering::
13454 combineElementTruncationToVectorTruncation(SDNode *N,
13455                                            DAGCombinerInfo &DCI) const {
13456   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13457          "Should be called with a BUILD_VECTOR node");
13458 
13459   SelectionDAG &DAG = DCI.DAG;
13460   SDLoc dl(N);
13461 
13462   SDValue FirstInput = N->getOperand(0);
13463   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13464          "The input operand must be an fp-to-int conversion.");
13465 
13466   // This combine happens after legalization so the fp_to_[su]i nodes are
13467   // already converted to PPCSISD nodes.
13468   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13469   if (FirstConversion == PPCISD::FCTIDZ ||
13470       FirstConversion == PPCISD::FCTIDUZ ||
13471       FirstConversion == PPCISD::FCTIWZ ||
13472       FirstConversion == PPCISD::FCTIWUZ) {
13473     bool IsSplat = true;
13474     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13475       FirstConversion == PPCISD::FCTIWUZ;
13476     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13477     SmallVector<SDValue, 4> Ops;
13478     EVT TargetVT = N->getValueType(0);
13479     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13480       SDValue NextOp = N->getOperand(i);
13481       if (NextOp.getOpcode() != PPCISD::MFVSR)
13482         return SDValue();
13483       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13484       if (NextConversion != FirstConversion)
13485         return SDValue();
13486       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13487       // This is not valid if the input was originally double precision. It is
13488       // also not profitable to do unless this is an extending load in which
13489       // case doing this combine will allow us to combine consecutive loads.
13490       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13491         return SDValue();
13492       if (N->getOperand(i) != FirstInput)
13493         IsSplat = false;
13494     }
13495 
13496     // If this is a splat, we leave it as-is since there will be only a single
13497     // fp-to-int conversion followed by a splat of the integer. This is better
13498     // for 32-bit and smaller ints and neutral for 64-bit ints.
13499     if (IsSplat)
13500       return SDValue();
13501 
13502     // Now that we know we have the right type of node, get its operands
13503     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13504       SDValue In = N->getOperand(i).getOperand(0);
13505       if (Is32Bit) {
13506         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13507         // here, we know that all inputs are extending loads so this is safe).
13508         if (In.isUndef())
13509           Ops.push_back(DAG.getUNDEF(SrcVT));
13510         else {
13511           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13512                                       MVT::f32, In.getOperand(0),
13513                                       DAG.getIntPtrConstant(1, dl));
13514           Ops.push_back(Trunc);
13515         }
13516       } else
13517         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13518     }
13519 
13520     unsigned Opcode;
13521     if (FirstConversion == PPCISD::FCTIDZ ||
13522         FirstConversion == PPCISD::FCTIWZ)
13523       Opcode = ISD::FP_TO_SINT;
13524     else
13525       Opcode = ISD::FP_TO_UINT;
13526 
13527     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13528     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13529     return DAG.getNode(Opcode, dl, TargetVT, BV);
13530   }
13531   return SDValue();
13532 }
13533 
13534 /// Reduce the number of loads when building a vector.
13535 ///
13536 /// Building a vector out of multiple loads can be converted to a load
13537 /// of the vector type if the loads are consecutive. If the loads are
13538 /// consecutive but in descending order, a shuffle is added at the end
13539 /// to reorder the vector.
13540 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13541   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13542          "Should be called with a BUILD_VECTOR node");
13543 
13544   SDLoc dl(N);
13545 
13546   // Return early for non byte-sized type, as they can't be consecutive.
13547   if (!N->getValueType(0).getVectorElementType().isByteSized())
13548     return SDValue();
13549 
13550   bool InputsAreConsecutiveLoads = true;
13551   bool InputsAreReverseConsecutive = true;
13552   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13553   SDValue FirstInput = N->getOperand(0);
13554   bool IsRoundOfExtLoad = false;
13555 
13556   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13557       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13558     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13559     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13560   }
13561   // Not a build vector of (possibly fp_rounded) loads.
13562   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13563       N->getNumOperands() == 1)
13564     return SDValue();
13565 
13566   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13567     // If any inputs are fp_round(extload), they all must be.
13568     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13569       return SDValue();
13570 
13571     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13572       N->getOperand(i);
13573     if (NextInput.getOpcode() != ISD::LOAD)
13574       return SDValue();
13575 
13576     SDValue PreviousInput =
13577       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13578     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13579     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13580 
13581     // If any inputs are fp_round(extload), they all must be.
13582     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13583       return SDValue();
13584 
13585     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13586       InputsAreConsecutiveLoads = false;
13587     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13588       InputsAreReverseConsecutive = false;
13589 
13590     // Exit early if the loads are neither consecutive nor reverse consecutive.
13591     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13592       return SDValue();
13593   }
13594 
13595   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13596          "The loads cannot be both consecutive and reverse consecutive.");
13597 
13598   SDValue FirstLoadOp =
13599     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13600   SDValue LastLoadOp =
13601     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13602                        N->getOperand(N->getNumOperands()-1);
13603 
13604   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13605   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13606   if (InputsAreConsecutiveLoads) {
13607     assert(LD1 && "Input needs to be a LoadSDNode.");
13608     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13609                        LD1->getBasePtr(), LD1->getPointerInfo(),
13610                        LD1->getAlignment());
13611   }
13612   if (InputsAreReverseConsecutive) {
13613     assert(LDL && "Input needs to be a LoadSDNode.");
13614     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13615                                LDL->getBasePtr(), LDL->getPointerInfo(),
13616                                LDL->getAlignment());
13617     SmallVector<int, 16> Ops;
13618     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13619       Ops.push_back(i);
13620 
13621     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13622                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13623   }
13624   return SDValue();
13625 }
13626 
13627 // This function adds the required vector_shuffle needed to get
13628 // the elements of the vector extract in the correct position
13629 // as specified by the CorrectElems encoding.
13630 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13631                                       SDValue Input, uint64_t Elems,
13632                                       uint64_t CorrectElems) {
13633   SDLoc dl(N);
13634 
13635   unsigned NumElems = Input.getValueType().getVectorNumElements();
13636   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13637 
13638   // Knowing the element indices being extracted from the original
13639   // vector and the order in which they're being inserted, just put
13640   // them at element indices required for the instruction.
13641   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13642     if (DAG.getDataLayout().isLittleEndian())
13643       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13644     else
13645       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13646     CorrectElems = CorrectElems >> 8;
13647     Elems = Elems >> 8;
13648   }
13649 
13650   SDValue Shuffle =
13651       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13652                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13653 
13654   EVT VT = N->getValueType(0);
13655   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13656 
13657   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13658                                Input.getValueType().getVectorElementType(),
13659                                VT.getVectorNumElements());
13660   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13661                      DAG.getValueType(ExtVT));
13662 }
13663 
13664 // Look for build vector patterns where input operands come from sign
13665 // extended vector_extract elements of specific indices. If the correct indices
13666 // aren't used, add a vector shuffle to fix up the indices and create
13667 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13668 // during instruction selection.
13669 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13670   // This array encodes the indices that the vector sign extend instructions
13671   // extract from when extending from one type to another for both BE and LE.
13672   // The right nibble of each byte corresponds to the LE incides.
13673   // and the left nibble of each byte corresponds to the BE incides.
13674   // For example: 0x3074B8FC  byte->word
13675   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13676   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13677   // For example: 0x000070F8  byte->double word
13678   // For LE: the allowed indices are: 0x0,0x8
13679   // For BE: the allowed indices are: 0x7,0xF
13680   uint64_t TargetElems[] = {
13681       0x3074B8FC, // b->w
13682       0x000070F8, // b->d
13683       0x10325476, // h->w
13684       0x00003074, // h->d
13685       0x00001032, // w->d
13686   };
13687 
13688   uint64_t Elems = 0;
13689   int Index;
13690   SDValue Input;
13691 
13692   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13693     if (!Op)
13694       return false;
13695     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13696         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13697       return false;
13698 
13699     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13700     // of the right width.
13701     SDValue Extract = Op.getOperand(0);
13702     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13703       Extract = Extract.getOperand(0);
13704     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13705       return false;
13706 
13707     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13708     if (!ExtOp)
13709       return false;
13710 
13711     Index = ExtOp->getZExtValue();
13712     if (Input && Input != Extract.getOperand(0))
13713       return false;
13714 
13715     if (!Input)
13716       Input = Extract.getOperand(0);
13717 
13718     Elems = Elems << 8;
13719     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13720     Elems |= Index;
13721 
13722     return true;
13723   };
13724 
13725   // If the build vector operands aren't sign extended vector extracts,
13726   // of the same input vector, then return.
13727   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13728     if (!isSExtOfVecExtract(N->getOperand(i))) {
13729       return SDValue();
13730     }
13731   }
13732 
13733   // If the vector extract indicies are not correct, add the appropriate
13734   // vector_shuffle.
13735   int TgtElemArrayIdx;
13736   int InputSize = Input.getValueType().getScalarSizeInBits();
13737   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13738   if (InputSize + OutputSize == 40)
13739     TgtElemArrayIdx = 0;
13740   else if (InputSize + OutputSize == 72)
13741     TgtElemArrayIdx = 1;
13742   else if (InputSize + OutputSize == 48)
13743     TgtElemArrayIdx = 2;
13744   else if (InputSize + OutputSize == 80)
13745     TgtElemArrayIdx = 3;
13746   else if (InputSize + OutputSize == 96)
13747     TgtElemArrayIdx = 4;
13748   else
13749     return SDValue();
13750 
13751   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13752   CorrectElems = DAG.getDataLayout().isLittleEndian()
13753                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13754                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13755   if (Elems != CorrectElems) {
13756     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13757   }
13758 
13759   // Regular lowering will catch cases where a shuffle is not needed.
13760   return SDValue();
13761 }
13762 
13763 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13764                                                  DAGCombinerInfo &DCI) const {
13765   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13766          "Should be called with a BUILD_VECTOR node");
13767 
13768   SelectionDAG &DAG = DCI.DAG;
13769   SDLoc dl(N);
13770 
13771   if (!Subtarget.hasVSX())
13772     return SDValue();
13773 
13774   // The target independent DAG combiner will leave a build_vector of
13775   // float-to-int conversions intact. We can generate MUCH better code for
13776   // a float-to-int conversion of a vector of floats.
13777   SDValue FirstInput = N->getOperand(0);
13778   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13779     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13780     if (Reduced)
13781       return Reduced;
13782   }
13783 
13784   // If we're building a vector out of consecutive loads, just load that
13785   // vector type.
13786   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13787   if (Reduced)
13788     return Reduced;
13789 
13790   // If we're building a vector out of extended elements from another vector
13791   // we have P9 vector integer extend instructions. The code assumes legal
13792   // input types (i.e. it can't handle things like v4i16) so do not run before
13793   // legalization.
13794   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13795     Reduced = combineBVOfVecSExt(N, DAG);
13796     if (Reduced)
13797       return Reduced;
13798   }
13799 
13800 
13801   if (N->getValueType(0) != MVT::v2f64)
13802     return SDValue();
13803 
13804   // Looking for:
13805   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13806   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13807       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13808     return SDValue();
13809   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13810       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13811     return SDValue();
13812   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13813     return SDValue();
13814 
13815   SDValue Ext1 = FirstInput.getOperand(0);
13816   SDValue Ext2 = N->getOperand(1).getOperand(0);
13817   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13818      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13819     return SDValue();
13820 
13821   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13822   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13823   if (!Ext1Op || !Ext2Op)
13824     return SDValue();
13825   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13826       Ext1.getOperand(0) != Ext2.getOperand(0))
13827     return SDValue();
13828 
13829   int FirstElem = Ext1Op->getZExtValue();
13830   int SecondElem = Ext2Op->getZExtValue();
13831   int SubvecIdx;
13832   if (FirstElem == 0 && SecondElem == 1)
13833     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13834   else if (FirstElem == 2 && SecondElem == 3)
13835     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13836   else
13837     return SDValue();
13838 
13839   SDValue SrcVec = Ext1.getOperand(0);
13840   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13841     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13842   return DAG.getNode(NodeType, dl, MVT::v2f64,
13843                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13844 }
13845 
13846 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13847                                               DAGCombinerInfo &DCI) const {
13848   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13849           N->getOpcode() == ISD::UINT_TO_FP) &&
13850          "Need an int -> FP conversion node here");
13851 
13852   if (useSoftFloat() || !Subtarget.has64BitSupport())
13853     return SDValue();
13854 
13855   SelectionDAG &DAG = DCI.DAG;
13856   SDLoc dl(N);
13857   SDValue Op(N, 0);
13858 
13859   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13860   // from the hardware.
13861   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13862     return SDValue();
13863   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13864       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13865     return SDValue();
13866 
13867   SDValue FirstOperand(Op.getOperand(0));
13868   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13869     (FirstOperand.getValueType() == MVT::i8 ||
13870      FirstOperand.getValueType() == MVT::i16);
13871   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13872     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13873     bool DstDouble = Op.getValueType() == MVT::f64;
13874     unsigned ConvOp = Signed ?
13875       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13876       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13877     SDValue WidthConst =
13878       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13879                             dl, false);
13880     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13881     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13882     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13883                                          DAG.getVTList(MVT::f64, MVT::Other),
13884                                          Ops, MVT::i8, LDN->getMemOperand());
13885 
13886     // For signed conversion, we need to sign-extend the value in the VSR
13887     if (Signed) {
13888       SDValue ExtOps[] = { Ld, WidthConst };
13889       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13890       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13891     } else
13892       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13893   }
13894 
13895 
13896   // For i32 intermediate values, unfortunately, the conversion functions
13897   // leave the upper 32 bits of the value are undefined. Within the set of
13898   // scalar instructions, we have no method for zero- or sign-extending the
13899   // value. Thus, we cannot handle i32 intermediate values here.
13900   if (Op.getOperand(0).getValueType() == MVT::i32)
13901     return SDValue();
13902 
13903   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13904          "UINT_TO_FP is supported only with FPCVT");
13905 
13906   // If we have FCFIDS, then use it when converting to single-precision.
13907   // Otherwise, convert to double-precision and then round.
13908   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13909                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13910                                                             : PPCISD::FCFIDS)
13911                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13912                                                             : PPCISD::FCFID);
13913   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13914                   ? MVT::f32
13915                   : MVT::f64;
13916 
13917   // If we're converting from a float, to an int, and back to a float again,
13918   // then we don't need the store/load pair at all.
13919   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13920        Subtarget.hasFPCVT()) ||
13921       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13922     SDValue Src = Op.getOperand(0).getOperand(0);
13923     if (Src.getValueType() == MVT::f32) {
13924       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13925       DCI.AddToWorklist(Src.getNode());
13926     } else if (Src.getValueType() != MVT::f64) {
13927       // Make sure that we don't pick up a ppc_fp128 source value.
13928       return SDValue();
13929     }
13930 
13931     unsigned FCTOp =
13932       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13933                                                         PPCISD::FCTIDUZ;
13934 
13935     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13936     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13937 
13938     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13939       FP = DAG.getNode(ISD::FP_ROUND, dl,
13940                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13941       DCI.AddToWorklist(FP.getNode());
13942     }
13943 
13944     return FP;
13945   }
13946 
13947   return SDValue();
13948 }
13949 
13950 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13951 // builtins) into loads with swaps.
13952 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13953                                               DAGCombinerInfo &DCI) const {
13954   SelectionDAG &DAG = DCI.DAG;
13955   SDLoc dl(N);
13956   SDValue Chain;
13957   SDValue Base;
13958   MachineMemOperand *MMO;
13959 
13960   switch (N->getOpcode()) {
13961   default:
13962     llvm_unreachable("Unexpected opcode for little endian VSX load");
13963   case ISD::LOAD: {
13964     LoadSDNode *LD = cast<LoadSDNode>(N);
13965     Chain = LD->getChain();
13966     Base = LD->getBasePtr();
13967     MMO = LD->getMemOperand();
13968     // If the MMO suggests this isn't a load of a full vector, leave
13969     // things alone.  For a built-in, we have to make the change for
13970     // correctness, so if there is a size problem that will be a bug.
13971     if (MMO->getSize() < 16)
13972       return SDValue();
13973     break;
13974   }
13975   case ISD::INTRINSIC_W_CHAIN: {
13976     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13977     Chain = Intrin->getChain();
13978     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13979     // us what we want. Get operand 2 instead.
13980     Base = Intrin->getOperand(2);
13981     MMO = Intrin->getMemOperand();
13982     break;
13983   }
13984   }
13985 
13986   MVT VecTy = N->getValueType(0).getSimpleVT();
13987 
13988   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13989   // aligned and the type is a vector with elements up to 4 bytes
13990   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13991       VecTy.getScalarSizeInBits() <= 32) {
13992     return SDValue();
13993   }
13994 
13995   SDValue LoadOps[] = { Chain, Base };
13996   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13997                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13998                                          LoadOps, MVT::v2f64, MMO);
13999 
14000   DCI.AddToWorklist(Load.getNode());
14001   Chain = Load.getValue(1);
14002   SDValue Swap = DAG.getNode(
14003       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14004   DCI.AddToWorklist(Swap.getNode());
14005 
14006   // Add a bitcast if the resulting load type doesn't match v2f64.
14007   if (VecTy != MVT::v2f64) {
14008     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14009     DCI.AddToWorklist(N.getNode());
14010     // Package {bitcast value, swap's chain} to match Load's shape.
14011     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14012                        N, Swap.getValue(1));
14013   }
14014 
14015   return Swap;
14016 }
14017 
14018 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14019 // builtins) into stores with swaps.
14020 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14021                                                DAGCombinerInfo &DCI) const {
14022   SelectionDAG &DAG = DCI.DAG;
14023   SDLoc dl(N);
14024   SDValue Chain;
14025   SDValue Base;
14026   unsigned SrcOpnd;
14027   MachineMemOperand *MMO;
14028 
14029   switch (N->getOpcode()) {
14030   default:
14031     llvm_unreachable("Unexpected opcode for little endian VSX store");
14032   case ISD::STORE: {
14033     StoreSDNode *ST = cast<StoreSDNode>(N);
14034     Chain = ST->getChain();
14035     Base = ST->getBasePtr();
14036     MMO = ST->getMemOperand();
14037     SrcOpnd = 1;
14038     // If the MMO suggests this isn't a store of a full vector, leave
14039     // things alone.  For a built-in, we have to make the change for
14040     // correctness, so if there is a size problem that will be a bug.
14041     if (MMO->getSize() < 16)
14042       return SDValue();
14043     break;
14044   }
14045   case ISD::INTRINSIC_VOID: {
14046     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14047     Chain = Intrin->getChain();
14048     // Intrin->getBasePtr() oddly does not get what we want.
14049     Base = Intrin->getOperand(3);
14050     MMO = Intrin->getMemOperand();
14051     SrcOpnd = 2;
14052     break;
14053   }
14054   }
14055 
14056   SDValue Src = N->getOperand(SrcOpnd);
14057   MVT VecTy = Src.getValueType().getSimpleVT();
14058 
14059   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14060   // aligned and the type is a vector with elements up to 4 bytes
14061   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14062       VecTy.getScalarSizeInBits() <= 32) {
14063     return SDValue();
14064   }
14065 
14066   // All stores are done as v2f64 and possible bit cast.
14067   if (VecTy != MVT::v2f64) {
14068     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14069     DCI.AddToWorklist(Src.getNode());
14070   }
14071 
14072   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14073                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14074   DCI.AddToWorklist(Swap.getNode());
14075   Chain = Swap.getValue(1);
14076   SDValue StoreOps[] = { Chain, Swap, Base };
14077   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14078                                           DAG.getVTList(MVT::Other),
14079                                           StoreOps, VecTy, MMO);
14080   DCI.AddToWorklist(Store.getNode());
14081   return Store;
14082 }
14083 
14084 // Handle DAG combine for STORE (FP_TO_INT F).
14085 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14086                                                DAGCombinerInfo &DCI) const {
14087 
14088   SelectionDAG &DAG = DCI.DAG;
14089   SDLoc dl(N);
14090   unsigned Opcode = N->getOperand(1).getOpcode();
14091 
14092   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14093          && "Not a FP_TO_INT Instruction!");
14094 
14095   SDValue Val = N->getOperand(1).getOperand(0);
14096   EVT Op1VT = N->getOperand(1).getValueType();
14097   EVT ResVT = Val.getValueType();
14098 
14099   // Floating point types smaller than 32 bits are not legal on Power.
14100   if (ResVT.getScalarSizeInBits() < 32)
14101     return SDValue();
14102 
14103   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14104   bool ValidTypeForStoreFltAsInt =
14105         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14106          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14107 
14108   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14109       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14110     return SDValue();
14111 
14112   // Extend f32 values to f64
14113   if (ResVT.getScalarSizeInBits() == 32) {
14114     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14115     DCI.AddToWorklist(Val.getNode());
14116   }
14117 
14118   // Set signed or unsigned conversion opcode.
14119   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14120                           PPCISD::FP_TO_SINT_IN_VSR :
14121                           PPCISD::FP_TO_UINT_IN_VSR;
14122 
14123   Val = DAG.getNode(ConvOpcode,
14124                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14125   DCI.AddToWorklist(Val.getNode());
14126 
14127   // Set number of bytes being converted.
14128   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14129   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14130                     DAG.getIntPtrConstant(ByteSize, dl, false),
14131                     DAG.getValueType(Op1VT) };
14132 
14133   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14134           DAG.getVTList(MVT::Other), Ops,
14135           cast<StoreSDNode>(N)->getMemoryVT(),
14136           cast<StoreSDNode>(N)->getMemOperand());
14137 
14138   DCI.AddToWorklist(Val.getNode());
14139   return Val;
14140 }
14141 
14142 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14143   // Check that the source of the element keeps flipping
14144   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14145   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14146   for (int i = 1, e = Mask.size(); i < e; i++) {
14147     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14148       return false;
14149     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14150       return false;
14151     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14152   }
14153   return true;
14154 }
14155 
14156 static bool isSplatBV(SDValue Op) {
14157   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14158     return false;
14159   SDValue FirstOp;
14160 
14161   // Find first non-undef input.
14162   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14163     FirstOp = Op.getOperand(i);
14164     if (!FirstOp.isUndef())
14165       break;
14166   }
14167 
14168   // All inputs are undef or the same as the first non-undef input.
14169   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14170     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14171       return false;
14172   return true;
14173 }
14174 
14175 static SDValue isScalarToVec(SDValue Op) {
14176   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14177     return Op;
14178   if (Op.getOpcode() != ISD::BITCAST)
14179     return SDValue();
14180   Op = Op.getOperand(0);
14181   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14182     return Op;
14183   return SDValue();
14184 }
14185 
14186 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14187                                             int LHSMaxIdx, int RHSMinIdx,
14188                                             int RHSMaxIdx, int HalfVec) {
14189   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14190     int Idx = ShuffV[i];
14191     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14192       ShuffV[i] += HalfVec;
14193   }
14194   return;
14195 }
14196 
14197 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14198 // the original is:
14199 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14200 // In such a case, just change the shuffle mask to extract the element
14201 // from the permuted index.
14202 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14203   SDLoc dl(OrigSToV);
14204   EVT VT = OrigSToV.getValueType();
14205   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14206          "Expecting a SCALAR_TO_VECTOR here");
14207   SDValue Input = OrigSToV.getOperand(0);
14208 
14209   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14210     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14211     SDValue OrigVector = Input.getOperand(0);
14212 
14213     // Can't handle non-const element indices or different vector types
14214     // for the input to the extract and the output of the scalar_to_vector.
14215     if (Idx && VT == OrigVector.getValueType()) {
14216       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14217       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14218       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14219     }
14220   }
14221   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14222                      OrigSToV.getOperand(0));
14223 }
14224 
14225 // On little endian subtargets, combine shuffles such as:
14226 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14227 // into:
14228 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14229 // because the latter can be matched to a single instruction merge.
14230 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14231 // to put the value into element zero. Adjust the shuffle mask so that the
14232 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14233 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14234                                                 SelectionDAG &DAG) const {
14235   SDValue LHS = SVN->getOperand(0);
14236   SDValue RHS = SVN->getOperand(1);
14237   auto Mask = SVN->getMask();
14238   int NumElts = LHS.getValueType().getVectorNumElements();
14239   SDValue Res(SVN, 0);
14240   SDLoc dl(SVN);
14241 
14242   // None of these combines are useful on big endian systems since the ISA
14243   // already has a big endian bias.
14244   if (!Subtarget.isLittleEndian())
14245     return Res;
14246 
14247   // If this is not a shuffle of a shuffle and the first element comes from
14248   // the second vector, canonicalize to the commuted form. This will make it
14249   // more likely to match one of the single instruction patterns.
14250   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14251       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14252     std::swap(LHS, RHS);
14253     Res = DAG.getCommutedVectorShuffle(*SVN);
14254     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14255   }
14256 
14257   // Adjust the shuffle mask if either input vector comes from a
14258   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14259   // form (to prevent the need for a swap).
14260   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14261   SDValue SToVLHS = isScalarToVec(LHS);
14262   SDValue SToVRHS = isScalarToVec(RHS);
14263   if (SToVLHS || SToVRHS) {
14264     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14265                             : SToVRHS.getValueType().getVectorNumElements();
14266     int NumEltsOut = ShuffV.size();
14267 
14268     // Initially assume that neither input is permuted. These will be adjusted
14269     // accordingly if either input is.
14270     int LHSMaxIdx = -1;
14271     int RHSMinIdx = -1;
14272     int RHSMaxIdx = -1;
14273     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14274 
14275     // Get the permuted scalar to vector nodes for the source(s) that come from
14276     // ISD::SCALAR_TO_VECTOR.
14277     if (SToVLHS) {
14278       // Set up the values for the shuffle vector fixup.
14279       LHSMaxIdx = NumEltsOut / NumEltsIn;
14280       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14281       if (SToVLHS.getValueType() != LHS.getValueType())
14282         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14283       LHS = SToVLHS;
14284     }
14285     if (SToVRHS) {
14286       RHSMinIdx = NumEltsOut;
14287       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14288       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14289       if (SToVRHS.getValueType() != RHS.getValueType())
14290         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14291       RHS = SToVRHS;
14292     }
14293 
14294     // Fix up the shuffle mask to reflect where the desired element actually is.
14295     // The minimum and maximum indices that correspond to element zero for both
14296     // the LHS and RHS are computed and will control which shuffle mask entries
14297     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14298     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14299     // HalfVec to refer to the corresponding element in the permuted vector.
14300     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14301                                     HalfVec);
14302     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14303 
14304     // We may have simplified away the shuffle. We won't be able to do anything
14305     // further with it here.
14306     if (!isa<ShuffleVectorSDNode>(Res))
14307       return Res;
14308     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14309   }
14310 
14311   // The common case after we commuted the shuffle is that the RHS is a splat
14312   // and we have elements coming in from the splat at indices that are not
14313   // conducive to using a merge.
14314   // Example:
14315   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14316   if (!isSplatBV(RHS))
14317     return Res;
14318 
14319   // We are looking for a mask such that all even elements are from
14320   // one vector and all odd elements from the other.
14321   if (!isAlternatingShuffMask(Mask, NumElts))
14322     return Res;
14323 
14324   // Adjust the mask so we are pulling in the same index from the splat
14325   // as the index from the interesting vector in consecutive elements.
14326   // Example:
14327   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14328   for (int i = 1, e = Mask.size(); i < e; i += 2)
14329     ShuffV[i] = (ShuffV[i - 1] + NumElts);
14330 
14331   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14332   return Res;
14333 }
14334 
14335 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14336                                                 LSBaseSDNode *LSBase,
14337                                                 DAGCombinerInfo &DCI) const {
14338   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14339         "Not a reverse memop pattern!");
14340 
14341   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14342     auto Mask = SVN->getMask();
14343     int i = 0;
14344     auto I = Mask.rbegin();
14345     auto E = Mask.rend();
14346 
14347     for (; I != E; ++I) {
14348       if (*I != i)
14349         return false;
14350       i++;
14351     }
14352     return true;
14353   };
14354 
14355   SelectionDAG &DAG = DCI.DAG;
14356   EVT VT = SVN->getValueType(0);
14357 
14358   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14359     return SDValue();
14360 
14361   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14362   // See comment in PPCVSXSwapRemoval.cpp.
14363   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14364   if (!Subtarget.hasP9Vector())
14365     return SDValue();
14366 
14367   if(!IsElementReverse(SVN))
14368     return SDValue();
14369 
14370   if (LSBase->getOpcode() == ISD::LOAD) {
14371     SDLoc dl(SVN);
14372     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14373     return DAG.getMemIntrinsicNode(
14374         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14375         LSBase->getMemoryVT(), LSBase->getMemOperand());
14376   }
14377 
14378   if (LSBase->getOpcode() == ISD::STORE) {
14379     SDLoc dl(LSBase);
14380     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14381                           LSBase->getBasePtr()};
14382     return DAG.getMemIntrinsicNode(
14383         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14384         LSBase->getMemoryVT(), LSBase->getMemOperand());
14385   }
14386 
14387   llvm_unreachable("Expected a load or store node here");
14388 }
14389 
14390 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14391                                              DAGCombinerInfo &DCI) const {
14392   SelectionDAG &DAG = DCI.DAG;
14393   SDLoc dl(N);
14394   switch (N->getOpcode()) {
14395   default: break;
14396   case ISD::ADD:
14397     return combineADD(N, DCI);
14398   case ISD::SHL:
14399     return combineSHL(N, DCI);
14400   case ISD::SRA:
14401     return combineSRA(N, DCI);
14402   case ISD::SRL:
14403     return combineSRL(N, DCI);
14404   case ISD::MUL:
14405     return combineMUL(N, DCI);
14406   case ISD::FMA:
14407   case PPCISD::FNMSUB:
14408     return combineFMALike(N, DCI);
14409   case PPCISD::SHL:
14410     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14411         return N->getOperand(0);
14412     break;
14413   case PPCISD::SRL:
14414     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14415         return N->getOperand(0);
14416     break;
14417   case PPCISD::SRA:
14418     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14419       if (C->isNullValue() ||   //  0 >>s V -> 0.
14420           C->isAllOnesValue())    // -1 >>s V -> -1.
14421         return N->getOperand(0);
14422     }
14423     break;
14424   case ISD::SIGN_EXTEND:
14425   case ISD::ZERO_EXTEND:
14426   case ISD::ANY_EXTEND:
14427     return DAGCombineExtBoolTrunc(N, DCI);
14428   case ISD::TRUNCATE:
14429     return combineTRUNCATE(N, DCI);
14430   case ISD::SETCC:
14431     if (SDValue CSCC = combineSetCC(N, DCI))
14432       return CSCC;
14433     LLVM_FALLTHROUGH;
14434   case ISD::SELECT_CC:
14435     return DAGCombineTruncBoolExt(N, DCI);
14436   case ISD::SINT_TO_FP:
14437   case ISD::UINT_TO_FP:
14438     return combineFPToIntToFP(N, DCI);
14439   case ISD::VECTOR_SHUFFLE:
14440     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14441       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14442       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14443     }
14444     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14445   case ISD::STORE: {
14446 
14447     EVT Op1VT = N->getOperand(1).getValueType();
14448     unsigned Opcode = N->getOperand(1).getOpcode();
14449 
14450     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14451       SDValue Val= combineStoreFPToInt(N, DCI);
14452       if (Val)
14453         return Val;
14454     }
14455 
14456     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14457       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14458       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14459       if (Val)
14460         return Val;
14461     }
14462 
14463     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14464     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14465         N->getOperand(1).getNode()->hasOneUse() &&
14466         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14467          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14468 
14469       // STBRX can only handle simple types and it makes no sense to store less
14470       // two bytes in byte-reversed order.
14471       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14472       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14473         break;
14474 
14475       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14476       // Do an any-extend to 32-bits if this is a half-word input.
14477       if (BSwapOp.getValueType() == MVT::i16)
14478         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14479 
14480       // If the type of BSWAP operand is wider than stored memory width
14481       // it need to be shifted to the right side before STBRX.
14482       if (Op1VT.bitsGT(mVT)) {
14483         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14484         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14485                               DAG.getConstant(Shift, dl, MVT::i32));
14486         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14487         if (Op1VT == MVT::i64)
14488           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14489       }
14490 
14491       SDValue Ops[] = {
14492         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14493       };
14494       return
14495         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14496                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14497                                 cast<StoreSDNode>(N)->getMemOperand());
14498     }
14499 
14500     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14501     // So it can increase the chance of CSE constant construction.
14502     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14503         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14504       // Need to sign-extended to 64-bits to handle negative values.
14505       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14506       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14507                                     MemVT.getSizeInBits());
14508       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14509 
14510       // DAG.getTruncStore() can't be used here because it doesn't accept
14511       // the general (base + offset) addressing mode.
14512       // So we use UpdateNodeOperands and setTruncatingStore instead.
14513       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14514                              N->getOperand(3));
14515       cast<StoreSDNode>(N)->setTruncatingStore(true);
14516       return SDValue(N, 0);
14517     }
14518 
14519     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14520     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14521     if (Op1VT.isSimple()) {
14522       MVT StoreVT = Op1VT.getSimpleVT();
14523       if (Subtarget.needsSwapsForVSXMemOps() &&
14524           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14525            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14526         return expandVSXStoreForLE(N, DCI);
14527     }
14528     break;
14529   }
14530   case ISD::LOAD: {
14531     LoadSDNode *LD = cast<LoadSDNode>(N);
14532     EVT VT = LD->getValueType(0);
14533 
14534     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14535     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14536     if (VT.isSimple()) {
14537       MVT LoadVT = VT.getSimpleVT();
14538       if (Subtarget.needsSwapsForVSXMemOps() &&
14539           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14540            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14541         return expandVSXLoadForLE(N, DCI);
14542     }
14543 
14544     // We sometimes end up with a 64-bit integer load, from which we extract
14545     // two single-precision floating-point numbers. This happens with
14546     // std::complex<float>, and other similar structures, because of the way we
14547     // canonicalize structure copies. However, if we lack direct moves,
14548     // then the final bitcasts from the extracted integer values to the
14549     // floating-point numbers turn into store/load pairs. Even with direct moves,
14550     // just loading the two floating-point numbers is likely better.
14551     auto ReplaceTwoFloatLoad = [&]() {
14552       if (VT != MVT::i64)
14553         return false;
14554 
14555       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14556           LD->isVolatile())
14557         return false;
14558 
14559       //  We're looking for a sequence like this:
14560       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14561       //      t16: i64 = srl t13, Constant:i32<32>
14562       //    t17: i32 = truncate t16
14563       //  t18: f32 = bitcast t17
14564       //    t19: i32 = truncate t13
14565       //  t20: f32 = bitcast t19
14566 
14567       if (!LD->hasNUsesOfValue(2, 0))
14568         return false;
14569 
14570       auto UI = LD->use_begin();
14571       while (UI.getUse().getResNo() != 0) ++UI;
14572       SDNode *Trunc = *UI++;
14573       while (UI.getUse().getResNo() != 0) ++UI;
14574       SDNode *RightShift = *UI;
14575       if (Trunc->getOpcode() != ISD::TRUNCATE)
14576         std::swap(Trunc, RightShift);
14577 
14578       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14579           Trunc->getValueType(0) != MVT::i32 ||
14580           !Trunc->hasOneUse())
14581         return false;
14582       if (RightShift->getOpcode() != ISD::SRL ||
14583           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14584           RightShift->getConstantOperandVal(1) != 32 ||
14585           !RightShift->hasOneUse())
14586         return false;
14587 
14588       SDNode *Trunc2 = *RightShift->use_begin();
14589       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14590           Trunc2->getValueType(0) != MVT::i32 ||
14591           !Trunc2->hasOneUse())
14592         return false;
14593 
14594       SDNode *Bitcast = *Trunc->use_begin();
14595       SDNode *Bitcast2 = *Trunc2->use_begin();
14596 
14597       if (Bitcast->getOpcode() != ISD::BITCAST ||
14598           Bitcast->getValueType(0) != MVT::f32)
14599         return false;
14600       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14601           Bitcast2->getValueType(0) != MVT::f32)
14602         return false;
14603 
14604       if (Subtarget.isLittleEndian())
14605         std::swap(Bitcast, Bitcast2);
14606 
14607       // Bitcast has the second float (in memory-layout order) and Bitcast2
14608       // has the first one.
14609 
14610       SDValue BasePtr = LD->getBasePtr();
14611       if (LD->isIndexed()) {
14612         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14613                "Non-pre-inc AM on PPC?");
14614         BasePtr =
14615           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14616                       LD->getOffset());
14617       }
14618 
14619       auto MMOFlags =
14620           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14621       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14622                                       LD->getPointerInfo(), LD->getAlignment(),
14623                                       MMOFlags, LD->getAAInfo());
14624       SDValue AddPtr =
14625         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14626                     BasePtr, DAG.getIntPtrConstant(4, dl));
14627       SDValue FloatLoad2 = DAG.getLoad(
14628           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14629           LD->getPointerInfo().getWithOffset(4),
14630           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14631 
14632       if (LD->isIndexed()) {
14633         // Note that DAGCombine should re-form any pre-increment load(s) from
14634         // what is produced here if that makes sense.
14635         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14636       }
14637 
14638       DCI.CombineTo(Bitcast2, FloatLoad);
14639       DCI.CombineTo(Bitcast, FloatLoad2);
14640 
14641       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14642                                     SDValue(FloatLoad2.getNode(), 1));
14643       return true;
14644     };
14645 
14646     if (ReplaceTwoFloatLoad())
14647       return SDValue(N, 0);
14648 
14649     EVT MemVT = LD->getMemoryVT();
14650     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14651     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14652     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14653     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14654     if (LD->isUnindexed() && VT.isVector() &&
14655         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14656           // P8 and later hardware should just use LOAD.
14657           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14658                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14659          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14660           LD->getAlignment() >= ScalarABIAlignment)) &&
14661         LD->getAlignment() < ABIAlignment) {
14662       // This is a type-legal unaligned Altivec or QPX load.
14663       SDValue Chain = LD->getChain();
14664       SDValue Ptr = LD->getBasePtr();
14665       bool isLittleEndian = Subtarget.isLittleEndian();
14666 
14667       // This implements the loading of unaligned vectors as described in
14668       // the venerable Apple Velocity Engine overview. Specifically:
14669       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14670       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14671       //
14672       // The general idea is to expand a sequence of one or more unaligned
14673       // loads into an alignment-based permutation-control instruction (lvsl
14674       // or lvsr), a series of regular vector loads (which always truncate
14675       // their input address to an aligned address), and a series of
14676       // permutations.  The results of these permutations are the requested
14677       // loaded values.  The trick is that the last "extra" load is not taken
14678       // from the address you might suspect (sizeof(vector) bytes after the
14679       // last requested load), but rather sizeof(vector) - 1 bytes after the
14680       // last requested vector. The point of this is to avoid a page fault if
14681       // the base address happened to be aligned. This works because if the
14682       // base address is aligned, then adding less than a full vector length
14683       // will cause the last vector in the sequence to be (re)loaded.
14684       // Otherwise, the next vector will be fetched as you might suspect was
14685       // necessary.
14686 
14687       // We might be able to reuse the permutation generation from
14688       // a different base address offset from this one by an aligned amount.
14689       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14690       // optimization later.
14691       Intrinsic::ID Intr, IntrLD, IntrPerm;
14692       MVT PermCntlTy, PermTy, LDTy;
14693       if (Subtarget.hasAltivec()) {
14694         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14695                                  Intrinsic::ppc_altivec_lvsl;
14696         IntrLD = Intrinsic::ppc_altivec_lvx;
14697         IntrPerm = Intrinsic::ppc_altivec_vperm;
14698         PermCntlTy = MVT::v16i8;
14699         PermTy = MVT::v4i32;
14700         LDTy = MVT::v4i32;
14701       } else {
14702         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14703                                        Intrinsic::ppc_qpx_qvlpcls;
14704         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14705                                        Intrinsic::ppc_qpx_qvlfs;
14706         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14707         PermCntlTy = MVT::v4f64;
14708         PermTy = MVT::v4f64;
14709         LDTy = MemVT.getSimpleVT();
14710       }
14711 
14712       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14713 
14714       // Create the new MMO for the new base load. It is like the original MMO,
14715       // but represents an area in memory almost twice the vector size centered
14716       // on the original address. If the address is unaligned, we might start
14717       // reading up to (sizeof(vector)-1) bytes below the address of the
14718       // original unaligned load.
14719       MachineFunction &MF = DAG.getMachineFunction();
14720       MachineMemOperand *BaseMMO =
14721         MF.getMachineMemOperand(LD->getMemOperand(),
14722                                 -(long)MemVT.getStoreSize()+1,
14723                                 2*MemVT.getStoreSize()-1);
14724 
14725       // Create the new base load.
14726       SDValue LDXIntID =
14727           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14728       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14729       SDValue BaseLoad =
14730         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14731                                 DAG.getVTList(PermTy, MVT::Other),
14732                                 BaseLoadOps, LDTy, BaseMMO);
14733 
14734       // Note that the value of IncOffset (which is provided to the next
14735       // load's pointer info offset value, and thus used to calculate the
14736       // alignment), and the value of IncValue (which is actually used to
14737       // increment the pointer value) are different! This is because we
14738       // require the next load to appear to be aligned, even though it
14739       // is actually offset from the base pointer by a lesser amount.
14740       int IncOffset = VT.getSizeInBits() / 8;
14741       int IncValue = IncOffset;
14742 
14743       // Walk (both up and down) the chain looking for another load at the real
14744       // (aligned) offset (the alignment of the other load does not matter in
14745       // this case). If found, then do not use the offset reduction trick, as
14746       // that will prevent the loads from being later combined (as they would
14747       // otherwise be duplicates).
14748       if (!findConsecutiveLoad(LD, DAG))
14749         --IncValue;
14750 
14751       SDValue Increment =
14752           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14753       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14754 
14755       MachineMemOperand *ExtraMMO =
14756         MF.getMachineMemOperand(LD->getMemOperand(),
14757                                 1, 2*MemVT.getStoreSize()-1);
14758       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14759       SDValue ExtraLoad =
14760         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14761                                 DAG.getVTList(PermTy, MVT::Other),
14762                                 ExtraLoadOps, LDTy, ExtraMMO);
14763 
14764       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14765         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14766 
14767       // Because vperm has a big-endian bias, we must reverse the order
14768       // of the input vectors and complement the permute control vector
14769       // when generating little endian code.  We have already handled the
14770       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14771       // and ExtraLoad here.
14772       SDValue Perm;
14773       if (isLittleEndian)
14774         Perm = BuildIntrinsicOp(IntrPerm,
14775                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14776       else
14777         Perm = BuildIntrinsicOp(IntrPerm,
14778                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14779 
14780       if (VT != PermTy)
14781         Perm = Subtarget.hasAltivec() ?
14782                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14783                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14784                                DAG.getTargetConstant(1, dl, MVT::i64));
14785                                // second argument is 1 because this rounding
14786                                // is always exact.
14787 
14788       // The output of the permutation is our loaded result, the TokenFactor is
14789       // our new chain.
14790       DCI.CombineTo(N, Perm, TF);
14791       return SDValue(N, 0);
14792     }
14793     }
14794     break;
14795     case ISD::INTRINSIC_WO_CHAIN: {
14796       bool isLittleEndian = Subtarget.isLittleEndian();
14797       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14798       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14799                                            : Intrinsic::ppc_altivec_lvsl);
14800       if ((IID == Intr ||
14801            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14802            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14803         N->getOperand(1)->getOpcode() == ISD::ADD) {
14804         SDValue Add = N->getOperand(1);
14805 
14806         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14807                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14808 
14809         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14810                                   APInt::getAllOnesValue(Bits /* alignment */)
14811                                       .zext(Add.getScalarValueSizeInBits()))) {
14812           SDNode *BasePtr = Add->getOperand(0).getNode();
14813           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14814                                     UE = BasePtr->use_end();
14815                UI != UE; ++UI) {
14816             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14817                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14818               // We've found another LVSL/LVSR, and this address is an aligned
14819               // multiple of that one. The results will be the same, so use the
14820               // one we've just found instead.
14821 
14822               return SDValue(*UI, 0);
14823             }
14824           }
14825         }
14826 
14827         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14828           SDNode *BasePtr = Add->getOperand(0).getNode();
14829           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14830                UE = BasePtr->use_end(); UI != UE; ++UI) {
14831             if (UI->getOpcode() == ISD::ADD &&
14832                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14833                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14834                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14835                 (1ULL << Bits) == 0) {
14836               SDNode *OtherAdd = *UI;
14837               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14838                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14839                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14840                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14841                   return SDValue(*VI, 0);
14842                 }
14843               }
14844             }
14845           }
14846         }
14847       }
14848 
14849       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14850       // Expose the vabsduw/h/b opportunity for down stream
14851       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14852           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14853            IID == Intrinsic::ppc_altivec_vmaxsh ||
14854            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14855         SDValue V1 = N->getOperand(1);
14856         SDValue V2 = N->getOperand(2);
14857         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14858              V1.getSimpleValueType() == MVT::v8i16 ||
14859              V1.getSimpleValueType() == MVT::v16i8) &&
14860             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14861           // (0-a, a)
14862           if (V1.getOpcode() == ISD::SUB &&
14863               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14864               V1.getOperand(1) == V2) {
14865             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14866           }
14867           // (a, 0-a)
14868           if (V2.getOpcode() == ISD::SUB &&
14869               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14870               V2.getOperand(1) == V1) {
14871             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14872           }
14873           // (x-y, y-x)
14874           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14875               V1.getOperand(0) == V2.getOperand(1) &&
14876               V1.getOperand(1) == V2.getOperand(0)) {
14877             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14878           }
14879         }
14880       }
14881     }
14882 
14883     break;
14884   case ISD::INTRINSIC_W_CHAIN:
14885     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14886     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14887     if (Subtarget.needsSwapsForVSXMemOps()) {
14888       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14889       default:
14890         break;
14891       case Intrinsic::ppc_vsx_lxvw4x:
14892       case Intrinsic::ppc_vsx_lxvd2x:
14893         return expandVSXLoadForLE(N, DCI);
14894       }
14895     }
14896     break;
14897   case ISD::INTRINSIC_VOID:
14898     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14899     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14900     if (Subtarget.needsSwapsForVSXMemOps()) {
14901       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14902       default:
14903         break;
14904       case Intrinsic::ppc_vsx_stxvw4x:
14905       case Intrinsic::ppc_vsx_stxvd2x:
14906         return expandVSXStoreForLE(N, DCI);
14907       }
14908     }
14909     break;
14910   case ISD::BSWAP:
14911     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14912     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14913         N->getOperand(0).hasOneUse() &&
14914         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14915          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14916           N->getValueType(0) == MVT::i64))) {
14917       SDValue Load = N->getOperand(0);
14918       LoadSDNode *LD = cast<LoadSDNode>(Load);
14919       // Create the byte-swapping load.
14920       SDValue Ops[] = {
14921         LD->getChain(),    // Chain
14922         LD->getBasePtr(),  // Ptr
14923         DAG.getValueType(N->getValueType(0)) // VT
14924       };
14925       SDValue BSLoad =
14926         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14927                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14928                                               MVT::i64 : MVT::i32, MVT::Other),
14929                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14930 
14931       // If this is an i16 load, insert the truncate.
14932       SDValue ResVal = BSLoad;
14933       if (N->getValueType(0) == MVT::i16)
14934         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14935 
14936       // First, combine the bswap away.  This makes the value produced by the
14937       // load dead.
14938       DCI.CombineTo(N, ResVal);
14939 
14940       // Next, combine the load away, we give it a bogus result value but a real
14941       // chain result.  The result value is dead because the bswap is dead.
14942       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14943 
14944       // Return N so it doesn't get rechecked!
14945       return SDValue(N, 0);
14946     }
14947     break;
14948   case PPCISD::VCMP:
14949     // If a VCMPo node already exists with exactly the same operands as this
14950     // node, use its result instead of this node (VCMPo computes both a CR6 and
14951     // a normal output).
14952     //
14953     if (!N->getOperand(0).hasOneUse() &&
14954         !N->getOperand(1).hasOneUse() &&
14955         !N->getOperand(2).hasOneUse()) {
14956 
14957       // Scan all of the users of the LHS, looking for VCMPo's that match.
14958       SDNode *VCMPoNode = nullptr;
14959 
14960       SDNode *LHSN = N->getOperand(0).getNode();
14961       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14962            UI != E; ++UI)
14963         if (UI->getOpcode() == PPCISD::VCMPo &&
14964             UI->getOperand(1) == N->getOperand(1) &&
14965             UI->getOperand(2) == N->getOperand(2) &&
14966             UI->getOperand(0) == N->getOperand(0)) {
14967           VCMPoNode = *UI;
14968           break;
14969         }
14970 
14971       // If there is no VCMPo node, or if the flag value has a single use, don't
14972       // transform this.
14973       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14974         break;
14975 
14976       // Look at the (necessarily single) use of the flag value.  If it has a
14977       // chain, this transformation is more complex.  Note that multiple things
14978       // could use the value result, which we should ignore.
14979       SDNode *FlagUser = nullptr;
14980       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14981            FlagUser == nullptr; ++UI) {
14982         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14983         SDNode *User = *UI;
14984         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14985           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14986             FlagUser = User;
14987             break;
14988           }
14989         }
14990       }
14991 
14992       // If the user is a MFOCRF instruction, we know this is safe.
14993       // Otherwise we give up for right now.
14994       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14995         return SDValue(VCMPoNode, 0);
14996     }
14997     break;
14998   case ISD::BRCOND: {
14999     SDValue Cond = N->getOperand(1);
15000     SDValue Target = N->getOperand(2);
15001 
15002     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15003         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15004           Intrinsic::loop_decrement) {
15005 
15006       // We now need to make the intrinsic dead (it cannot be instruction
15007       // selected).
15008       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15009       assert(Cond.getNode()->hasOneUse() &&
15010              "Counter decrement has more than one use");
15011 
15012       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15013                          N->getOperand(0), Target);
15014     }
15015   }
15016   break;
15017   case ISD::BR_CC: {
15018     // If this is a branch on an altivec predicate comparison, lower this so
15019     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15020     // lowering is done pre-legalize, because the legalizer lowers the predicate
15021     // compare down to code that is difficult to reassemble.
15022     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15023     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15024 
15025     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15026     // value. If so, pass-through the AND to get to the intrinsic.
15027     if (LHS.getOpcode() == ISD::AND &&
15028         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15029         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15030           Intrinsic::loop_decrement &&
15031         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15032         !isNullConstant(LHS.getOperand(1)))
15033       LHS = LHS.getOperand(0);
15034 
15035     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15036         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15037           Intrinsic::loop_decrement &&
15038         isa<ConstantSDNode>(RHS)) {
15039       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15040              "Counter decrement comparison is not EQ or NE");
15041 
15042       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15043       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15044                     (CC == ISD::SETNE && !Val);
15045 
15046       // We now need to make the intrinsic dead (it cannot be instruction
15047       // selected).
15048       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15049       assert(LHS.getNode()->hasOneUse() &&
15050              "Counter decrement has more than one use");
15051 
15052       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15053                          N->getOperand(0), N->getOperand(4));
15054     }
15055 
15056     int CompareOpc;
15057     bool isDot;
15058 
15059     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15060         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15061         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15062       assert(isDot && "Can't compare against a vector result!");
15063 
15064       // If this is a comparison against something other than 0/1, then we know
15065       // that the condition is never/always true.
15066       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15067       if (Val != 0 && Val != 1) {
15068         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15069           return N->getOperand(0);
15070         // Always !=, turn it into an unconditional branch.
15071         return DAG.getNode(ISD::BR, dl, MVT::Other,
15072                            N->getOperand(0), N->getOperand(4));
15073       }
15074 
15075       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15076 
15077       // Create the PPCISD altivec 'dot' comparison node.
15078       SDValue Ops[] = {
15079         LHS.getOperand(2),  // LHS of compare
15080         LHS.getOperand(3),  // RHS of compare
15081         DAG.getConstant(CompareOpc, dl, MVT::i32)
15082       };
15083       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15084       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
15085 
15086       // Unpack the result based on how the target uses it.
15087       PPC::Predicate CompOpc;
15088       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15089       default:  // Can't happen, don't crash on invalid number though.
15090       case 0:   // Branch on the value of the EQ bit of CR6.
15091         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15092         break;
15093       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15094         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15095         break;
15096       case 2:   // Branch on the value of the LT bit of CR6.
15097         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15098         break;
15099       case 3:   // Branch on the inverted value of the LT bit of CR6.
15100         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15101         break;
15102       }
15103 
15104       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15105                          DAG.getConstant(CompOpc, dl, MVT::i32),
15106                          DAG.getRegister(PPC::CR6, MVT::i32),
15107                          N->getOperand(4), CompNode.getValue(1));
15108     }
15109     break;
15110   }
15111   case ISD::BUILD_VECTOR:
15112     return DAGCombineBuildVector(N, DCI);
15113   case ISD::ABS:
15114     return combineABS(N, DCI);
15115   case ISD::VSELECT:
15116     return combineVSelect(N, DCI);
15117   }
15118 
15119   return SDValue();
15120 }
15121 
15122 SDValue
15123 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15124                                  SelectionDAG &DAG,
15125                                  SmallVectorImpl<SDNode *> &Created) const {
15126   // fold (sdiv X, pow2)
15127   EVT VT = N->getValueType(0);
15128   if (VT == MVT::i64 && !Subtarget.isPPC64())
15129     return SDValue();
15130   if ((VT != MVT::i32 && VT != MVT::i64) ||
15131       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15132     return SDValue();
15133 
15134   SDLoc DL(N);
15135   SDValue N0 = N->getOperand(0);
15136 
15137   bool IsNegPow2 = (-Divisor).isPowerOf2();
15138   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15139   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15140 
15141   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15142   Created.push_back(Op.getNode());
15143 
15144   if (IsNegPow2) {
15145     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15146     Created.push_back(Op.getNode());
15147   }
15148 
15149   return Op;
15150 }
15151 
15152 //===----------------------------------------------------------------------===//
15153 // Inline Assembly Support
15154 //===----------------------------------------------------------------------===//
15155 
15156 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15157                                                       KnownBits &Known,
15158                                                       const APInt &DemandedElts,
15159                                                       const SelectionDAG &DAG,
15160                                                       unsigned Depth) const {
15161   Known.resetAll();
15162   switch (Op.getOpcode()) {
15163   default: break;
15164   case PPCISD::LBRX: {
15165     // lhbrx is known to have the top bits cleared out.
15166     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15167       Known.Zero = 0xFFFF0000;
15168     break;
15169   }
15170   case ISD::INTRINSIC_WO_CHAIN: {
15171     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15172     default: break;
15173     case Intrinsic::ppc_altivec_vcmpbfp_p:
15174     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15175     case Intrinsic::ppc_altivec_vcmpequb_p:
15176     case Intrinsic::ppc_altivec_vcmpequh_p:
15177     case Intrinsic::ppc_altivec_vcmpequw_p:
15178     case Intrinsic::ppc_altivec_vcmpequd_p:
15179     case Intrinsic::ppc_altivec_vcmpgefp_p:
15180     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15181     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15182     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15183     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15184     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15185     case Intrinsic::ppc_altivec_vcmpgtub_p:
15186     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15187     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15188     case Intrinsic::ppc_altivec_vcmpgtud_p:
15189       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15190       break;
15191     }
15192   }
15193   }
15194 }
15195 
15196 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15197   switch (Subtarget.getCPUDirective()) {
15198   default: break;
15199   case PPC::DIR_970:
15200   case PPC::DIR_PWR4:
15201   case PPC::DIR_PWR5:
15202   case PPC::DIR_PWR5X:
15203   case PPC::DIR_PWR6:
15204   case PPC::DIR_PWR6X:
15205   case PPC::DIR_PWR7:
15206   case PPC::DIR_PWR8:
15207   case PPC::DIR_PWR9:
15208   case PPC::DIR_PWR10:
15209   case PPC::DIR_PWR_FUTURE: {
15210     if (!ML)
15211       break;
15212 
15213     if (!DisableInnermostLoopAlign32) {
15214       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15215       // so that we can decrease cache misses and branch-prediction misses.
15216       // Actual alignment of the loop will depend on the hotness check and other
15217       // logic in alignBlocks.
15218       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15219         return Align(32);
15220     }
15221 
15222     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15223 
15224     // For small loops (between 5 and 8 instructions), align to a 32-byte
15225     // boundary so that the entire loop fits in one instruction-cache line.
15226     uint64_t LoopSize = 0;
15227     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15228       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15229         LoopSize += TII->getInstSizeInBytes(*J);
15230         if (LoopSize > 32)
15231           break;
15232       }
15233 
15234     if (LoopSize > 16 && LoopSize <= 32)
15235       return Align(32);
15236 
15237     break;
15238   }
15239   }
15240 
15241   return TargetLowering::getPrefLoopAlignment(ML);
15242 }
15243 
15244 /// getConstraintType - Given a constraint, return the type of
15245 /// constraint it is for this target.
15246 PPCTargetLowering::ConstraintType
15247 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15248   if (Constraint.size() == 1) {
15249     switch (Constraint[0]) {
15250     default: break;
15251     case 'b':
15252     case 'r':
15253     case 'f':
15254     case 'd':
15255     case 'v':
15256     case 'y':
15257       return C_RegisterClass;
15258     case 'Z':
15259       // FIXME: While Z does indicate a memory constraint, it specifically
15260       // indicates an r+r address (used in conjunction with the 'y' modifier
15261       // in the replacement string). Currently, we're forcing the base
15262       // register to be r0 in the asm printer (which is interpreted as zero)
15263       // and forming the complete address in the second register. This is
15264       // suboptimal.
15265       return C_Memory;
15266     }
15267   } else if (Constraint == "wc") { // individual CR bits.
15268     return C_RegisterClass;
15269   } else if (Constraint == "wa" || Constraint == "wd" ||
15270              Constraint == "wf" || Constraint == "ws" ||
15271              Constraint == "wi" || Constraint == "ww") {
15272     return C_RegisterClass; // VSX registers.
15273   }
15274   return TargetLowering::getConstraintType(Constraint);
15275 }
15276 
15277 /// Examine constraint type and operand type and determine a weight value.
15278 /// This object must already have been set up with the operand type
15279 /// and the current alternative constraint selected.
15280 TargetLowering::ConstraintWeight
15281 PPCTargetLowering::getSingleConstraintMatchWeight(
15282     AsmOperandInfo &info, const char *constraint) const {
15283   ConstraintWeight weight = CW_Invalid;
15284   Value *CallOperandVal = info.CallOperandVal;
15285     // If we don't have a value, we can't do a match,
15286     // but allow it at the lowest weight.
15287   if (!CallOperandVal)
15288     return CW_Default;
15289   Type *type = CallOperandVal->getType();
15290 
15291   // Look at the constraint type.
15292   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15293     return CW_Register; // an individual CR bit.
15294   else if ((StringRef(constraint) == "wa" ||
15295             StringRef(constraint) == "wd" ||
15296             StringRef(constraint) == "wf") &&
15297            type->isVectorTy())
15298     return CW_Register;
15299   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15300     return CW_Register; // just hold 64-bit integers data.
15301   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15302     return CW_Register;
15303   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15304     return CW_Register;
15305 
15306   switch (*constraint) {
15307   default:
15308     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15309     break;
15310   case 'b':
15311     if (type->isIntegerTy())
15312       weight = CW_Register;
15313     break;
15314   case 'f':
15315     if (type->isFloatTy())
15316       weight = CW_Register;
15317     break;
15318   case 'd':
15319     if (type->isDoubleTy())
15320       weight = CW_Register;
15321     break;
15322   case 'v':
15323     if (type->isVectorTy())
15324       weight = CW_Register;
15325     break;
15326   case 'y':
15327     weight = CW_Register;
15328     break;
15329   case 'Z':
15330     weight = CW_Memory;
15331     break;
15332   }
15333   return weight;
15334 }
15335 
15336 std::pair<unsigned, const TargetRegisterClass *>
15337 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15338                                                 StringRef Constraint,
15339                                                 MVT VT) const {
15340   if (Constraint.size() == 1) {
15341     // GCC RS6000 Constraint Letters
15342     switch (Constraint[0]) {
15343     case 'b':   // R1-R31
15344       if (VT == MVT::i64 && Subtarget.isPPC64())
15345         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15346       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15347     case 'r':   // R0-R31
15348       if (VT == MVT::i64 && Subtarget.isPPC64())
15349         return std::make_pair(0U, &PPC::G8RCRegClass);
15350       return std::make_pair(0U, &PPC::GPRCRegClass);
15351     // 'd' and 'f' constraints are both defined to be "the floating point
15352     // registers", where one is for 32-bit and the other for 64-bit. We don't
15353     // really care overly much here so just give them all the same reg classes.
15354     case 'd':
15355     case 'f':
15356       if (Subtarget.hasSPE()) {
15357         if (VT == MVT::f32 || VT == MVT::i32)
15358           return std::make_pair(0U, &PPC::GPRCRegClass);
15359         if (VT == MVT::f64 || VT == MVT::i64)
15360           return std::make_pair(0U, &PPC::SPERCRegClass);
15361       } else {
15362         if (VT == MVT::f32 || VT == MVT::i32)
15363           return std::make_pair(0U, &PPC::F4RCRegClass);
15364         if (VT == MVT::f64 || VT == MVT::i64)
15365           return std::make_pair(0U, &PPC::F8RCRegClass);
15366         if (VT == MVT::v4f64 && Subtarget.hasQPX())
15367           return std::make_pair(0U, &PPC::QFRCRegClass);
15368         if (VT == MVT::v4f32 && Subtarget.hasQPX())
15369           return std::make_pair(0U, &PPC::QSRCRegClass);
15370       }
15371       break;
15372     case 'v':
15373       if (VT == MVT::v4f64 && Subtarget.hasQPX())
15374         return std::make_pair(0U, &PPC::QFRCRegClass);
15375       if (VT == MVT::v4f32 && Subtarget.hasQPX())
15376         return std::make_pair(0U, &PPC::QSRCRegClass);
15377       if (Subtarget.hasAltivec())
15378         return std::make_pair(0U, &PPC::VRRCRegClass);
15379       break;
15380     case 'y':   // crrc
15381       return std::make_pair(0U, &PPC::CRRCRegClass);
15382     }
15383   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15384     // An individual CR bit.
15385     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15386   } else if ((Constraint == "wa" || Constraint == "wd" ||
15387              Constraint == "wf" || Constraint == "wi") &&
15388              Subtarget.hasVSX()) {
15389     return std::make_pair(0U, &PPC::VSRCRegClass);
15390   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15391     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15392       return std::make_pair(0U, &PPC::VSSRCRegClass);
15393     else
15394       return std::make_pair(0U, &PPC::VSFRCRegClass);
15395   }
15396 
15397   // If we name a VSX register, we can't defer to the base class because it
15398   // will not recognize the correct register (their names will be VSL{0-31}
15399   // and V{0-31} so they won't match). So we match them here.
15400   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15401     int VSNum = atoi(Constraint.data() + 3);
15402     assert(VSNum >= 0 && VSNum <= 63 &&
15403            "Attempted to access a vsr out of range");
15404     if (VSNum < 32)
15405       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15406     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15407   }
15408   std::pair<unsigned, const TargetRegisterClass *> R =
15409       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15410 
15411   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15412   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15413   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15414   // register.
15415   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15416   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15417   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15418       PPC::GPRCRegClass.contains(R.first))
15419     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15420                             PPC::sub_32, &PPC::G8RCRegClass),
15421                           &PPC::G8RCRegClass);
15422 
15423   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15424   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15425     R.first = PPC::CR0;
15426     R.second = &PPC::CRRCRegClass;
15427   }
15428 
15429   return R;
15430 }
15431 
15432 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15433 /// vector.  If it is invalid, don't add anything to Ops.
15434 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15435                                                      std::string &Constraint,
15436                                                      std::vector<SDValue>&Ops,
15437                                                      SelectionDAG &DAG) const {
15438   SDValue Result;
15439 
15440   // Only support length 1 constraints.
15441   if (Constraint.length() > 1) return;
15442 
15443   char Letter = Constraint[0];
15444   switch (Letter) {
15445   default: break;
15446   case 'I':
15447   case 'J':
15448   case 'K':
15449   case 'L':
15450   case 'M':
15451   case 'N':
15452   case 'O':
15453   case 'P': {
15454     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15455     if (!CST) return; // Must be an immediate to match.
15456     SDLoc dl(Op);
15457     int64_t Value = CST->getSExtValue();
15458     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15459                          // numbers are printed as such.
15460     switch (Letter) {
15461     default: llvm_unreachable("Unknown constraint letter!");
15462     case 'I':  // "I" is a signed 16-bit constant.
15463       if (isInt<16>(Value))
15464         Result = DAG.getTargetConstant(Value, dl, TCVT);
15465       break;
15466     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15467       if (isShiftedUInt<16, 16>(Value))
15468         Result = DAG.getTargetConstant(Value, dl, TCVT);
15469       break;
15470     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15471       if (isShiftedInt<16, 16>(Value))
15472         Result = DAG.getTargetConstant(Value, dl, TCVT);
15473       break;
15474     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15475       if (isUInt<16>(Value))
15476         Result = DAG.getTargetConstant(Value, dl, TCVT);
15477       break;
15478     case 'M':  // "M" is a constant that is greater than 31.
15479       if (Value > 31)
15480         Result = DAG.getTargetConstant(Value, dl, TCVT);
15481       break;
15482     case 'N':  // "N" is a positive constant that is an exact power of two.
15483       if (Value > 0 && isPowerOf2_64(Value))
15484         Result = DAG.getTargetConstant(Value, dl, TCVT);
15485       break;
15486     case 'O':  // "O" is the constant zero.
15487       if (Value == 0)
15488         Result = DAG.getTargetConstant(Value, dl, TCVT);
15489       break;
15490     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15491       if (isInt<16>(-Value))
15492         Result = DAG.getTargetConstant(Value, dl, TCVT);
15493       break;
15494     }
15495     break;
15496   }
15497   }
15498 
15499   if (Result.getNode()) {
15500     Ops.push_back(Result);
15501     return;
15502   }
15503 
15504   // Handle standard constraint letters.
15505   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15506 }
15507 
15508 // isLegalAddressingMode - Return true if the addressing mode represented
15509 // by AM is legal for this target, for a load/store of the specified type.
15510 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15511                                               const AddrMode &AM, Type *Ty,
15512                                               unsigned AS, Instruction *I) const {
15513   // PPC does not allow r+i addressing modes for vectors!
15514   if (Ty->isVectorTy() && AM.BaseOffs != 0)
15515     return false;
15516 
15517   // PPC allows a sign-extended 16-bit immediate field.
15518   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15519     return false;
15520 
15521   // No global is ever allowed as a base.
15522   if (AM.BaseGV)
15523     return false;
15524 
15525   // PPC only support r+r,
15526   switch (AM.Scale) {
15527   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15528     break;
15529   case 1:
15530     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15531       return false;
15532     // Otherwise we have r+r or r+i.
15533     break;
15534   case 2:
15535     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15536       return false;
15537     // Allow 2*r as r+r.
15538     break;
15539   default:
15540     // No other scales are supported.
15541     return false;
15542   }
15543 
15544   return true;
15545 }
15546 
15547 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15548                                            SelectionDAG &DAG) const {
15549   MachineFunction &MF = DAG.getMachineFunction();
15550   MachineFrameInfo &MFI = MF.getFrameInfo();
15551   MFI.setReturnAddressIsTaken(true);
15552 
15553   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15554     return SDValue();
15555 
15556   SDLoc dl(Op);
15557   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15558 
15559   // Make sure the function does not optimize away the store of the RA to
15560   // the stack.
15561   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15562   FuncInfo->setLRStoreRequired();
15563   bool isPPC64 = Subtarget.isPPC64();
15564   auto PtrVT = getPointerTy(MF.getDataLayout());
15565 
15566   if (Depth > 0) {
15567     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15568     SDValue Offset =
15569         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15570                         isPPC64 ? MVT::i64 : MVT::i32);
15571     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15572                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15573                        MachinePointerInfo());
15574   }
15575 
15576   // Just load the return address off the stack.
15577   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15578   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15579                      MachinePointerInfo());
15580 }
15581 
15582 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15583                                           SelectionDAG &DAG) const {
15584   SDLoc dl(Op);
15585   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15586 
15587   MachineFunction &MF = DAG.getMachineFunction();
15588   MachineFrameInfo &MFI = MF.getFrameInfo();
15589   MFI.setFrameAddressIsTaken(true);
15590 
15591   EVT PtrVT = getPointerTy(MF.getDataLayout());
15592   bool isPPC64 = PtrVT == MVT::i64;
15593 
15594   // Naked functions never have a frame pointer, and so we use r1. For all
15595   // other functions, this decision must be delayed until during PEI.
15596   unsigned FrameReg;
15597   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15598     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15599   else
15600     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15601 
15602   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15603                                          PtrVT);
15604   while (Depth--)
15605     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15606                             FrameAddr, MachinePointerInfo());
15607   return FrameAddr;
15608 }
15609 
15610 // FIXME? Maybe this could be a TableGen attribute on some registers and
15611 // this table could be generated automatically from RegInfo.
15612 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15613                                               const MachineFunction &MF) const {
15614   bool isPPC64 = Subtarget.isPPC64();
15615 
15616   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15617   if (!is64Bit && VT != LLT::scalar(32))
15618     report_fatal_error("Invalid register global variable type");
15619 
15620   Register Reg = StringSwitch<Register>(RegName)
15621                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15622                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15623                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15624                      .Default(Register());
15625 
15626   if (Reg)
15627     return Reg;
15628   report_fatal_error("Invalid register name global variable");
15629 }
15630 
15631 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15632   // 32-bit SVR4 ABI access everything as got-indirect.
15633   if (Subtarget.is32BitELFABI())
15634     return true;
15635 
15636   // AIX accesses everything indirectly through the TOC, which is similar to
15637   // the GOT.
15638   if (Subtarget.isAIXABI())
15639     return true;
15640 
15641   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15642   // If it is small or large code model, module locals are accessed
15643   // indirectly by loading their address from .toc/.got.
15644   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15645     return true;
15646 
15647   // JumpTable and BlockAddress are accessed as got-indirect.
15648   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15649     return true;
15650 
15651   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15652     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15653 
15654   return false;
15655 }
15656 
15657 bool
15658 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15659   // The PowerPC target isn't yet aware of offsets.
15660   return false;
15661 }
15662 
15663 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15664                                            const CallInst &I,
15665                                            MachineFunction &MF,
15666                                            unsigned Intrinsic) const {
15667   switch (Intrinsic) {
15668   case Intrinsic::ppc_qpx_qvlfd:
15669   case Intrinsic::ppc_qpx_qvlfs:
15670   case Intrinsic::ppc_qpx_qvlfcd:
15671   case Intrinsic::ppc_qpx_qvlfcs:
15672   case Intrinsic::ppc_qpx_qvlfiwa:
15673   case Intrinsic::ppc_qpx_qvlfiwz:
15674   case Intrinsic::ppc_altivec_lvx:
15675   case Intrinsic::ppc_altivec_lvxl:
15676   case Intrinsic::ppc_altivec_lvebx:
15677   case Intrinsic::ppc_altivec_lvehx:
15678   case Intrinsic::ppc_altivec_lvewx:
15679   case Intrinsic::ppc_vsx_lxvd2x:
15680   case Intrinsic::ppc_vsx_lxvw4x: {
15681     EVT VT;
15682     switch (Intrinsic) {
15683     case Intrinsic::ppc_altivec_lvebx:
15684       VT = MVT::i8;
15685       break;
15686     case Intrinsic::ppc_altivec_lvehx:
15687       VT = MVT::i16;
15688       break;
15689     case Intrinsic::ppc_altivec_lvewx:
15690       VT = MVT::i32;
15691       break;
15692     case Intrinsic::ppc_vsx_lxvd2x:
15693       VT = MVT::v2f64;
15694       break;
15695     case Intrinsic::ppc_qpx_qvlfd:
15696       VT = MVT::v4f64;
15697       break;
15698     case Intrinsic::ppc_qpx_qvlfs:
15699       VT = MVT::v4f32;
15700       break;
15701     case Intrinsic::ppc_qpx_qvlfcd:
15702       VT = MVT::v2f64;
15703       break;
15704     case Intrinsic::ppc_qpx_qvlfcs:
15705       VT = MVT::v2f32;
15706       break;
15707     default:
15708       VT = MVT::v4i32;
15709       break;
15710     }
15711 
15712     Info.opc = ISD::INTRINSIC_W_CHAIN;
15713     Info.memVT = VT;
15714     Info.ptrVal = I.getArgOperand(0);
15715     Info.offset = -VT.getStoreSize()+1;
15716     Info.size = 2*VT.getStoreSize()-1;
15717     Info.align = Align(1);
15718     Info.flags = MachineMemOperand::MOLoad;
15719     return true;
15720   }
15721   case Intrinsic::ppc_qpx_qvlfda:
15722   case Intrinsic::ppc_qpx_qvlfsa:
15723   case Intrinsic::ppc_qpx_qvlfcda:
15724   case Intrinsic::ppc_qpx_qvlfcsa:
15725   case Intrinsic::ppc_qpx_qvlfiwaa:
15726   case Intrinsic::ppc_qpx_qvlfiwza: {
15727     EVT VT;
15728     switch (Intrinsic) {
15729     case Intrinsic::ppc_qpx_qvlfda:
15730       VT = MVT::v4f64;
15731       break;
15732     case Intrinsic::ppc_qpx_qvlfsa:
15733       VT = MVT::v4f32;
15734       break;
15735     case Intrinsic::ppc_qpx_qvlfcda:
15736       VT = MVT::v2f64;
15737       break;
15738     case Intrinsic::ppc_qpx_qvlfcsa:
15739       VT = MVT::v2f32;
15740       break;
15741     default:
15742       VT = MVT::v4i32;
15743       break;
15744     }
15745 
15746     Info.opc = ISD::INTRINSIC_W_CHAIN;
15747     Info.memVT = VT;
15748     Info.ptrVal = I.getArgOperand(0);
15749     Info.offset = 0;
15750     Info.size = VT.getStoreSize();
15751     Info.align = Align(1);
15752     Info.flags = MachineMemOperand::MOLoad;
15753     return true;
15754   }
15755   case Intrinsic::ppc_qpx_qvstfd:
15756   case Intrinsic::ppc_qpx_qvstfs:
15757   case Intrinsic::ppc_qpx_qvstfcd:
15758   case Intrinsic::ppc_qpx_qvstfcs:
15759   case Intrinsic::ppc_qpx_qvstfiw:
15760   case Intrinsic::ppc_altivec_stvx:
15761   case Intrinsic::ppc_altivec_stvxl:
15762   case Intrinsic::ppc_altivec_stvebx:
15763   case Intrinsic::ppc_altivec_stvehx:
15764   case Intrinsic::ppc_altivec_stvewx:
15765   case Intrinsic::ppc_vsx_stxvd2x:
15766   case Intrinsic::ppc_vsx_stxvw4x: {
15767     EVT VT;
15768     switch (Intrinsic) {
15769     case Intrinsic::ppc_altivec_stvebx:
15770       VT = MVT::i8;
15771       break;
15772     case Intrinsic::ppc_altivec_stvehx:
15773       VT = MVT::i16;
15774       break;
15775     case Intrinsic::ppc_altivec_stvewx:
15776       VT = MVT::i32;
15777       break;
15778     case Intrinsic::ppc_vsx_stxvd2x:
15779       VT = MVT::v2f64;
15780       break;
15781     case Intrinsic::ppc_qpx_qvstfd:
15782       VT = MVT::v4f64;
15783       break;
15784     case Intrinsic::ppc_qpx_qvstfs:
15785       VT = MVT::v4f32;
15786       break;
15787     case Intrinsic::ppc_qpx_qvstfcd:
15788       VT = MVT::v2f64;
15789       break;
15790     case Intrinsic::ppc_qpx_qvstfcs:
15791       VT = MVT::v2f32;
15792       break;
15793     default:
15794       VT = MVT::v4i32;
15795       break;
15796     }
15797 
15798     Info.opc = ISD::INTRINSIC_VOID;
15799     Info.memVT = VT;
15800     Info.ptrVal = I.getArgOperand(1);
15801     Info.offset = -VT.getStoreSize()+1;
15802     Info.size = 2*VT.getStoreSize()-1;
15803     Info.align = Align(1);
15804     Info.flags = MachineMemOperand::MOStore;
15805     return true;
15806   }
15807   case Intrinsic::ppc_qpx_qvstfda:
15808   case Intrinsic::ppc_qpx_qvstfsa:
15809   case Intrinsic::ppc_qpx_qvstfcda:
15810   case Intrinsic::ppc_qpx_qvstfcsa:
15811   case Intrinsic::ppc_qpx_qvstfiwa: {
15812     EVT VT;
15813     switch (Intrinsic) {
15814     case Intrinsic::ppc_qpx_qvstfda:
15815       VT = MVT::v4f64;
15816       break;
15817     case Intrinsic::ppc_qpx_qvstfsa:
15818       VT = MVT::v4f32;
15819       break;
15820     case Intrinsic::ppc_qpx_qvstfcda:
15821       VT = MVT::v2f64;
15822       break;
15823     case Intrinsic::ppc_qpx_qvstfcsa:
15824       VT = MVT::v2f32;
15825       break;
15826     default:
15827       VT = MVT::v4i32;
15828       break;
15829     }
15830 
15831     Info.opc = ISD::INTRINSIC_VOID;
15832     Info.memVT = VT;
15833     Info.ptrVal = I.getArgOperand(1);
15834     Info.offset = 0;
15835     Info.size = VT.getStoreSize();
15836     Info.align = Align(1);
15837     Info.flags = MachineMemOperand::MOStore;
15838     return true;
15839   }
15840   default:
15841     break;
15842   }
15843 
15844   return false;
15845 }
15846 
15847 /// It returns EVT::Other if the type should be determined using generic
15848 /// target-independent logic.
15849 EVT PPCTargetLowering::getOptimalMemOpType(
15850     const MemOp &Op, const AttributeList &FuncAttributes) const {
15851   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15852     // When expanding a memset, require at least two QPX instructions to cover
15853     // the cost of loading the value to be stored from the constant pool.
15854     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15855         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15856         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15857       return MVT::v4f64;
15858     }
15859 
15860     // We should use Altivec/VSX loads and stores when available. For unaligned
15861     // addresses, unaligned VSX loads are only fast starting with the P8.
15862     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15863         (Op.isAligned(Align(16)) ||
15864          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15865       return MVT::v4i32;
15866   }
15867 
15868   if (Subtarget.isPPC64()) {
15869     return MVT::i64;
15870   }
15871 
15872   return MVT::i32;
15873 }
15874 
15875 /// Returns true if it is beneficial to convert a load of a constant
15876 /// to just the constant itself.
15877 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15878                                                           Type *Ty) const {
15879   assert(Ty->isIntegerTy());
15880 
15881   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15882   return !(BitSize == 0 || BitSize > 64);
15883 }
15884 
15885 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15886   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15887     return false;
15888   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15889   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15890   return NumBits1 == 64 && NumBits2 == 32;
15891 }
15892 
15893 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15894   if (!VT1.isInteger() || !VT2.isInteger())
15895     return false;
15896   unsigned NumBits1 = VT1.getSizeInBits();
15897   unsigned NumBits2 = VT2.getSizeInBits();
15898   return NumBits1 == 64 && NumBits2 == 32;
15899 }
15900 
15901 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15902   // Generally speaking, zexts are not free, but they are free when they can be
15903   // folded with other operations.
15904   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15905     EVT MemVT = LD->getMemoryVT();
15906     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15907          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15908         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15909          LD->getExtensionType() == ISD::ZEXTLOAD))
15910       return true;
15911   }
15912 
15913   // FIXME: Add other cases...
15914   //  - 32-bit shifts with a zext to i64
15915   //  - zext after ctlz, bswap, etc.
15916   //  - zext after and by a constant mask
15917 
15918   return TargetLowering::isZExtFree(Val, VT2);
15919 }
15920 
15921 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15922   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15923          "invalid fpext types");
15924   // Extending to float128 is not free.
15925   if (DestVT == MVT::f128)
15926     return false;
15927   return true;
15928 }
15929 
15930 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15931   return isInt<16>(Imm) || isUInt<16>(Imm);
15932 }
15933 
15934 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15935   return isInt<16>(Imm) || isUInt<16>(Imm);
15936 }
15937 
15938 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15939                                                        unsigned,
15940                                                        unsigned,
15941                                                        MachineMemOperand::Flags,
15942                                                        bool *Fast) const {
15943   if (DisablePPCUnaligned)
15944     return false;
15945 
15946   // PowerPC supports unaligned memory access for simple non-vector types.
15947   // Although accessing unaligned addresses is not as efficient as accessing
15948   // aligned addresses, it is generally more efficient than manual expansion,
15949   // and generally only traps for software emulation when crossing page
15950   // boundaries.
15951 
15952   if (!VT.isSimple())
15953     return false;
15954 
15955   if (VT.isFloatingPoint() && !VT.isVector() &&
15956       !Subtarget.allowsUnalignedFPAccess())
15957     return false;
15958 
15959   if (VT.getSimpleVT().isVector()) {
15960     if (Subtarget.hasVSX()) {
15961       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15962           VT != MVT::v4f32 && VT != MVT::v4i32)
15963         return false;
15964     } else {
15965       return false;
15966     }
15967   }
15968 
15969   if (VT == MVT::ppcf128)
15970     return false;
15971 
15972   if (Fast)
15973     *Fast = true;
15974 
15975   return true;
15976 }
15977 
15978 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15979                                                    EVT VT) const {
15980   return isFMAFasterThanFMulAndFAdd(
15981       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15982 }
15983 
15984 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15985                                                    Type *Ty) const {
15986   switch (Ty->getScalarType()->getTypeID()) {
15987   case Type::FloatTyID:
15988   case Type::DoubleTyID:
15989     return true;
15990   case Type::FP128TyID:
15991     return EnableQuadPrecision && Subtarget.hasP9Vector();
15992   default:
15993     return false;
15994   }
15995 }
15996 
15997 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
15998 // FIXME: add more patterns which are profitable to hoist.
15999 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16000   if (I->getOpcode() != Instruction::FMul)
16001     return true;
16002 
16003   if (!I->hasOneUse())
16004     return true;
16005 
16006   Instruction *User = I->user_back();
16007   assert(User && "A single use instruction with no uses.");
16008 
16009   if (User->getOpcode() != Instruction::FSub &&
16010       User->getOpcode() != Instruction::FAdd)
16011     return true;
16012 
16013   const TargetOptions &Options = getTargetMachine().Options;
16014   const Function *F = I->getFunction();
16015   const DataLayout &DL = F->getParent()->getDataLayout();
16016   Type *Ty = User->getOperand(0)->getType();
16017 
16018   return !(
16019       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16020       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16021       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16022 }
16023 
16024 const MCPhysReg *
16025 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16026   // LR is a callee-save register, but we must treat it as clobbered by any call
16027   // site. Hence we include LR in the scratch registers, which are in turn added
16028   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16029   // to CTR, which is used by any indirect call.
16030   static const MCPhysReg ScratchRegs[] = {
16031     PPC::X12, PPC::LR8, PPC::CTR8, 0
16032   };
16033 
16034   return ScratchRegs;
16035 }
16036 
16037 Register PPCTargetLowering::getExceptionPointerRegister(
16038     const Constant *PersonalityFn) const {
16039   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16040 }
16041 
16042 Register PPCTargetLowering::getExceptionSelectorRegister(
16043     const Constant *PersonalityFn) const {
16044   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16045 }
16046 
16047 bool
16048 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16049                      EVT VT , unsigned DefinedValues) const {
16050   if (VT == MVT::v2i64)
16051     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16052 
16053   if (Subtarget.hasVSX() || Subtarget.hasQPX())
16054     return true;
16055 
16056   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16057 }
16058 
16059 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16060   if (DisableILPPref || Subtarget.enableMachineScheduler())
16061     return TargetLowering::getSchedulingPreference(N);
16062 
16063   return Sched::ILP;
16064 }
16065 
16066 // Create a fast isel object.
16067 FastISel *
16068 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16069                                   const TargetLibraryInfo *LibInfo) const {
16070   return PPC::createFastISel(FuncInfo, LibInfo);
16071 }
16072 
16073 // 'Inverted' means the FMA opcode after negating one multiplicand.
16074 // For example, (fma -a b c) = (fnmsub a b c)
16075 static unsigned invertFMAOpcode(unsigned Opc) {
16076   switch (Opc) {
16077   default:
16078     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16079   case ISD::FMA:
16080     return PPCISD::FNMSUB;
16081   case PPCISD::FNMSUB:
16082     return ISD::FMA;
16083   }
16084 }
16085 
16086 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16087                                                 bool LegalOps, bool OptForSize,
16088                                                 NegatibleCost &Cost,
16089                                                 unsigned Depth) const {
16090   if (Depth > SelectionDAG::MaxRecursionDepth)
16091     return SDValue();
16092 
16093   unsigned Opc = Op.getOpcode();
16094   EVT VT = Op.getValueType();
16095   SDNodeFlags Flags = Op.getNode()->getFlags();
16096 
16097   switch (Opc) {
16098   case PPCISD::FNMSUB:
16099     // TODO: QPX subtarget is deprecated. No transformation here.
16100     if (!Op.hasOneUse() || !isTypeLegal(VT) || Subtarget.hasQPX())
16101       break;
16102 
16103     const TargetOptions &Options = getTargetMachine().Options;
16104     SDValue N0 = Op.getOperand(0);
16105     SDValue N1 = Op.getOperand(1);
16106     SDValue N2 = Op.getOperand(2);
16107     SDLoc Loc(Op);
16108 
16109     NegatibleCost N2Cost = NegatibleCost::Expensive;
16110     SDValue NegN2 =
16111         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16112 
16113     if (!NegN2)
16114       return SDValue();
16115 
16116     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16117     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16118     // These transformations may change sign of zeroes. For example,
16119     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16120     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16121       // Try and choose the cheaper one to negate.
16122       NegatibleCost N0Cost = NegatibleCost::Expensive;
16123       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16124                                            N0Cost, Depth + 1);
16125 
16126       NegatibleCost N1Cost = NegatibleCost::Expensive;
16127       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16128                                            N1Cost, Depth + 1);
16129 
16130       if (NegN0 && N0Cost <= N1Cost) {
16131         Cost = std::min(N0Cost, N2Cost);
16132         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16133       } else if (NegN1) {
16134         Cost = std::min(N1Cost, N2Cost);
16135         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16136       }
16137     }
16138 
16139     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16140     if (isOperationLegal(ISD::FMA, VT)) {
16141       Cost = N2Cost;
16142       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16143     }
16144 
16145     break;
16146   }
16147 
16148   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16149                                               Cost, Depth);
16150 }
16151 
16152 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16153 bool PPCTargetLowering::useLoadStackGuardNode() const {
16154   if (!Subtarget.isTargetLinux())
16155     return TargetLowering::useLoadStackGuardNode();
16156   return true;
16157 }
16158 
16159 // Override to disable global variable loading on Linux.
16160 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16161   if (!Subtarget.isTargetLinux())
16162     return TargetLowering::insertSSPDeclarations(M);
16163 }
16164 
16165 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16166                                      bool ForCodeSize) const {
16167   if (!VT.isSimple() || !Subtarget.hasVSX())
16168     return false;
16169 
16170   switch(VT.getSimpleVT().SimpleTy) {
16171   default:
16172     // For FP types that are currently not supported by PPC backend, return
16173     // false. Examples: f16, f80.
16174     return false;
16175   case MVT::f32:
16176   case MVT::f64:
16177   case MVT::ppcf128:
16178     return Imm.isPosZero();
16179   }
16180 }
16181 
16182 // For vector shift operation op, fold
16183 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16184 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16185                                   SelectionDAG &DAG) {
16186   SDValue N0 = N->getOperand(0);
16187   SDValue N1 = N->getOperand(1);
16188   EVT VT = N0.getValueType();
16189   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16190   unsigned Opcode = N->getOpcode();
16191   unsigned TargetOpcode;
16192 
16193   switch (Opcode) {
16194   default:
16195     llvm_unreachable("Unexpected shift operation");
16196   case ISD::SHL:
16197     TargetOpcode = PPCISD::SHL;
16198     break;
16199   case ISD::SRL:
16200     TargetOpcode = PPCISD::SRL;
16201     break;
16202   case ISD::SRA:
16203     TargetOpcode = PPCISD::SRA;
16204     break;
16205   }
16206 
16207   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16208       N1->getOpcode() == ISD::AND)
16209     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16210       if (Mask->getZExtValue() == OpSizeInBits - 1)
16211         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16212 
16213   return SDValue();
16214 }
16215 
16216 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16217   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16218     return Value;
16219 
16220   SDValue N0 = N->getOperand(0);
16221   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16222   if (!Subtarget.isISA3_0() ||
16223       N0.getOpcode() != ISD::SIGN_EXTEND ||
16224       N0.getOperand(0).getValueType() != MVT::i32 ||
16225       CN1 == nullptr || N->getValueType(0) != MVT::i64)
16226     return SDValue();
16227 
16228   // We can't save an operation here if the value is already extended, and
16229   // the existing shift is easier to combine.
16230   SDValue ExtsSrc = N0.getOperand(0);
16231   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16232       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16233     return SDValue();
16234 
16235   SDLoc DL(N0);
16236   SDValue ShiftBy = SDValue(CN1, 0);
16237   // We want the shift amount to be i32 on the extswli, but the shift could
16238   // have an i64.
16239   if (ShiftBy.getValueType() == MVT::i64)
16240     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16241 
16242   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16243                          ShiftBy);
16244 }
16245 
16246 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16247   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16248     return Value;
16249 
16250   return SDValue();
16251 }
16252 
16253 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16254   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16255     return Value;
16256 
16257   return SDValue();
16258 }
16259 
16260 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16261 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16262 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16263 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16264 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16265                                  const PPCSubtarget &Subtarget) {
16266   if (!Subtarget.isPPC64())
16267     return SDValue();
16268 
16269   SDValue LHS = N->getOperand(0);
16270   SDValue RHS = N->getOperand(1);
16271 
16272   auto isZextOfCompareWithConstant = [](SDValue Op) {
16273     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16274         Op.getValueType() != MVT::i64)
16275       return false;
16276 
16277     SDValue Cmp = Op.getOperand(0);
16278     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16279         Cmp.getOperand(0).getValueType() != MVT::i64)
16280       return false;
16281 
16282     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16283       int64_t NegConstant = 0 - Constant->getSExtValue();
16284       // Due to the limitations of the addi instruction,
16285       // -C is required to be [-32768, 32767].
16286       return isInt<16>(NegConstant);
16287     }
16288 
16289     return false;
16290   };
16291 
16292   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16293   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16294 
16295   // If there is a pattern, canonicalize a zext operand to the RHS.
16296   if (LHSHasPattern && !RHSHasPattern)
16297     std::swap(LHS, RHS);
16298   else if (!LHSHasPattern && !RHSHasPattern)
16299     return SDValue();
16300 
16301   SDLoc DL(N);
16302   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16303   SDValue Cmp = RHS.getOperand(0);
16304   SDValue Z = Cmp.getOperand(0);
16305   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16306 
16307   assert(Constant && "Constant Should not be a null pointer.");
16308   int64_t NegConstant = 0 - Constant->getSExtValue();
16309 
16310   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16311   default: break;
16312   case ISD::SETNE: {
16313     //                                 when C == 0
16314     //                             --> addze X, (addic Z, -1).carry
16315     //                            /
16316     // add X, (zext(setne Z, C))--
16317     //                            \    when -32768 <= -C <= 32767 && C != 0
16318     //                             --> addze X, (addic (addi Z, -C), -1).carry
16319     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16320                               DAG.getConstant(NegConstant, DL, MVT::i64));
16321     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16322     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16323                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16324     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16325                        SDValue(Addc.getNode(), 1));
16326     }
16327   case ISD::SETEQ: {
16328     //                                 when C == 0
16329     //                             --> addze X, (subfic Z, 0).carry
16330     //                            /
16331     // add X, (zext(sete  Z, C))--
16332     //                            \    when -32768 <= -C <= 32767 && C != 0
16333     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16334     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16335                               DAG.getConstant(NegConstant, DL, MVT::i64));
16336     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16337     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16338                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16339     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16340                        SDValue(Subc.getNode(), 1));
16341     }
16342   }
16343 
16344   return SDValue();
16345 }
16346 
16347 // Transform
16348 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16349 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16350 // In this case both C1 and C2 must be known constants.
16351 // C1+C2 must fit into a 34 bit signed integer.
16352 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16353                                           const PPCSubtarget &Subtarget) {
16354   if (!Subtarget.isUsingPCRelativeCalls())
16355     return SDValue();
16356 
16357   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16358   // If we find that node try to cast the Global Address and the Constant.
16359   SDValue LHS = N->getOperand(0);
16360   SDValue RHS = N->getOperand(1);
16361 
16362   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16363     std::swap(LHS, RHS);
16364 
16365   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16366     return SDValue();
16367 
16368   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16369   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16370   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16371 
16372   // Check that both casts succeeded.
16373   if (!GSDN || !ConstNode)
16374     return SDValue();
16375 
16376   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16377   SDLoc DL(GSDN);
16378 
16379   // The signed int offset needs to fit in 34 bits.
16380   if (!isInt<34>(NewOffset))
16381     return SDValue();
16382 
16383   // The new global address is a copy of the old global address except
16384   // that it has the updated Offset.
16385   SDValue GA =
16386       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16387                                  NewOffset, GSDN->getTargetFlags());
16388   SDValue MatPCRel =
16389       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16390   return MatPCRel;
16391 }
16392 
16393 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16394   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16395     return Value;
16396 
16397   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16398     return Value;
16399 
16400   return SDValue();
16401 }
16402 
16403 // Detect TRUNCATE operations on bitcasts of float128 values.
16404 // What we are looking for here is the situtation where we extract a subset
16405 // of bits from a 128 bit float.
16406 // This can be of two forms:
16407 // 1) BITCAST of f128 feeding TRUNCATE
16408 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16409 // The reason this is required is because we do not have a legal i128 type
16410 // and so we want to prevent having to store the f128 and then reload part
16411 // of it.
16412 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16413                                            DAGCombinerInfo &DCI) const {
16414   // If we are using CRBits then try that first.
16415   if (Subtarget.useCRBits()) {
16416     // Check if CRBits did anything and return that if it did.
16417     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16418       return CRTruncValue;
16419   }
16420 
16421   SDLoc dl(N);
16422   SDValue Op0 = N->getOperand(0);
16423 
16424   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16425   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16426     EVT VT = N->getValueType(0);
16427     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16428       return SDValue();
16429     SDValue Sub = Op0.getOperand(0);
16430     if (Sub.getOpcode() == ISD::SUB) {
16431       SDValue SubOp0 = Sub.getOperand(0);
16432       SDValue SubOp1 = Sub.getOperand(1);
16433       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16434           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16435         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16436                                SubOp1.getOperand(0),
16437                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16438       }
16439     }
16440   }
16441 
16442   // Looking for a truncate of i128 to i64.
16443   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16444     return SDValue();
16445 
16446   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16447 
16448   // SRL feeding TRUNCATE.
16449   if (Op0.getOpcode() == ISD::SRL) {
16450     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16451     // The right shift has to be by 64 bits.
16452     if (!ConstNode || ConstNode->getZExtValue() != 64)
16453       return SDValue();
16454 
16455     // Switch the element number to extract.
16456     EltToExtract = EltToExtract ? 0 : 1;
16457     // Update Op0 past the SRL.
16458     Op0 = Op0.getOperand(0);
16459   }
16460 
16461   // BITCAST feeding a TRUNCATE possibly via SRL.
16462   if (Op0.getOpcode() == ISD::BITCAST &&
16463       Op0.getValueType() == MVT::i128 &&
16464       Op0.getOperand(0).getValueType() == MVT::f128) {
16465     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16466     return DCI.DAG.getNode(
16467         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16468         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16469   }
16470   return SDValue();
16471 }
16472 
16473 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16474   SelectionDAG &DAG = DCI.DAG;
16475 
16476   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16477   if (!ConstOpOrElement)
16478     return SDValue();
16479 
16480   // An imul is usually smaller than the alternative sequence for legal type.
16481   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16482       isOperationLegal(ISD::MUL, N->getValueType(0)))
16483     return SDValue();
16484 
16485   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16486     switch (this->Subtarget.getCPUDirective()) {
16487     default:
16488       // TODO: enhance the condition for subtarget before pwr8
16489       return false;
16490     case PPC::DIR_PWR8:
16491       //  type        mul     add    shl
16492       // scalar        4       1      1
16493       // vector        7       2      2
16494       return true;
16495     case PPC::DIR_PWR9:
16496     case PPC::DIR_PWR10:
16497     case PPC::DIR_PWR_FUTURE:
16498       //  type        mul     add    shl
16499       // scalar        5       2      2
16500       // vector        7       2      2
16501 
16502       // The cycle RATIO of related operations are showed as a table above.
16503       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16504       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16505       // are 4, it is always profitable; but for 3 instrs patterns
16506       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16507       // So we should only do it for vector type.
16508       return IsAddOne && IsNeg ? VT.isVector() : true;
16509     }
16510   };
16511 
16512   EVT VT = N->getValueType(0);
16513   SDLoc DL(N);
16514 
16515   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16516   bool IsNeg = MulAmt.isNegative();
16517   APInt MulAmtAbs = MulAmt.abs();
16518 
16519   if ((MulAmtAbs - 1).isPowerOf2()) {
16520     // (mul x, 2^N + 1) => (add (shl x, N), x)
16521     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16522 
16523     if (!IsProfitable(IsNeg, true, VT))
16524       return SDValue();
16525 
16526     SDValue Op0 = N->getOperand(0);
16527     SDValue Op1 =
16528         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16529                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16530     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16531 
16532     if (!IsNeg)
16533       return Res;
16534 
16535     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16536   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16537     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16538     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16539 
16540     if (!IsProfitable(IsNeg, false, VT))
16541       return SDValue();
16542 
16543     SDValue Op0 = N->getOperand(0);
16544     SDValue Op1 =
16545         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16546                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16547 
16548     if (!IsNeg)
16549       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16550     else
16551       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16552 
16553   } else {
16554     return SDValue();
16555   }
16556 }
16557 
16558 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16559 // in combiner since we need to check SD flags and other subtarget features.
16560 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16561                                           DAGCombinerInfo &DCI) const {
16562   SDValue N0 = N->getOperand(0);
16563   SDValue N1 = N->getOperand(1);
16564   SDValue N2 = N->getOperand(2);
16565   SDNodeFlags Flags = N->getFlags();
16566   EVT VT = N->getValueType(0);
16567   SelectionDAG &DAG = DCI.DAG;
16568   const TargetOptions &Options = getTargetMachine().Options;
16569   unsigned Opc = N->getOpcode();
16570   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16571   bool LegalOps = !DCI.isBeforeLegalizeOps();
16572   SDLoc Loc(N);
16573 
16574   // TODO: QPX subtarget is deprecated. No transformation here.
16575   if (Subtarget.hasQPX() || !isOperationLegal(ISD::FMA, VT))
16576     return SDValue();
16577 
16578   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16579   // since (fnmsub a b c)=-0 while c-ab=+0.
16580   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16581     return SDValue();
16582 
16583   // (fma (fneg a) b c) => (fnmsub a b c)
16584   // (fnmsub (fneg a) b c) => (fma a b c)
16585   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16586     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16587 
16588   // (fma a (fneg b) c) => (fnmsub a b c)
16589   // (fnmsub a (fneg b) c) => (fma a b c)
16590   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16591     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16592 
16593   return SDValue();
16594 }
16595 
16596 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16597   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16598   if (!Subtarget.is64BitELFABI())
16599     return false;
16600 
16601   // If not a tail call then no need to proceed.
16602   if (!CI->isTailCall())
16603     return false;
16604 
16605   // If sibling calls have been disabled and tail-calls aren't guaranteed
16606   // there is no reason to duplicate.
16607   auto &TM = getTargetMachine();
16608   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16609     return false;
16610 
16611   // Can't tail call a function called indirectly, or if it has variadic args.
16612   const Function *Callee = CI->getCalledFunction();
16613   if (!Callee || Callee->isVarArg())
16614     return false;
16615 
16616   // Make sure the callee and caller calling conventions are eligible for tco.
16617   const Function *Caller = CI->getParent()->getParent();
16618   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16619                                            CI->getCallingConv()))
16620       return false;
16621 
16622   // If the function is local then we have a good chance at tail-calling it
16623   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16624 }
16625 
16626 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16627   if (!Subtarget.hasVSX())
16628     return false;
16629   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16630     return true;
16631   return VT == MVT::f32 || VT == MVT::f64 ||
16632     VT == MVT::v4f32 || VT == MVT::v2f64;
16633 }
16634 
16635 bool PPCTargetLowering::
16636 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16637   const Value *Mask = AndI.getOperand(1);
16638   // If the mask is suitable for andi. or andis. we should sink the and.
16639   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16640     // Can't handle constants wider than 64-bits.
16641     if (CI->getBitWidth() > 64)
16642       return false;
16643     int64_t ConstVal = CI->getZExtValue();
16644     return isUInt<16>(ConstVal) ||
16645       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16646   }
16647 
16648   // For non-constant masks, we can always use the record-form and.
16649   return true;
16650 }
16651 
16652 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16653 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16654 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16655 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16656 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16657 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16658   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16659   assert(Subtarget.hasP9Altivec() &&
16660          "Only combine this when P9 altivec supported!");
16661   EVT VT = N->getValueType(0);
16662   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16663     return SDValue();
16664 
16665   SelectionDAG &DAG = DCI.DAG;
16666   SDLoc dl(N);
16667   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16668     // Even for signed integers, if it's known to be positive (as signed
16669     // integer) due to zero-extended inputs.
16670     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16671     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16672     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16673          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16674         (SubOpcd1 == ISD::ZERO_EXTEND ||
16675          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16676       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16677                          N->getOperand(0)->getOperand(0),
16678                          N->getOperand(0)->getOperand(1),
16679                          DAG.getTargetConstant(0, dl, MVT::i32));
16680     }
16681 
16682     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16683     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16684         N->getOperand(0).hasOneUse()) {
16685       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16686                          N->getOperand(0)->getOperand(0),
16687                          N->getOperand(0)->getOperand(1),
16688                          DAG.getTargetConstant(1, dl, MVT::i32));
16689     }
16690   }
16691 
16692   return SDValue();
16693 }
16694 
16695 // For type v4i32/v8ii16/v16i8, transform
16696 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16697 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16698 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16699 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16700 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16701                                           DAGCombinerInfo &DCI) const {
16702   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16703   assert(Subtarget.hasP9Altivec() &&
16704          "Only combine this when P9 altivec supported!");
16705 
16706   SelectionDAG &DAG = DCI.DAG;
16707   SDLoc dl(N);
16708   SDValue Cond = N->getOperand(0);
16709   SDValue TrueOpnd = N->getOperand(1);
16710   SDValue FalseOpnd = N->getOperand(2);
16711   EVT VT = N->getOperand(1).getValueType();
16712 
16713   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16714       FalseOpnd.getOpcode() != ISD::SUB)
16715     return SDValue();
16716 
16717   // ABSD only available for type v4i32/v8i16/v16i8
16718   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16719     return SDValue();
16720 
16721   // At least to save one more dependent computation
16722   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16723     return SDValue();
16724 
16725   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16726 
16727   // Can only handle unsigned comparison here
16728   switch (CC) {
16729   default:
16730     return SDValue();
16731   case ISD::SETUGT:
16732   case ISD::SETUGE:
16733     break;
16734   case ISD::SETULT:
16735   case ISD::SETULE:
16736     std::swap(TrueOpnd, FalseOpnd);
16737     break;
16738   }
16739 
16740   SDValue CmpOpnd1 = Cond.getOperand(0);
16741   SDValue CmpOpnd2 = Cond.getOperand(1);
16742 
16743   // SETCC CmpOpnd1 CmpOpnd2 cond
16744   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16745   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16746   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16747       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16748       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16749       FalseOpnd.getOperand(1) == CmpOpnd1) {
16750     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16751                        CmpOpnd1, CmpOpnd2,
16752                        DAG.getTargetConstant(0, dl, MVT::i32));
16753   }
16754 
16755   return SDValue();
16756 }
16757