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, Align &MaxAlign, Align MaxMaxAlign) {
1393   if (MaxAlign == MaxMaxAlign)
1394     return;
1395   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1396     if (MaxMaxAlign >= 32 &&
1397         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1398       MaxAlign = Align(32);
1399     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1400              MaxAlign < 16)
1401       MaxAlign = Align(16);
1402   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1403     Align EltAlign;
1404     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1405     if (EltAlign > MaxAlign)
1406       MaxAlign = EltAlign;
1407   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1408     for (auto *EltTy : STy->elements()) {
1409       Align EltAlign;
1410       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1411       if (EltAlign > MaxAlign)
1412         MaxAlign = EltAlign;
1413       if (MaxAlign == MaxMaxAlign)
1414         break;
1415     }
1416   }
1417 }
1418 
1419 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1420 /// function arguments in the caller parameter area.
1421 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1422                                                   const DataLayout &DL) const {
1423   // 16byte and wider vectors are passed on 16byte boundary.
1424   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1425   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1426   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1427     getMaxByValAlign(Ty, Alignment, Subtarget.hasQPX() ? Align(32) : Align(16));
1428   return Alignment.value();
1429 }
1430 
1431 bool PPCTargetLowering::useSoftFloat() const {
1432   return Subtarget.useSoftFloat();
1433 }
1434 
1435 bool PPCTargetLowering::hasSPE() const {
1436   return Subtarget.hasSPE();
1437 }
1438 
1439 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1440   return VT.isScalarInteger();
1441 }
1442 
1443 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1444 /// type is cheaper than a multiply followed by a shift.
1445 /// This is true for words and doublewords on 64-bit PowerPC.
1446 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1447   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1448                               isOperationLegal(ISD::MULHU, Type)))
1449     return true;
1450   return TargetLowering::isMulhCheaperThanMulShift(Type);
1451 }
1452 
1453 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1454   switch ((PPCISD::NodeType)Opcode) {
1455   case PPCISD::FIRST_NUMBER:    break;
1456   case PPCISD::FSEL:            return "PPCISD::FSEL";
1457   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1458   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1459   case PPCISD::FCFID:           return "PPCISD::FCFID";
1460   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1461   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1462   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1463   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1464   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1465   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1466   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1467   case PPCISD::FP_TO_UINT_IN_VSR:
1468                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1469   case PPCISD::FP_TO_SINT_IN_VSR:
1470                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1471   case PPCISD::FRE:             return "PPCISD::FRE";
1472   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1473   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1474   case PPCISD::VPERM:           return "PPCISD::VPERM";
1475   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1476   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1477   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1478   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1479   case PPCISD::CMPB:            return "PPCISD::CMPB";
1480   case PPCISD::Hi:              return "PPCISD::Hi";
1481   case PPCISD::Lo:              return "PPCISD::Lo";
1482   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1483   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1484   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1485   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1486   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1487   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1488   case PPCISD::SRL:             return "PPCISD::SRL";
1489   case PPCISD::SRA:             return "PPCISD::SRA";
1490   case PPCISD::SHL:             return "PPCISD::SHL";
1491   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1492   case PPCISD::CALL:            return "PPCISD::CALL";
1493   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1494   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1495   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1496   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1497   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1498   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1499   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1500   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1501   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1502   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1503   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1504   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1505   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1506   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1507   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1508   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1509     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1510   case PPCISD::ANDI_rec_1_EQ_BIT:
1511     return "PPCISD::ANDI_rec_1_EQ_BIT";
1512   case PPCISD::ANDI_rec_1_GT_BIT:
1513     return "PPCISD::ANDI_rec_1_GT_BIT";
1514   case PPCISD::VCMP:            return "PPCISD::VCMP";
1515   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1516   case PPCISD::LBRX:            return "PPCISD::LBRX";
1517   case PPCISD::STBRX:           return "PPCISD::STBRX";
1518   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1519   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1520   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1521   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1522   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1523   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1524   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1525   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1526   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1527   case PPCISD::ST_VSR_SCAL_INT:
1528                                 return "PPCISD::ST_VSR_SCAL_INT";
1529   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1530   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1531   case PPCISD::BDZ:             return "PPCISD::BDZ";
1532   case PPCISD::MFFS:            return "PPCISD::MFFS";
1533   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1534   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1535   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1536   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1537   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1538   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1539   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1540   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1541   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1542   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1543   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1544   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1545   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1546   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1547   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1548   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1549   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1550   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1551   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1552   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1553   case PPCISD::SC:              return "PPCISD::SC";
1554   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1555   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1556   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1557   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1558   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1559   case PPCISD::VABSD:           return "PPCISD::VABSD";
1560   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1561   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1562   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1563   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1564   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1565   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1566   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1567   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1568   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1569   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1570   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1571   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1572   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1573   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1574   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1575   }
1576   return nullptr;
1577 }
1578 
1579 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1580                                           EVT VT) const {
1581   if (!VT.isVector())
1582     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1583 
1584   if (Subtarget.hasQPX())
1585     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1586 
1587   return VT.changeVectorElementTypeToInteger();
1588 }
1589 
1590 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1591   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1592   return true;
1593 }
1594 
1595 //===----------------------------------------------------------------------===//
1596 // Node matching predicates, for use by the tblgen matching code.
1597 //===----------------------------------------------------------------------===//
1598 
1599 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1600 static bool isFloatingPointZero(SDValue Op) {
1601   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1602     return CFP->getValueAPF().isZero();
1603   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1604     // Maybe this has already been legalized into the constant pool?
1605     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1606       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1607         return CFP->getValueAPF().isZero();
1608   }
1609   return false;
1610 }
1611 
1612 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1613 /// true if Op is undef or if it matches the specified value.
1614 static bool isConstantOrUndef(int Op, int Val) {
1615   return Op < 0 || Op == Val;
1616 }
1617 
1618 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1619 /// VPKUHUM instruction.
1620 /// The ShuffleKind distinguishes between big-endian operations with
1621 /// two different inputs (0), either-endian operations with two identical
1622 /// inputs (1), and little-endian operations with two different inputs (2).
1623 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1624 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1625                                SelectionDAG &DAG) {
1626   bool IsLE = DAG.getDataLayout().isLittleEndian();
1627   if (ShuffleKind == 0) {
1628     if (IsLE)
1629       return false;
1630     for (unsigned i = 0; i != 16; ++i)
1631       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1632         return false;
1633   } else if (ShuffleKind == 2) {
1634     if (!IsLE)
1635       return false;
1636     for (unsigned i = 0; i != 16; ++i)
1637       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1638         return false;
1639   } else if (ShuffleKind == 1) {
1640     unsigned j = IsLE ? 0 : 1;
1641     for (unsigned i = 0; i != 8; ++i)
1642       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1643           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1644         return false;
1645   }
1646   return true;
1647 }
1648 
1649 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1650 /// VPKUWUM instruction.
1651 /// The ShuffleKind distinguishes between big-endian operations with
1652 /// two different inputs (0), either-endian operations with two identical
1653 /// inputs (1), and little-endian operations with two different inputs (2).
1654 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1655 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1656                                SelectionDAG &DAG) {
1657   bool IsLE = DAG.getDataLayout().isLittleEndian();
1658   if (ShuffleKind == 0) {
1659     if (IsLE)
1660       return false;
1661     for (unsigned i = 0; i != 16; i += 2)
1662       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1663           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1664         return false;
1665   } else if (ShuffleKind == 2) {
1666     if (!IsLE)
1667       return false;
1668     for (unsigned i = 0; i != 16; i += 2)
1669       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1670           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1671         return false;
1672   } else if (ShuffleKind == 1) {
1673     unsigned j = IsLE ? 0 : 2;
1674     for (unsigned i = 0; i != 8; i += 2)
1675       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1676           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1677           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1678           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1679         return false;
1680   }
1681   return true;
1682 }
1683 
1684 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1685 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1686 /// current subtarget.
1687 ///
1688 /// The ShuffleKind distinguishes between big-endian operations with
1689 /// two different inputs (0), either-endian operations with two identical
1690 /// inputs (1), and little-endian operations with two different inputs (2).
1691 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1692 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1693                                SelectionDAG &DAG) {
1694   const PPCSubtarget& Subtarget =
1695       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1696   if (!Subtarget.hasP8Vector())
1697     return false;
1698 
1699   bool IsLE = DAG.getDataLayout().isLittleEndian();
1700   if (ShuffleKind == 0) {
1701     if (IsLE)
1702       return false;
1703     for (unsigned i = 0; i != 16; i += 4)
1704       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1705           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1706           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1707           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1708         return false;
1709   } else if (ShuffleKind == 2) {
1710     if (!IsLE)
1711       return false;
1712     for (unsigned i = 0; i != 16; i += 4)
1713       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1714           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1715           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1716           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1717         return false;
1718   } else if (ShuffleKind == 1) {
1719     unsigned j = IsLE ? 0 : 4;
1720     for (unsigned i = 0; i != 8; i += 4)
1721       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1722           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1723           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1724           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1725           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1726           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1727           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1728           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1729         return false;
1730   }
1731   return true;
1732 }
1733 
1734 /// isVMerge - Common function, used to match vmrg* shuffles.
1735 ///
1736 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1737                      unsigned LHSStart, unsigned RHSStart) {
1738   if (N->getValueType(0) != MVT::v16i8)
1739     return false;
1740   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1741          "Unsupported merge size!");
1742 
1743   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1744     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1745       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1746                              LHSStart+j+i*UnitSize) ||
1747           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1748                              RHSStart+j+i*UnitSize))
1749         return false;
1750     }
1751   return true;
1752 }
1753 
1754 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1755 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1756 /// The ShuffleKind distinguishes between big-endian merges with two
1757 /// different inputs (0), either-endian merges with two identical inputs (1),
1758 /// and little-endian merges with two different inputs (2).  For the latter,
1759 /// the input operands are swapped (see PPCInstrAltivec.td).
1760 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1761                              unsigned ShuffleKind, SelectionDAG &DAG) {
1762   if (DAG.getDataLayout().isLittleEndian()) {
1763     if (ShuffleKind == 1) // unary
1764       return isVMerge(N, UnitSize, 0, 0);
1765     else if (ShuffleKind == 2) // swapped
1766       return isVMerge(N, UnitSize, 0, 16);
1767     else
1768       return false;
1769   } else {
1770     if (ShuffleKind == 1) // unary
1771       return isVMerge(N, UnitSize, 8, 8);
1772     else if (ShuffleKind == 0) // normal
1773       return isVMerge(N, UnitSize, 8, 24);
1774     else
1775       return false;
1776   }
1777 }
1778 
1779 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1780 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1781 /// The ShuffleKind distinguishes between big-endian merges with two
1782 /// different inputs (0), either-endian merges with two identical inputs (1),
1783 /// and little-endian merges with two different inputs (2).  For the latter,
1784 /// the input operands are swapped (see PPCInstrAltivec.td).
1785 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1786                              unsigned ShuffleKind, SelectionDAG &DAG) {
1787   if (DAG.getDataLayout().isLittleEndian()) {
1788     if (ShuffleKind == 1) // unary
1789       return isVMerge(N, UnitSize, 8, 8);
1790     else if (ShuffleKind == 2) // swapped
1791       return isVMerge(N, UnitSize, 8, 24);
1792     else
1793       return false;
1794   } else {
1795     if (ShuffleKind == 1) // unary
1796       return isVMerge(N, UnitSize, 0, 0);
1797     else if (ShuffleKind == 0) // normal
1798       return isVMerge(N, UnitSize, 0, 16);
1799     else
1800       return false;
1801   }
1802 }
1803 
1804 /**
1805  * Common function used to match vmrgew and vmrgow shuffles
1806  *
1807  * The indexOffset determines whether to look for even or odd words in
1808  * the shuffle mask. This is based on the of the endianness of the target
1809  * machine.
1810  *   - Little Endian:
1811  *     - Use offset of 0 to check for odd elements
1812  *     - Use offset of 4 to check for even elements
1813  *   - Big Endian:
1814  *     - Use offset of 0 to check for even elements
1815  *     - Use offset of 4 to check for odd elements
1816  * A detailed description of the vector element ordering for little endian and
1817  * big endian can be found at
1818  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1819  * Targeting your applications - what little endian and big endian IBM XL C/C++
1820  * compiler differences mean to you
1821  *
1822  * The mask to the shuffle vector instruction specifies the indices of the
1823  * elements from the two input vectors to place in the result. The elements are
1824  * numbered in array-access order, starting with the first vector. These vectors
1825  * are always of type v16i8, thus each vector will contain 16 elements of size
1826  * 8. More info on the shuffle vector can be found in the
1827  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1828  * Language Reference.
1829  *
1830  * The RHSStartValue indicates whether the same input vectors are used (unary)
1831  * or two different input vectors are used, based on the following:
1832  *   - If the instruction uses the same vector for both inputs, the range of the
1833  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1834  *     be 0.
1835  *   - If the instruction has two different vectors then the range of the
1836  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1837  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1838  *     to 31 specify elements in the second vector).
1839  *
1840  * \param[in] N The shuffle vector SD Node to analyze
1841  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1842  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1843  * vector to the shuffle_vector instruction
1844  * \return true iff this shuffle vector represents an even or odd word merge
1845  */
1846 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1847                      unsigned RHSStartValue) {
1848   if (N->getValueType(0) != MVT::v16i8)
1849     return false;
1850 
1851   for (unsigned i = 0; i < 2; ++i)
1852     for (unsigned j = 0; j < 4; ++j)
1853       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1854                              i*RHSStartValue+j+IndexOffset) ||
1855           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1856                              i*RHSStartValue+j+IndexOffset+8))
1857         return false;
1858   return true;
1859 }
1860 
1861 /**
1862  * Determine if the specified shuffle mask is suitable for the vmrgew or
1863  * vmrgow instructions.
1864  *
1865  * \param[in] N The shuffle vector SD Node to analyze
1866  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1867  * \param[in] ShuffleKind Identify the type of merge:
1868  *   - 0 = big-endian merge with two different inputs;
1869  *   - 1 = either-endian merge with two identical inputs;
1870  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1871  *     little-endian merges).
1872  * \param[in] DAG The current SelectionDAG
1873  * \return true iff this shuffle mask
1874  */
1875 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1876                               unsigned ShuffleKind, SelectionDAG &DAG) {
1877   if (DAG.getDataLayout().isLittleEndian()) {
1878     unsigned indexOffset = CheckEven ? 4 : 0;
1879     if (ShuffleKind == 1) // Unary
1880       return isVMerge(N, indexOffset, 0);
1881     else if (ShuffleKind == 2) // swapped
1882       return isVMerge(N, indexOffset, 16);
1883     else
1884       return false;
1885   }
1886   else {
1887     unsigned indexOffset = CheckEven ? 0 : 4;
1888     if (ShuffleKind == 1) // Unary
1889       return isVMerge(N, indexOffset, 0);
1890     else if (ShuffleKind == 0) // Normal
1891       return isVMerge(N, indexOffset, 16);
1892     else
1893       return false;
1894   }
1895   return false;
1896 }
1897 
1898 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1899 /// amount, otherwise return -1.
1900 /// The ShuffleKind distinguishes between big-endian operations with two
1901 /// different inputs (0), either-endian operations with two identical inputs
1902 /// (1), and little-endian operations with two different inputs (2).  For the
1903 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1904 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1905                              SelectionDAG &DAG) {
1906   if (N->getValueType(0) != MVT::v16i8)
1907     return -1;
1908 
1909   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1910 
1911   // Find the first non-undef value in the shuffle mask.
1912   unsigned i;
1913   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1914     /*search*/;
1915 
1916   if (i == 16) return -1;  // all undef.
1917 
1918   // Otherwise, check to see if the rest of the elements are consecutively
1919   // numbered from this value.
1920   unsigned ShiftAmt = SVOp->getMaskElt(i);
1921   if (ShiftAmt < i) return -1;
1922 
1923   ShiftAmt -= i;
1924   bool isLE = DAG.getDataLayout().isLittleEndian();
1925 
1926   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1927     // Check the rest of the elements to see if they are consecutive.
1928     for (++i; i != 16; ++i)
1929       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1930         return -1;
1931   } else if (ShuffleKind == 1) {
1932     // Check the rest of the elements to see if they are consecutive.
1933     for (++i; i != 16; ++i)
1934       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1935         return -1;
1936   } else
1937     return -1;
1938 
1939   if (isLE)
1940     ShiftAmt = 16 - ShiftAmt;
1941 
1942   return ShiftAmt;
1943 }
1944 
1945 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1946 /// specifies a splat of a single element that is suitable for input to
1947 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1948 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1949   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1950          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1951 
1952   // The consecutive indices need to specify an element, not part of two
1953   // different elements.  So abandon ship early if this isn't the case.
1954   if (N->getMaskElt(0) % EltSize != 0)
1955     return false;
1956 
1957   // This is a splat operation if each element of the permute is the same, and
1958   // if the value doesn't reference the second vector.
1959   unsigned ElementBase = N->getMaskElt(0);
1960 
1961   // FIXME: Handle UNDEF elements too!
1962   if (ElementBase >= 16)
1963     return false;
1964 
1965   // Check that the indices are consecutive, in the case of a multi-byte element
1966   // splatted with a v16i8 mask.
1967   for (unsigned i = 1; i != EltSize; ++i)
1968     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1969       return false;
1970 
1971   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1972     if (N->getMaskElt(i) < 0) continue;
1973     for (unsigned j = 0; j != EltSize; ++j)
1974       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1975         return false;
1976   }
1977   return true;
1978 }
1979 
1980 /// Check that the mask is shuffling N byte elements. Within each N byte
1981 /// element of the mask, the indices could be either in increasing or
1982 /// decreasing order as long as they are consecutive.
1983 /// \param[in] N the shuffle vector SD Node to analyze
1984 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1985 /// Word/DoubleWord/QuadWord).
1986 /// \param[in] StepLen the delta indices number among the N byte element, if
1987 /// the mask is in increasing/decreasing order then it is 1/-1.
1988 /// \return true iff the mask is shuffling N byte elements.
1989 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1990                                    int StepLen) {
1991   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1992          "Unexpected element width.");
1993   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1994 
1995   unsigned NumOfElem = 16 / Width;
1996   unsigned MaskVal[16]; //  Width is never greater than 16
1997   for (unsigned i = 0; i < NumOfElem; ++i) {
1998     MaskVal[0] = N->getMaskElt(i * Width);
1999     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2000       return false;
2001     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2002       return false;
2003     }
2004 
2005     for (unsigned int j = 1; j < Width; ++j) {
2006       MaskVal[j] = N->getMaskElt(i * Width + j);
2007       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2008         return false;
2009       }
2010     }
2011   }
2012 
2013   return true;
2014 }
2015 
2016 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2017                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2018   if (!isNByteElemShuffleMask(N, 4, 1))
2019     return false;
2020 
2021   // Now we look at mask elements 0,4,8,12
2022   unsigned M0 = N->getMaskElt(0) / 4;
2023   unsigned M1 = N->getMaskElt(4) / 4;
2024   unsigned M2 = N->getMaskElt(8) / 4;
2025   unsigned M3 = N->getMaskElt(12) / 4;
2026   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2027   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2028 
2029   // Below, let H and L be arbitrary elements of the shuffle mask
2030   // where H is in the range [4,7] and L is in the range [0,3].
2031   // H, 1, 2, 3 or L, 5, 6, 7
2032   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2033       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2034     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2035     InsertAtByte = IsLE ? 12 : 0;
2036     Swap = M0 < 4;
2037     return true;
2038   }
2039   // 0, H, 2, 3 or 4, L, 6, 7
2040   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2041       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2042     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2043     InsertAtByte = IsLE ? 8 : 4;
2044     Swap = M1 < 4;
2045     return true;
2046   }
2047   // 0, 1, H, 3 or 4, 5, L, 7
2048   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2049       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2050     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2051     InsertAtByte = IsLE ? 4 : 8;
2052     Swap = M2 < 4;
2053     return true;
2054   }
2055   // 0, 1, 2, H or 4, 5, 6, L
2056   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2057       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2058     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2059     InsertAtByte = IsLE ? 0 : 12;
2060     Swap = M3 < 4;
2061     return true;
2062   }
2063 
2064   // If both vector operands for the shuffle are the same vector, the mask will
2065   // contain only elements from the first one and the second one will be undef.
2066   if (N->getOperand(1).isUndef()) {
2067     ShiftElts = 0;
2068     Swap = true;
2069     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2070     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2071       InsertAtByte = IsLE ? 12 : 0;
2072       return true;
2073     }
2074     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2075       InsertAtByte = IsLE ? 8 : 4;
2076       return true;
2077     }
2078     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2079       InsertAtByte = IsLE ? 4 : 8;
2080       return true;
2081     }
2082     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2083       InsertAtByte = IsLE ? 0 : 12;
2084       return true;
2085     }
2086   }
2087 
2088   return false;
2089 }
2090 
2091 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2092                                bool &Swap, bool IsLE) {
2093   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2094   // Ensure each byte index of the word is consecutive.
2095   if (!isNByteElemShuffleMask(N, 4, 1))
2096     return false;
2097 
2098   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2099   unsigned M0 = N->getMaskElt(0) / 4;
2100   unsigned M1 = N->getMaskElt(4) / 4;
2101   unsigned M2 = N->getMaskElt(8) / 4;
2102   unsigned M3 = N->getMaskElt(12) / 4;
2103 
2104   // If both vector operands for the shuffle are the same vector, the mask will
2105   // contain only elements from the first one and the second one will be undef.
2106   if (N->getOperand(1).isUndef()) {
2107     assert(M0 < 4 && "Indexing into an undef vector?");
2108     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2109       return false;
2110 
2111     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2112     Swap = false;
2113     return true;
2114   }
2115 
2116   // Ensure each word index of the ShuffleVector Mask is consecutive.
2117   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2118     return false;
2119 
2120   if (IsLE) {
2121     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2122       // Input vectors don't need to be swapped if the leading element
2123       // of the result is one of the 3 left elements of the second vector
2124       // (or if there is no shift to be done at all).
2125       Swap = false;
2126       ShiftElts = (8 - M0) % 8;
2127     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2128       // Input vectors need to be swapped if the leading element
2129       // of the result is one of the 3 left elements of the first vector
2130       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2131       Swap = true;
2132       ShiftElts = (4 - M0) % 4;
2133     }
2134 
2135     return true;
2136   } else {                                          // BE
2137     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2138       // Input vectors don't need to be swapped if the leading element
2139       // of the result is one of the 4 elements of the first vector.
2140       Swap = false;
2141       ShiftElts = M0;
2142     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2143       // Input vectors need to be swapped if the leading element
2144       // of the result is one of the 4 elements of the right vector.
2145       Swap = true;
2146       ShiftElts = M0 - 4;
2147     }
2148 
2149     return true;
2150   }
2151 }
2152 
2153 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2154   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2155 
2156   if (!isNByteElemShuffleMask(N, Width, -1))
2157     return false;
2158 
2159   for (int i = 0; i < 16; i += Width)
2160     if (N->getMaskElt(i) != i + Width - 1)
2161       return false;
2162 
2163   return true;
2164 }
2165 
2166 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2167   return isXXBRShuffleMaskHelper(N, 2);
2168 }
2169 
2170 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2171   return isXXBRShuffleMaskHelper(N, 4);
2172 }
2173 
2174 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2175   return isXXBRShuffleMaskHelper(N, 8);
2176 }
2177 
2178 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2179   return isXXBRShuffleMaskHelper(N, 16);
2180 }
2181 
2182 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2183 /// if the inputs to the instruction should be swapped and set \p DM to the
2184 /// value for the immediate.
2185 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2186 /// AND element 0 of the result comes from the first input (LE) or second input
2187 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2188 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2189 /// mask.
2190 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2191                                bool &Swap, bool IsLE) {
2192   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2193 
2194   // Ensure each byte index of the double word is consecutive.
2195   if (!isNByteElemShuffleMask(N, 8, 1))
2196     return false;
2197 
2198   unsigned M0 = N->getMaskElt(0) / 8;
2199   unsigned M1 = N->getMaskElt(8) / 8;
2200   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2201 
2202   // If both vector operands for the shuffle are the same vector, the mask will
2203   // contain only elements from the first one and the second one will be undef.
2204   if (N->getOperand(1).isUndef()) {
2205     if ((M0 | M1) < 2) {
2206       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2207       Swap = false;
2208       return true;
2209     } else
2210       return false;
2211   }
2212 
2213   if (IsLE) {
2214     if (M0 > 1 && M1 < 2) {
2215       Swap = false;
2216     } else if (M0 < 2 && M1 > 1) {
2217       M0 = (M0 + 2) % 4;
2218       M1 = (M1 + 2) % 4;
2219       Swap = true;
2220     } else
2221       return false;
2222 
2223     // Note: if control flow comes here that means Swap is already set above
2224     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2225     return true;
2226   } else { // BE
2227     if (M0 < 2 && M1 > 1) {
2228       Swap = false;
2229     } else if (M0 > 1 && M1 < 2) {
2230       M0 = (M0 + 2) % 4;
2231       M1 = (M1 + 2) % 4;
2232       Swap = true;
2233     } else
2234       return false;
2235 
2236     // Note: if control flow comes here that means Swap is already set above
2237     DM = (M0 << 1) + (M1 & 1);
2238     return true;
2239   }
2240 }
2241 
2242 
2243 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2244 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2245 /// elements are counted from the left of the vector register).
2246 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2247                                          SelectionDAG &DAG) {
2248   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2249   assert(isSplatShuffleMask(SVOp, EltSize));
2250   if (DAG.getDataLayout().isLittleEndian())
2251     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2252   else
2253     return SVOp->getMaskElt(0) / EltSize;
2254 }
2255 
2256 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2257 /// by using a vspltis[bhw] instruction of the specified element size, return
2258 /// the constant being splatted.  The ByteSize field indicates the number of
2259 /// bytes of each element [124] -> [bhw].
2260 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2261   SDValue OpVal(nullptr, 0);
2262 
2263   // If ByteSize of the splat is bigger than the element size of the
2264   // build_vector, then we have a case where we are checking for a splat where
2265   // multiple elements of the buildvector are folded together into a single
2266   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2267   unsigned EltSize = 16/N->getNumOperands();
2268   if (EltSize < ByteSize) {
2269     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2270     SDValue UniquedVals[4];
2271     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2272 
2273     // See if all of the elements in the buildvector agree across.
2274     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2275       if (N->getOperand(i).isUndef()) continue;
2276       // If the element isn't a constant, bail fully out.
2277       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2278 
2279       if (!UniquedVals[i&(Multiple-1)].getNode())
2280         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2281       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2282         return SDValue();  // no match.
2283     }
2284 
2285     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2286     // either constant or undef values that are identical for each chunk.  See
2287     // if these chunks can form into a larger vspltis*.
2288 
2289     // Check to see if all of the leading entries are either 0 or -1.  If
2290     // neither, then this won't fit into the immediate field.
2291     bool LeadingZero = true;
2292     bool LeadingOnes = true;
2293     for (unsigned i = 0; i != Multiple-1; ++i) {
2294       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2295 
2296       LeadingZero &= isNullConstant(UniquedVals[i]);
2297       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2298     }
2299     // Finally, check the least significant entry.
2300     if (LeadingZero) {
2301       if (!UniquedVals[Multiple-1].getNode())
2302         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2303       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2304       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2305         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2306     }
2307     if (LeadingOnes) {
2308       if (!UniquedVals[Multiple-1].getNode())
2309         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2310       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2311       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2312         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2313     }
2314 
2315     return SDValue();
2316   }
2317 
2318   // Check to see if this buildvec has a single non-undef value in its elements.
2319   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2320     if (N->getOperand(i).isUndef()) continue;
2321     if (!OpVal.getNode())
2322       OpVal = N->getOperand(i);
2323     else if (OpVal != N->getOperand(i))
2324       return SDValue();
2325   }
2326 
2327   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2328 
2329   unsigned ValSizeInBytes = EltSize;
2330   uint64_t Value = 0;
2331   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2332     Value = CN->getZExtValue();
2333   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2334     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2335     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2336   }
2337 
2338   // If the splat value is larger than the element value, then we can never do
2339   // this splat.  The only case that we could fit the replicated bits into our
2340   // immediate field for would be zero, and we prefer to use vxor for it.
2341   if (ValSizeInBytes < ByteSize) return SDValue();
2342 
2343   // If the element value is larger than the splat value, check if it consists
2344   // of a repeated bit pattern of size ByteSize.
2345   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2346     return SDValue();
2347 
2348   // Properly sign extend the value.
2349   int MaskVal = SignExtend32(Value, ByteSize * 8);
2350 
2351   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2352   if (MaskVal == 0) return SDValue();
2353 
2354   // Finally, if this value fits in a 5 bit sext field, return it
2355   if (SignExtend32<5>(MaskVal) == MaskVal)
2356     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2357   return SDValue();
2358 }
2359 
2360 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2361 /// amount, otherwise return -1.
2362 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2363   EVT VT = N->getValueType(0);
2364   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2365     return -1;
2366 
2367   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2368 
2369   // Find the first non-undef value in the shuffle mask.
2370   unsigned i;
2371   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2372     /*search*/;
2373 
2374   if (i == 4) return -1;  // all undef.
2375 
2376   // Otherwise, check to see if the rest of the elements are consecutively
2377   // numbered from this value.
2378   unsigned ShiftAmt = SVOp->getMaskElt(i);
2379   if (ShiftAmt < i) return -1;
2380   ShiftAmt -= i;
2381 
2382   // Check the rest of the elements to see if they are consecutive.
2383   for (++i; i != 4; ++i)
2384     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2385       return -1;
2386 
2387   return ShiftAmt;
2388 }
2389 
2390 //===----------------------------------------------------------------------===//
2391 //  Addressing Mode Selection
2392 //===----------------------------------------------------------------------===//
2393 
2394 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2395 /// or 64-bit immediate, and if the value can be accurately represented as a
2396 /// sign extension from a 16-bit value.  If so, this returns true and the
2397 /// immediate.
2398 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2399   if (!isa<ConstantSDNode>(N))
2400     return false;
2401 
2402   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2403   if (N->getValueType(0) == MVT::i32)
2404     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2405   else
2406     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2407 }
2408 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2409   return isIntS16Immediate(Op.getNode(), Imm);
2410 }
2411 
2412 
2413 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2414 /// be represented as an indexed [r+r] operation.
2415 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2416                                                SDValue &Index,
2417                                                SelectionDAG &DAG) const {
2418   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2419       UI != E; ++UI) {
2420     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2421       if (Memop->getMemoryVT() == MVT::f64) {
2422           Base = N.getOperand(0);
2423           Index = N.getOperand(1);
2424           return true;
2425       }
2426     }
2427   }
2428   return false;
2429 }
2430 
2431 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2432 /// can be represented as an indexed [r+r] operation.  Returns false if it
2433 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2434 /// non-zero and N can be represented by a base register plus a signed 16-bit
2435 /// displacement, make a more precise judgement by checking (displacement % \p
2436 /// EncodingAlignment).
2437 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2438                                             SDValue &Index, SelectionDAG &DAG,
2439                                             unsigned EncodingAlignment) const {
2440   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2441   // a [pc+imm].
2442   if (SelectAddressPCRel(N, Base))
2443     return false;
2444 
2445   int16_t imm = 0;
2446   if (N.getOpcode() == ISD::ADD) {
2447     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2448     // SPE load/store can only handle 8-bit offsets.
2449     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2450         return true;
2451     if (isIntS16Immediate(N.getOperand(1), imm) &&
2452         (!EncodingAlignment || !(imm % EncodingAlignment)))
2453       return false; // r+i
2454     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2455       return false;    // r+i
2456 
2457     Base = N.getOperand(0);
2458     Index = N.getOperand(1);
2459     return true;
2460   } else if (N.getOpcode() == ISD::OR) {
2461     if (isIntS16Immediate(N.getOperand(1), imm) &&
2462         (!EncodingAlignment || !(imm % EncodingAlignment)))
2463       return false; // r+i can fold it if we can.
2464 
2465     // If this is an or of disjoint bitfields, we can codegen this as an add
2466     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2467     // disjoint.
2468     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2469 
2470     if (LHSKnown.Zero.getBoolValue()) {
2471       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2472       // If all of the bits are known zero on the LHS or RHS, the add won't
2473       // carry.
2474       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2475         Base = N.getOperand(0);
2476         Index = N.getOperand(1);
2477         return true;
2478       }
2479     }
2480   }
2481 
2482   return false;
2483 }
2484 
2485 // If we happen to be doing an i64 load or store into a stack slot that has
2486 // less than a 4-byte alignment, then the frame-index elimination may need to
2487 // use an indexed load or store instruction (because the offset may not be a
2488 // multiple of 4). The extra register needed to hold the offset comes from the
2489 // register scavenger, and it is possible that the scavenger will need to use
2490 // an emergency spill slot. As a result, we need to make sure that a spill slot
2491 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2492 // stack slot.
2493 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2494   // FIXME: This does not handle the LWA case.
2495   if (VT != MVT::i64)
2496     return;
2497 
2498   // NOTE: We'll exclude negative FIs here, which come from argument
2499   // lowering, because there are no known test cases triggering this problem
2500   // using packed structures (or similar). We can remove this exclusion if
2501   // we find such a test case. The reason why this is so test-case driven is
2502   // because this entire 'fixup' is only to prevent crashes (from the
2503   // register scavenger) on not-really-valid inputs. For example, if we have:
2504   //   %a = alloca i1
2505   //   %b = bitcast i1* %a to i64*
2506   //   store i64* a, i64 b
2507   // then the store should really be marked as 'align 1', but is not. If it
2508   // were marked as 'align 1' then the indexed form would have been
2509   // instruction-selected initially, and the problem this 'fixup' is preventing
2510   // won't happen regardless.
2511   if (FrameIdx < 0)
2512     return;
2513 
2514   MachineFunction &MF = DAG.getMachineFunction();
2515   MachineFrameInfo &MFI = MF.getFrameInfo();
2516 
2517   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2518     return;
2519 
2520   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2521   FuncInfo->setHasNonRISpills();
2522 }
2523 
2524 /// Returns true if the address N can be represented by a base register plus
2525 /// a signed 16-bit displacement [r+imm], and if it is not better
2526 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2527 /// displacements that are multiples of that value.
2528 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2529                                             SDValue &Base,
2530                                             SelectionDAG &DAG,
2531                                             unsigned EncodingAlignment) const {
2532   // FIXME dl should come from parent load or store, not from address
2533   SDLoc dl(N);
2534 
2535   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2536   // a [pc+imm].
2537   if (SelectAddressPCRel(N, Base))
2538     return false;
2539 
2540   // If this can be more profitably realized as r+r, fail.
2541   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2542     return false;
2543 
2544   if (N.getOpcode() == ISD::ADD) {
2545     int16_t imm = 0;
2546     if (isIntS16Immediate(N.getOperand(1), imm) &&
2547         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2548       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2549       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2550         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2551         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2552       } else {
2553         Base = N.getOperand(0);
2554       }
2555       return true; // [r+i]
2556     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2557       // Match LOAD (ADD (X, Lo(G))).
2558       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2559              && "Cannot handle constant offsets yet!");
2560       Disp = N.getOperand(1).getOperand(0);  // The global address.
2561       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2562              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2563              Disp.getOpcode() == ISD::TargetConstantPool ||
2564              Disp.getOpcode() == ISD::TargetJumpTable);
2565       Base = N.getOperand(0);
2566       return true;  // [&g+r]
2567     }
2568   } else if (N.getOpcode() == ISD::OR) {
2569     int16_t imm = 0;
2570     if (isIntS16Immediate(N.getOperand(1), imm) &&
2571         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2572       // If this is an or of disjoint bitfields, we can codegen this as an add
2573       // (for better address arithmetic) if the LHS and RHS of the OR are
2574       // provably disjoint.
2575       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2576 
2577       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2578         // If all of the bits are known zero on the LHS or RHS, the add won't
2579         // carry.
2580         if (FrameIndexSDNode *FI =
2581               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2582           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2583           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2584         } else {
2585           Base = N.getOperand(0);
2586         }
2587         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2588         return true;
2589       }
2590     }
2591   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2592     // Loading from a constant address.
2593 
2594     // If this address fits entirely in a 16-bit sext immediate field, codegen
2595     // this as "d, 0"
2596     int16_t Imm;
2597     if (isIntS16Immediate(CN, Imm) &&
2598         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2599       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2600       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2601                              CN->getValueType(0));
2602       return true;
2603     }
2604 
2605     // Handle 32-bit sext immediates with LIS + addr mode.
2606     if ((CN->getValueType(0) == MVT::i32 ||
2607          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2608         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2609       int Addr = (int)CN->getZExtValue();
2610 
2611       // Otherwise, break this down into an LIS + disp.
2612       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2613 
2614       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2615                                    MVT::i32);
2616       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2617       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2618       return true;
2619     }
2620   }
2621 
2622   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2623   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2624     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2625     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2626   } else
2627     Base = N;
2628   return true;      // [r+0]
2629 }
2630 
2631 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2632 /// represented as an indexed [r+r] operation.
2633 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2634                                                 SDValue &Index,
2635                                                 SelectionDAG &DAG) const {
2636   // Check to see if we can easily represent this as an [r+r] address.  This
2637   // will fail if it thinks that the address is more profitably represented as
2638   // reg+imm, e.g. where imm = 0.
2639   if (SelectAddressRegReg(N, Base, Index, DAG))
2640     return true;
2641 
2642   // If the address is the result of an add, we will utilize the fact that the
2643   // address calculation includes an implicit add.  However, we can reduce
2644   // register pressure if we do not materialize a constant just for use as the
2645   // index register.  We only get rid of the add if it is not an add of a
2646   // value and a 16-bit signed constant and both have a single use.
2647   int16_t imm = 0;
2648   if (N.getOpcode() == ISD::ADD &&
2649       (!isIntS16Immediate(N.getOperand(1), imm) ||
2650        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2651     Base = N.getOperand(0);
2652     Index = N.getOperand(1);
2653     return true;
2654   }
2655 
2656   // Otherwise, do it the hard way, using R0 as the base register.
2657   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2658                          N.getValueType());
2659   Index = N;
2660   return true;
2661 }
2662 
2663 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2664   Ty *PCRelCand = dyn_cast<Ty>(N);
2665   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2666 }
2667 
2668 /// Returns true if this address is a PC Relative address.
2669 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2670 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2671 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2672   // This is a materialize PC Relative node. Always select this as PC Relative.
2673   Base = N;
2674   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2675     return true;
2676   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2677       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2678       isValidPCRelNode<JumpTableSDNode>(N) ||
2679       isValidPCRelNode<BlockAddressSDNode>(N))
2680     return true;
2681   return false;
2682 }
2683 
2684 /// Returns true if we should use a direct load into vector instruction
2685 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2686 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2687 
2688   // If there are any other uses other than scalar to vector, then we should
2689   // keep it as a scalar load -> direct move pattern to prevent multiple
2690   // loads.
2691   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2692   if (!LD)
2693     return false;
2694 
2695   EVT MemVT = LD->getMemoryVT();
2696   if (!MemVT.isSimple())
2697     return false;
2698   switch(MemVT.getSimpleVT().SimpleTy) {
2699   case MVT::i64:
2700     break;
2701   case MVT::i32:
2702     if (!ST.hasP8Vector())
2703       return false;
2704     break;
2705   case MVT::i16:
2706   case MVT::i8:
2707     if (!ST.hasP9Vector())
2708       return false;
2709     break;
2710   default:
2711     return false;
2712   }
2713 
2714   SDValue LoadedVal(N, 0);
2715   if (!LoadedVal.hasOneUse())
2716     return false;
2717 
2718   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2719        UI != UE; ++UI)
2720     if (UI.getUse().get().getResNo() == 0 &&
2721         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2722         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2723       return false;
2724 
2725   return true;
2726 }
2727 
2728 /// getPreIndexedAddressParts - returns true by value, base pointer and
2729 /// offset pointer and addressing mode by reference if the node's address
2730 /// can be legally represented as pre-indexed load / store address.
2731 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2732                                                   SDValue &Offset,
2733                                                   ISD::MemIndexedMode &AM,
2734                                                   SelectionDAG &DAG) const {
2735   if (DisablePPCPreinc) return false;
2736 
2737   bool isLoad = true;
2738   SDValue Ptr;
2739   EVT VT;
2740   unsigned Alignment;
2741   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2742     Ptr = LD->getBasePtr();
2743     VT = LD->getMemoryVT();
2744     Alignment = LD->getAlignment();
2745   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2746     Ptr = ST->getBasePtr();
2747     VT  = ST->getMemoryVT();
2748     Alignment = ST->getAlignment();
2749     isLoad = false;
2750   } else
2751     return false;
2752 
2753   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2754   // instructions because we can fold these into a more efficient instruction
2755   // instead, (such as LXSD).
2756   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2757     return false;
2758   }
2759 
2760   // PowerPC doesn't have preinc load/store instructions for vectors (except
2761   // for QPX, which does have preinc r+r forms).
2762   if (VT.isVector()) {
2763     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2764       return false;
2765     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2766       AM = ISD::PRE_INC;
2767       return true;
2768     }
2769   }
2770 
2771   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2772     // Common code will reject creating a pre-inc form if the base pointer
2773     // is a frame index, or if N is a store and the base pointer is either
2774     // the same as or a predecessor of the value being stored.  Check for
2775     // those situations here, and try with swapped Base/Offset instead.
2776     bool Swap = false;
2777 
2778     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2779       Swap = true;
2780     else if (!isLoad) {
2781       SDValue Val = cast<StoreSDNode>(N)->getValue();
2782       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2783         Swap = true;
2784     }
2785 
2786     if (Swap)
2787       std::swap(Base, Offset);
2788 
2789     AM = ISD::PRE_INC;
2790     return true;
2791   }
2792 
2793   // LDU/STU can only handle immediates that are a multiple of 4.
2794   if (VT != MVT::i64) {
2795     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2796       return false;
2797   } else {
2798     // LDU/STU need an address with at least 4-byte alignment.
2799     if (Alignment < 4)
2800       return false;
2801 
2802     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2803       return false;
2804   }
2805 
2806   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2807     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2808     // sext i32 to i64 when addr mode is r+i.
2809     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2810         LD->getExtensionType() == ISD::SEXTLOAD &&
2811         isa<ConstantSDNode>(Offset))
2812       return false;
2813   }
2814 
2815   AM = ISD::PRE_INC;
2816   return true;
2817 }
2818 
2819 //===----------------------------------------------------------------------===//
2820 //  LowerOperation implementation
2821 //===----------------------------------------------------------------------===//
2822 
2823 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2824 /// and LoOpFlags to the target MO flags.
2825 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2826                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2827                                const GlobalValue *GV = nullptr) {
2828   HiOpFlags = PPCII::MO_HA;
2829   LoOpFlags = PPCII::MO_LO;
2830 
2831   // Don't use the pic base if not in PIC relocation model.
2832   if (IsPIC) {
2833     HiOpFlags |= PPCII::MO_PIC_FLAG;
2834     LoOpFlags |= PPCII::MO_PIC_FLAG;
2835   }
2836 }
2837 
2838 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2839                              SelectionDAG &DAG) {
2840   SDLoc DL(HiPart);
2841   EVT PtrVT = HiPart.getValueType();
2842   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2843 
2844   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2845   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2846 
2847   // With PIC, the first instruction is actually "GR+hi(&G)".
2848   if (isPIC)
2849     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2850                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2851 
2852   // Generate non-pic code that has direct accesses to the constant pool.
2853   // The address of the global is just (hi(&g)+lo(&g)).
2854   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2855 }
2856 
2857 static void setUsesTOCBasePtr(MachineFunction &MF) {
2858   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2859   FuncInfo->setUsesTOCBasePtr();
2860 }
2861 
2862 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2863   setUsesTOCBasePtr(DAG.getMachineFunction());
2864 }
2865 
2866 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2867                                        SDValue GA) const {
2868   const bool Is64Bit = Subtarget.isPPC64();
2869   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2870   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2871                         : Subtarget.isAIXABI()
2872                               ? DAG.getRegister(PPC::R2, VT)
2873                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2874   SDValue Ops[] = { GA, Reg };
2875   return DAG.getMemIntrinsicNode(
2876       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2877       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2878       MachineMemOperand::MOLoad);
2879 }
2880 
2881 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2882                                              SelectionDAG &DAG) const {
2883   EVT PtrVT = Op.getValueType();
2884   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2885   const Constant *C = CP->getConstVal();
2886 
2887   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2888   // The actual address of the GlobalValue is stored in the TOC.
2889   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2890     if (Subtarget.isUsingPCRelativeCalls()) {
2891       SDLoc DL(CP);
2892       EVT Ty = getPointerTy(DAG.getDataLayout());
2893       SDValue ConstPool = DAG.getTargetConstantPool(
2894           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2895       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2896     }
2897     setUsesTOCBasePtr(DAG);
2898     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2899     return getTOCEntry(DAG, SDLoc(CP), GA);
2900   }
2901 
2902   unsigned MOHiFlag, MOLoFlag;
2903   bool IsPIC = isPositionIndependent();
2904   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2905 
2906   if (IsPIC && Subtarget.isSVR4ABI()) {
2907     SDValue GA =
2908         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2909     return getTOCEntry(DAG, SDLoc(CP), GA);
2910   }
2911 
2912   SDValue CPIHi =
2913       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2914   SDValue CPILo =
2915       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2916   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2917 }
2918 
2919 // For 64-bit PowerPC, prefer the more compact relative encodings.
2920 // This trades 32 bits per jump table entry for one or two instructions
2921 // on the jump site.
2922 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2923   if (isJumpTableRelative())
2924     return MachineJumpTableInfo::EK_LabelDifference32;
2925 
2926   return TargetLowering::getJumpTableEncoding();
2927 }
2928 
2929 bool PPCTargetLowering::isJumpTableRelative() const {
2930   if (UseAbsoluteJumpTables)
2931     return false;
2932   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2933     return true;
2934   return TargetLowering::isJumpTableRelative();
2935 }
2936 
2937 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2938                                                     SelectionDAG &DAG) const {
2939   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2940     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2941 
2942   switch (getTargetMachine().getCodeModel()) {
2943   case CodeModel::Small:
2944   case CodeModel::Medium:
2945     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2946   default:
2947     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2948                        getPointerTy(DAG.getDataLayout()));
2949   }
2950 }
2951 
2952 const MCExpr *
2953 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2954                                                 unsigned JTI,
2955                                                 MCContext &Ctx) const {
2956   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2957     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2958 
2959   switch (getTargetMachine().getCodeModel()) {
2960   case CodeModel::Small:
2961   case CodeModel::Medium:
2962     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2963   default:
2964     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2965   }
2966 }
2967 
2968 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2969   EVT PtrVT = Op.getValueType();
2970   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2971 
2972   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2973   if (Subtarget.isUsingPCRelativeCalls()) {
2974     SDLoc DL(JT);
2975     EVT Ty = getPointerTy(DAG.getDataLayout());
2976     SDValue GA =
2977         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2978     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2979     return MatAddr;
2980   }
2981 
2982   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2983   // The actual address of the GlobalValue is stored in the TOC.
2984   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2985     setUsesTOCBasePtr(DAG);
2986     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2987     return getTOCEntry(DAG, SDLoc(JT), GA);
2988   }
2989 
2990   unsigned MOHiFlag, MOLoFlag;
2991   bool IsPIC = isPositionIndependent();
2992   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2993 
2994   if (IsPIC && Subtarget.isSVR4ABI()) {
2995     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2996                                         PPCII::MO_PIC_FLAG);
2997     return getTOCEntry(DAG, SDLoc(GA), GA);
2998   }
2999 
3000   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3001   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3002   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3003 }
3004 
3005 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3006                                              SelectionDAG &DAG) const {
3007   EVT PtrVT = Op.getValueType();
3008   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3009   const BlockAddress *BA = BASDN->getBlockAddress();
3010 
3011   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3012   if (Subtarget.isUsingPCRelativeCalls()) {
3013     SDLoc DL(BASDN);
3014     EVT Ty = getPointerTy(DAG.getDataLayout());
3015     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3016                                            PPCII::MO_PCREL_FLAG);
3017     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3018     return MatAddr;
3019   }
3020 
3021   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3022   // The actual BlockAddress is stored in the TOC.
3023   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3024     setUsesTOCBasePtr(DAG);
3025     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3026     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3027   }
3028 
3029   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3030   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3031     return getTOCEntry(
3032         DAG, SDLoc(BASDN),
3033         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3034 
3035   unsigned MOHiFlag, MOLoFlag;
3036   bool IsPIC = isPositionIndependent();
3037   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3038   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3039   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3040   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3041 }
3042 
3043 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3044                                               SelectionDAG &DAG) const {
3045   // FIXME: TLS addresses currently use medium model code sequences,
3046   // which is the most useful form.  Eventually support for small and
3047   // large models could be added if users need it, at the cost of
3048   // additional complexity.
3049   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3050   if (DAG.getTarget().useEmulatedTLS())
3051     return LowerToTLSEmulatedModel(GA, DAG);
3052 
3053   SDLoc dl(GA);
3054   const GlobalValue *GV = GA->getGlobal();
3055   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3056   bool is64bit = Subtarget.isPPC64();
3057   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3058   PICLevel::Level picLevel = M->getPICLevel();
3059 
3060   const TargetMachine &TM = getTargetMachine();
3061   TLSModel::Model Model = TM.getTLSModel(GV);
3062 
3063   if (Model == TLSModel::LocalExec) {
3064     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3065                                                PPCII::MO_TPREL_HA);
3066     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3067                                                PPCII::MO_TPREL_LO);
3068     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3069                              : DAG.getRegister(PPC::R2, MVT::i32);
3070 
3071     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3072     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3073   }
3074 
3075   if (Model == TLSModel::InitialExec) {
3076     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3077     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3078                                                 PPCII::MO_TLS);
3079     SDValue GOTPtr;
3080     if (is64bit) {
3081       setUsesTOCBasePtr(DAG);
3082       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3083       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
3084                            PtrVT, GOTReg, TGA);
3085     } else {
3086       if (!TM.isPositionIndependent())
3087         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3088       else if (picLevel == PICLevel::SmallPIC)
3089         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3090       else
3091         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3092     }
3093     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
3094                                    PtrVT, TGA, GOTPtr);
3095     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3096   }
3097 
3098   if (Model == TLSModel::GeneralDynamic) {
3099     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3100     SDValue GOTPtr;
3101     if (is64bit) {
3102       setUsesTOCBasePtr(DAG);
3103       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3104       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3105                                    GOTReg, TGA);
3106     } else {
3107       if (picLevel == PICLevel::SmallPIC)
3108         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3109       else
3110         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3111     }
3112     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3113                        GOTPtr, TGA, TGA);
3114   }
3115 
3116   if (Model == TLSModel::LocalDynamic) {
3117     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3118     SDValue GOTPtr;
3119     if (is64bit) {
3120       setUsesTOCBasePtr(DAG);
3121       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3122       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3123                            GOTReg, TGA);
3124     } else {
3125       if (picLevel == PICLevel::SmallPIC)
3126         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3127       else
3128         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3129     }
3130     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3131                                   PtrVT, GOTPtr, TGA, TGA);
3132     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3133                                       PtrVT, TLSAddr, TGA);
3134     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3135   }
3136 
3137   llvm_unreachable("Unknown TLS model!");
3138 }
3139 
3140 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3141                                               SelectionDAG &DAG) const {
3142   EVT PtrVT = Op.getValueType();
3143   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3144   SDLoc DL(GSDN);
3145   const GlobalValue *GV = GSDN->getGlobal();
3146 
3147   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3148   // The actual address of the GlobalValue is stored in the TOC.
3149   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3150     if (Subtarget.isUsingPCRelativeCalls()) {
3151       EVT Ty = getPointerTy(DAG.getDataLayout());
3152       if (isAccessedAsGotIndirect(Op)) {
3153         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3154                                                 PPCII::MO_PCREL_FLAG |
3155                                                     PPCII::MO_GOT_FLAG);
3156         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3157         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3158                                    MachinePointerInfo());
3159         return Load;
3160       } else {
3161         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3162                                                 PPCII::MO_PCREL_FLAG);
3163         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3164       }
3165     }
3166     setUsesTOCBasePtr(DAG);
3167     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3168     return getTOCEntry(DAG, DL, GA);
3169   }
3170 
3171   unsigned MOHiFlag, MOLoFlag;
3172   bool IsPIC = isPositionIndependent();
3173   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3174 
3175   if (IsPIC && Subtarget.isSVR4ABI()) {
3176     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3177                                             GSDN->getOffset(),
3178                                             PPCII::MO_PIC_FLAG);
3179     return getTOCEntry(DAG, DL, GA);
3180   }
3181 
3182   SDValue GAHi =
3183     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3184   SDValue GALo =
3185     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3186 
3187   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3188 }
3189 
3190 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3191   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3192   SDLoc dl(Op);
3193 
3194   if (Op.getValueType() == MVT::v2i64) {
3195     // When the operands themselves are v2i64 values, we need to do something
3196     // special because VSX has no underlying comparison operations for these.
3197     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3198       // Equality can be handled by casting to the legal type for Altivec
3199       // comparisons, everything else needs to be expanded.
3200       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3201         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3202                  DAG.getSetCC(dl, MVT::v4i32,
3203                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3204                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3205                    CC));
3206       }
3207 
3208       return SDValue();
3209     }
3210 
3211     // We handle most of these in the usual way.
3212     return Op;
3213   }
3214 
3215   // If we're comparing for equality to zero, expose the fact that this is
3216   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3217   // fold the new nodes.
3218   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3219     return V;
3220 
3221   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3222     // Leave comparisons against 0 and -1 alone for now, since they're usually
3223     // optimized.  FIXME: revisit this when we can custom lower all setcc
3224     // optimizations.
3225     if (C->isAllOnesValue() || C->isNullValue())
3226       return SDValue();
3227   }
3228 
3229   // If we have an integer seteq/setne, turn it into a compare against zero
3230   // by xor'ing the rhs with the lhs, which is faster than setting a
3231   // condition register, reading it back out, and masking the correct bit.  The
3232   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3233   // the result to other bit-twiddling opportunities.
3234   EVT LHSVT = Op.getOperand(0).getValueType();
3235   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3236     EVT VT = Op.getValueType();
3237     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3238                                 Op.getOperand(1));
3239     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3240   }
3241   return SDValue();
3242 }
3243 
3244 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3245   SDNode *Node = Op.getNode();
3246   EVT VT = Node->getValueType(0);
3247   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3248   SDValue InChain = Node->getOperand(0);
3249   SDValue VAListPtr = Node->getOperand(1);
3250   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3251   SDLoc dl(Node);
3252 
3253   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3254 
3255   // gpr_index
3256   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3257                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3258   InChain = GprIndex.getValue(1);
3259 
3260   if (VT == MVT::i64) {
3261     // Check if GprIndex is even
3262     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3263                                  DAG.getConstant(1, dl, MVT::i32));
3264     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3265                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3266     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3267                                           DAG.getConstant(1, dl, MVT::i32));
3268     // Align GprIndex to be even if it isn't
3269     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3270                            GprIndex);
3271   }
3272 
3273   // fpr index is 1 byte after gpr
3274   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3275                                DAG.getConstant(1, dl, MVT::i32));
3276 
3277   // fpr
3278   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3279                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3280   InChain = FprIndex.getValue(1);
3281 
3282   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3283                                        DAG.getConstant(8, dl, MVT::i32));
3284 
3285   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3286                                         DAG.getConstant(4, dl, MVT::i32));
3287 
3288   // areas
3289   SDValue OverflowArea =
3290       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3291   InChain = OverflowArea.getValue(1);
3292 
3293   SDValue RegSaveArea =
3294       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3295   InChain = RegSaveArea.getValue(1);
3296 
3297   // select overflow_area if index > 8
3298   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3299                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3300 
3301   // adjustment constant gpr_index * 4/8
3302   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3303                                     VT.isInteger() ? GprIndex : FprIndex,
3304                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3305                                                     MVT::i32));
3306 
3307   // OurReg = RegSaveArea + RegConstant
3308   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3309                                RegConstant);
3310 
3311   // Floating types are 32 bytes into RegSaveArea
3312   if (VT.isFloatingPoint())
3313     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3314                          DAG.getConstant(32, dl, MVT::i32));
3315 
3316   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3317   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3318                                    VT.isInteger() ? GprIndex : FprIndex,
3319                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3320                                                    MVT::i32));
3321 
3322   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3323                               VT.isInteger() ? VAListPtr : FprPtr,
3324                               MachinePointerInfo(SV), MVT::i8);
3325 
3326   // determine if we should load from reg_save_area or overflow_area
3327   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3328 
3329   // increase overflow_area by 4/8 if gpr/fpr > 8
3330   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3331                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3332                                           dl, MVT::i32));
3333 
3334   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3335                              OverflowAreaPlusN);
3336 
3337   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3338                               MachinePointerInfo(), MVT::i32);
3339 
3340   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3341 }
3342 
3343 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3344   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3345 
3346   // We have to copy the entire va_list struct:
3347   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3348   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3349                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3350                        false, true, false, MachinePointerInfo(),
3351                        MachinePointerInfo());
3352 }
3353 
3354 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3355                                                   SelectionDAG &DAG) const {
3356   if (Subtarget.isAIXABI())
3357     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3358 
3359   return Op.getOperand(0);
3360 }
3361 
3362 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3363                                                 SelectionDAG &DAG) const {
3364   if (Subtarget.isAIXABI())
3365     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3366 
3367   SDValue Chain = Op.getOperand(0);
3368   SDValue Trmp = Op.getOperand(1); // trampoline
3369   SDValue FPtr = Op.getOperand(2); // nested function
3370   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3371   SDLoc dl(Op);
3372 
3373   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3374   bool isPPC64 = (PtrVT == MVT::i64);
3375   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3376 
3377   TargetLowering::ArgListTy Args;
3378   TargetLowering::ArgListEntry Entry;
3379 
3380   Entry.Ty = IntPtrTy;
3381   Entry.Node = Trmp; Args.push_back(Entry);
3382 
3383   // TrampSize == (isPPC64 ? 48 : 40);
3384   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3385                                isPPC64 ? MVT::i64 : MVT::i32);
3386   Args.push_back(Entry);
3387 
3388   Entry.Node = FPtr; Args.push_back(Entry);
3389   Entry.Node = Nest; Args.push_back(Entry);
3390 
3391   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3392   TargetLowering::CallLoweringInfo CLI(DAG);
3393   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3394       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3395       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3396 
3397   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3398   return CallResult.second;
3399 }
3400 
3401 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3402   MachineFunction &MF = DAG.getMachineFunction();
3403   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3404   EVT PtrVT = getPointerTy(MF.getDataLayout());
3405 
3406   SDLoc dl(Op);
3407 
3408   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3409     // vastart just stores the address of the VarArgsFrameIndex slot into the
3410     // memory location argument.
3411     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3412     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3413     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3414                         MachinePointerInfo(SV));
3415   }
3416 
3417   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3418   // We suppose the given va_list is already allocated.
3419   //
3420   // typedef struct {
3421   //  char gpr;     /* index into the array of 8 GPRs
3422   //                 * stored in the register save area
3423   //                 * gpr=0 corresponds to r3,
3424   //                 * gpr=1 to r4, etc.
3425   //                 */
3426   //  char fpr;     /* index into the array of 8 FPRs
3427   //                 * stored in the register save area
3428   //                 * fpr=0 corresponds to f1,
3429   //                 * fpr=1 to f2, etc.
3430   //                 */
3431   //  char *overflow_arg_area;
3432   //                /* location on stack that holds
3433   //                 * the next overflow argument
3434   //                 */
3435   //  char *reg_save_area;
3436   //               /* where r3:r10 and f1:f8 (if saved)
3437   //                * are stored
3438   //                */
3439   // } va_list[1];
3440 
3441   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3442   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3443   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3444                                             PtrVT);
3445   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3446                                  PtrVT);
3447 
3448   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3449   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3450 
3451   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3452   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3453 
3454   uint64_t FPROffset = 1;
3455   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3456 
3457   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3458 
3459   // Store first byte : number of int regs
3460   SDValue firstStore =
3461       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3462                         MachinePointerInfo(SV), MVT::i8);
3463   uint64_t nextOffset = FPROffset;
3464   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3465                                   ConstFPROffset);
3466 
3467   // Store second byte : number of float regs
3468   SDValue secondStore =
3469       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3470                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3471   nextOffset += StackOffset;
3472   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3473 
3474   // Store second word : arguments given on stack
3475   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3476                                     MachinePointerInfo(SV, nextOffset));
3477   nextOffset += FrameOffset;
3478   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3479 
3480   // Store third word : arguments given in registers
3481   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3482                       MachinePointerInfo(SV, nextOffset));
3483 }
3484 
3485 /// FPR - The set of FP registers that should be allocated for arguments
3486 /// on Darwin and AIX.
3487 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3488                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3489                                 PPC::F11, PPC::F12, PPC::F13};
3490 
3491 /// QFPR - The set of QPX registers that should be allocated for arguments.
3492 static const MCPhysReg QFPR[] = {
3493     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3494     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3495 
3496 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3497 /// the stack.
3498 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3499                                        unsigned PtrByteSize) {
3500   unsigned ArgSize = ArgVT.getStoreSize();
3501   if (Flags.isByVal())
3502     ArgSize = Flags.getByValSize();
3503 
3504   // Round up to multiples of the pointer size, except for array members,
3505   // which are always packed.
3506   if (!Flags.isInConsecutiveRegs())
3507     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3508 
3509   return ArgSize;
3510 }
3511 
3512 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3513 /// on the stack.
3514 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3515                                          ISD::ArgFlagsTy Flags,
3516                                          unsigned PtrByteSize) {
3517   Align Alignment(PtrByteSize);
3518 
3519   // Altivec parameters are padded to a 16 byte boundary.
3520   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3521       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3522       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3523       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3524     Alignment = Align(16);
3525   // QPX vector types stored in double-precision are padded to a 32 byte
3526   // boundary.
3527   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3528     Alignment = Align(32);
3529 
3530   // ByVal parameters are aligned as requested.
3531   if (Flags.isByVal()) {
3532     auto BVAlign = Flags.getNonZeroByValAlign();
3533     if (BVAlign > PtrByteSize) {
3534       if (BVAlign.value() % PtrByteSize != 0)
3535         llvm_unreachable(
3536             "ByVal alignment is not a multiple of the pointer size");
3537 
3538       Alignment = BVAlign;
3539     }
3540   }
3541 
3542   // Array members are always packed to their original alignment.
3543   if (Flags.isInConsecutiveRegs()) {
3544     // If the array member was split into multiple registers, the first
3545     // needs to be aligned to the size of the full type.  (Except for
3546     // ppcf128, which is only aligned as its f64 components.)
3547     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3548       Alignment = Align(OrigVT.getStoreSize());
3549     else
3550       Alignment = Align(ArgVT.getStoreSize());
3551   }
3552 
3553   return Alignment;
3554 }
3555 
3556 /// CalculateStackSlotUsed - Return whether this argument will use its
3557 /// stack slot (instead of being passed in registers).  ArgOffset,
3558 /// AvailableFPRs, and AvailableVRs must hold the current argument
3559 /// position, and will be updated to account for this argument.
3560 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3561                                    ISD::ArgFlagsTy Flags,
3562                                    unsigned PtrByteSize,
3563                                    unsigned LinkageSize,
3564                                    unsigned ParamAreaSize,
3565                                    unsigned &ArgOffset,
3566                                    unsigned &AvailableFPRs,
3567                                    unsigned &AvailableVRs, bool HasQPX) {
3568   bool UseMemory = false;
3569 
3570   // Respect alignment of argument on the stack.
3571   Align Alignment =
3572       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3573   ArgOffset = alignTo(ArgOffset, Alignment);
3574   // If there's no space left in the argument save area, we must
3575   // use memory (this check also catches zero-sized arguments).
3576   if (ArgOffset >= LinkageSize + ParamAreaSize)
3577     UseMemory = true;
3578 
3579   // Allocate argument on the stack.
3580   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3581   if (Flags.isInConsecutiveRegsLast())
3582     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3583   // If we overran the argument save area, we must use memory
3584   // (this check catches arguments passed partially in memory)
3585   if (ArgOffset > LinkageSize + ParamAreaSize)
3586     UseMemory = true;
3587 
3588   // However, if the argument is actually passed in an FPR or a VR,
3589   // we don't use memory after all.
3590   if (!Flags.isByVal()) {
3591     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3592         // QPX registers overlap with the scalar FP registers.
3593         (HasQPX && (ArgVT == MVT::v4f32 ||
3594                     ArgVT == MVT::v4f64 ||
3595                     ArgVT == MVT::v4i1)))
3596       if (AvailableFPRs > 0) {
3597         --AvailableFPRs;
3598         return false;
3599       }
3600     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3601         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3602         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3603         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3604       if (AvailableVRs > 0) {
3605         --AvailableVRs;
3606         return false;
3607       }
3608   }
3609 
3610   return UseMemory;
3611 }
3612 
3613 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3614 /// ensure minimum alignment required for target.
3615 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3616                                      unsigned NumBytes) {
3617   return alignTo(NumBytes, Lowering->getStackAlign());
3618 }
3619 
3620 SDValue PPCTargetLowering::LowerFormalArguments(
3621     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3622     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3623     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3624   if (Subtarget.isAIXABI())
3625     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3626                                     InVals);
3627   if (Subtarget.is64BitELFABI())
3628     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3629                                        InVals);
3630   if (Subtarget.is32BitELFABI())
3631     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3632                                        InVals);
3633 
3634   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3635                                      InVals);
3636 }
3637 
3638 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3639     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3640     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3641     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3642 
3643   // 32-bit SVR4 ABI Stack Frame Layout:
3644   //              +-----------------------------------+
3645   //        +-->  |            Back chain             |
3646   //        |     +-----------------------------------+
3647   //        |     | Floating-point register save area |
3648   //        |     +-----------------------------------+
3649   //        |     |    General register save area     |
3650   //        |     +-----------------------------------+
3651   //        |     |          CR save word             |
3652   //        |     +-----------------------------------+
3653   //        |     |         VRSAVE save word          |
3654   //        |     +-----------------------------------+
3655   //        |     |         Alignment padding         |
3656   //        |     +-----------------------------------+
3657   //        |     |     Vector register save area     |
3658   //        |     +-----------------------------------+
3659   //        |     |       Local variable space        |
3660   //        |     +-----------------------------------+
3661   //        |     |        Parameter list area        |
3662   //        |     +-----------------------------------+
3663   //        |     |           LR save word            |
3664   //        |     +-----------------------------------+
3665   // SP-->  +---  |            Back chain             |
3666   //              +-----------------------------------+
3667   //
3668   // Specifications:
3669   //   System V Application Binary Interface PowerPC Processor Supplement
3670   //   AltiVec Technology Programming Interface Manual
3671 
3672   MachineFunction &MF = DAG.getMachineFunction();
3673   MachineFrameInfo &MFI = MF.getFrameInfo();
3674   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3675 
3676   EVT PtrVT = getPointerTy(MF.getDataLayout());
3677   // Potential tail calls could cause overwriting of argument stack slots.
3678   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3679                        (CallConv == CallingConv::Fast));
3680   const Align PtrAlign(4);
3681 
3682   // Assign locations to all of the incoming arguments.
3683   SmallVector<CCValAssign, 16> ArgLocs;
3684   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3685                  *DAG.getContext());
3686 
3687   // Reserve space for the linkage area on the stack.
3688   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3689   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3690   if (useSoftFloat())
3691     CCInfo.PreAnalyzeFormalArguments(Ins);
3692 
3693   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3694   CCInfo.clearWasPPCF128();
3695 
3696   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3697     CCValAssign &VA = ArgLocs[i];
3698 
3699     // Arguments stored in registers.
3700     if (VA.isRegLoc()) {
3701       const TargetRegisterClass *RC;
3702       EVT ValVT = VA.getValVT();
3703 
3704       switch (ValVT.getSimpleVT().SimpleTy) {
3705         default:
3706           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3707         case MVT::i1:
3708         case MVT::i32:
3709           RC = &PPC::GPRCRegClass;
3710           break;
3711         case MVT::f32:
3712           if (Subtarget.hasP8Vector())
3713             RC = &PPC::VSSRCRegClass;
3714           else if (Subtarget.hasSPE())
3715             RC = &PPC::GPRCRegClass;
3716           else
3717             RC = &PPC::F4RCRegClass;
3718           break;
3719         case MVT::f64:
3720           if (Subtarget.hasVSX())
3721             RC = &PPC::VSFRCRegClass;
3722           else if (Subtarget.hasSPE())
3723             // SPE passes doubles in GPR pairs.
3724             RC = &PPC::GPRCRegClass;
3725           else
3726             RC = &PPC::F8RCRegClass;
3727           break;
3728         case MVT::v16i8:
3729         case MVT::v8i16:
3730         case MVT::v4i32:
3731           RC = &PPC::VRRCRegClass;
3732           break;
3733         case MVT::v4f32:
3734           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3735           break;
3736         case MVT::v2f64:
3737         case MVT::v2i64:
3738           RC = &PPC::VRRCRegClass;
3739           break;
3740         case MVT::v4f64:
3741           RC = &PPC::QFRCRegClass;
3742           break;
3743         case MVT::v4i1:
3744           RC = &PPC::QBRCRegClass;
3745           break;
3746       }
3747 
3748       SDValue ArgValue;
3749       // Transform the arguments stored in physical registers into
3750       // virtual ones.
3751       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3752         assert(i + 1 < e && "No second half of double precision argument");
3753         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3754         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3755         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3756         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3757         if (!Subtarget.isLittleEndian())
3758           std::swap (ArgValueLo, ArgValueHi);
3759         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3760                                ArgValueHi);
3761       } else {
3762         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3763         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3764                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3765         if (ValVT == MVT::i1)
3766           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3767       }
3768 
3769       InVals.push_back(ArgValue);
3770     } else {
3771       // Argument stored in memory.
3772       assert(VA.isMemLoc());
3773 
3774       // Get the extended size of the argument type in stack
3775       unsigned ArgSize = VA.getLocVT().getStoreSize();
3776       // Get the actual size of the argument type
3777       unsigned ObjSize = VA.getValVT().getStoreSize();
3778       unsigned ArgOffset = VA.getLocMemOffset();
3779       // Stack objects in PPC32 are right justified.
3780       ArgOffset += ArgSize - ObjSize;
3781       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3782 
3783       // Create load nodes to retrieve arguments from the stack.
3784       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3785       InVals.push_back(
3786           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3787     }
3788   }
3789 
3790   // Assign locations to all of the incoming aggregate by value arguments.
3791   // Aggregates passed by value are stored in the local variable space of the
3792   // caller's stack frame, right above the parameter list area.
3793   SmallVector<CCValAssign, 16> ByValArgLocs;
3794   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3795                       ByValArgLocs, *DAG.getContext());
3796 
3797   // Reserve stack space for the allocations in CCInfo.
3798   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3799 
3800   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3801 
3802   // Area that is at least reserved in the caller of this function.
3803   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3804   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3805 
3806   // Set the size that is at least reserved in caller of this function.  Tail
3807   // call optimized function's reserved stack space needs to be aligned so that
3808   // taking the difference between two stack areas will result in an aligned
3809   // stack.
3810   MinReservedArea =
3811       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3812   FuncInfo->setMinReservedArea(MinReservedArea);
3813 
3814   SmallVector<SDValue, 8> MemOps;
3815 
3816   // If the function takes variable number of arguments, make a frame index for
3817   // the start of the first vararg value... for expansion of llvm.va_start.
3818   if (isVarArg) {
3819     static const MCPhysReg GPArgRegs[] = {
3820       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3821       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3822     };
3823     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3824 
3825     static const MCPhysReg FPArgRegs[] = {
3826       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3827       PPC::F8
3828     };
3829     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3830 
3831     if (useSoftFloat() || hasSPE())
3832        NumFPArgRegs = 0;
3833 
3834     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3835     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3836 
3837     // Make room for NumGPArgRegs and NumFPArgRegs.
3838     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3839                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3840 
3841     FuncInfo->setVarArgsStackOffset(
3842       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3843                             CCInfo.getNextStackOffset(), true));
3844 
3845     FuncInfo->setVarArgsFrameIndex(
3846         MFI.CreateStackObject(Depth, Align(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 callsShareTOCBase(const Function *Caller, SDValue Callee,
4704                               const TargetMachine &TM) {
4705   // It does not make sense to call callsShareTOCBase() with a caller that
4706   // is PC Relative since PC Relative callers do not have a TOC.
4707 #ifndef NDEBUG
4708   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4709   assert(!STICaller->isUsingPCRelativeCalls() &&
4710          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4711 #endif
4712 
4713   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4714   // don't have enough information to determine if the caller and callee share
4715   // the same  TOC base, so we have to pessimistically assume they don't for
4716   // correctness.
4717   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4718   if (!G)
4719     return false;
4720 
4721   const GlobalValue *GV = G->getGlobal();
4722 
4723   // If the callee is preemptable, then the static linker will use a plt-stub
4724   // which saves the toc to the stack, and needs a nop after the call
4725   // instruction to convert to a toc-restore.
4726   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4727     return false;
4728 
4729   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4730   // We may need a TOC restore in the situation where the caller requires a
4731   // valid TOC but the callee is PC Relative and does not.
4732   const Function *F = dyn_cast<Function>(GV);
4733   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4734 
4735   // If we have an Alias we can try to get the function from there.
4736   if (Alias) {
4737     const GlobalObject *GlobalObj = Alias->getBaseObject();
4738     F = dyn_cast<Function>(GlobalObj);
4739   }
4740 
4741   // If we still have no valid function pointer we do not have enough
4742   // information to determine if the callee uses PC Relative calls so we must
4743   // assume that it does.
4744   if (!F)
4745     return false;
4746 
4747   // If the callee uses PC Relative we cannot guarantee that the callee won't
4748   // clobber the TOC of the caller and so we must assume that the two
4749   // functions do not share a TOC base.
4750   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4751   if (STICallee->isUsingPCRelativeCalls())
4752     return false;
4753 
4754   // The medium and large code models are expected to provide a sufficiently
4755   // large TOC to provide all data addressing needs of a module with a
4756   // single TOC.
4757   if (CodeModel::Medium == TM.getCodeModel() ||
4758       CodeModel::Large == TM.getCodeModel())
4759     return true;
4760 
4761   // Otherwise we need to ensure callee and caller are in the same section,
4762   // since the linker may allocate multiple TOCs, and we don't know which
4763   // sections will belong to the same TOC base.
4764   if (!GV->isStrongDefinitionForLinker())
4765     return false;
4766 
4767   // Any explicitly-specified sections and section prefixes must also match.
4768   // Also, if we're using -ffunction-sections, then each function is always in
4769   // a different section (the same is true for COMDAT functions).
4770   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4771       GV->getSection() != Caller->getSection())
4772     return false;
4773   if (const auto *F = dyn_cast<Function>(GV)) {
4774     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4775       return false;
4776   }
4777 
4778   return true;
4779 }
4780 
4781 static bool
4782 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4783                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4784   assert(Subtarget.is64BitELFABI());
4785 
4786   const unsigned PtrByteSize = 8;
4787   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4788 
4789   static const MCPhysReg GPR[] = {
4790     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4791     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4792   };
4793   static const MCPhysReg VR[] = {
4794     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4795     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4796   };
4797 
4798   const unsigned NumGPRs = array_lengthof(GPR);
4799   const unsigned NumFPRs = 13;
4800   const unsigned NumVRs = array_lengthof(VR);
4801   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4802 
4803   unsigned NumBytes = LinkageSize;
4804   unsigned AvailableFPRs = NumFPRs;
4805   unsigned AvailableVRs = NumVRs;
4806 
4807   for (const ISD::OutputArg& Param : Outs) {
4808     if (Param.Flags.isNest()) continue;
4809 
4810     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4811                                PtrByteSize, LinkageSize, ParamAreaSize,
4812                                NumBytes, AvailableFPRs, AvailableVRs,
4813                                Subtarget.hasQPX()))
4814       return true;
4815   }
4816   return false;
4817 }
4818 
4819 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4820   if (CB.arg_size() != CallerFn->arg_size())
4821     return false;
4822 
4823   auto CalleeArgIter = CB.arg_begin();
4824   auto CalleeArgEnd = CB.arg_end();
4825   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4826 
4827   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4828     const Value* CalleeArg = *CalleeArgIter;
4829     const Value* CallerArg = &(*CallerArgIter);
4830     if (CalleeArg == CallerArg)
4831       continue;
4832 
4833     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4834     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4835     //      }
4836     // 1st argument of callee is undef and has the same type as caller.
4837     if (CalleeArg->getType() == CallerArg->getType() &&
4838         isa<UndefValue>(CalleeArg))
4839       continue;
4840 
4841     return false;
4842   }
4843 
4844   return true;
4845 }
4846 
4847 // Returns true if TCO is possible between the callers and callees
4848 // calling conventions.
4849 static bool
4850 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4851                                     CallingConv::ID CalleeCC) {
4852   // Tail calls are possible with fastcc and ccc.
4853   auto isTailCallableCC  = [] (CallingConv::ID CC){
4854       return  CC == CallingConv::C || CC == CallingConv::Fast;
4855   };
4856   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4857     return false;
4858 
4859   // We can safely tail call both fastcc and ccc callees from a c calling
4860   // convention caller. If the caller is fastcc, we may have less stack space
4861   // than a non-fastcc caller with the same signature so disable tail-calls in
4862   // that case.
4863   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4864 }
4865 
4866 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4867     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4868     const SmallVectorImpl<ISD::OutputArg> &Outs,
4869     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4870   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4871 
4872   if (DisableSCO && !TailCallOpt) return false;
4873 
4874   // Variadic argument functions are not supported.
4875   if (isVarArg) return false;
4876 
4877   auto &Caller = DAG.getMachineFunction().getFunction();
4878   // Check that the calling conventions are compatible for tco.
4879   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4880     return false;
4881 
4882   // Caller contains any byval parameter is not supported.
4883   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4884     return false;
4885 
4886   // Callee contains any byval parameter is not supported, too.
4887   // Note: This is a quick work around, because in some cases, e.g.
4888   // caller's stack size > callee's stack size, we are still able to apply
4889   // sibling call optimization. For example, gcc is able to do SCO for caller1
4890   // in the following example, but not for caller2.
4891   //   struct test {
4892   //     long int a;
4893   //     char ary[56];
4894   //   } gTest;
4895   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4896   //     b->a = v.a;
4897   //     return 0;
4898   //   }
4899   //   void caller1(struct test a, struct test c, struct test *b) {
4900   //     callee(gTest, b); }
4901   //   void caller2(struct test *b) { callee(gTest, b); }
4902   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4903     return false;
4904 
4905   // If callee and caller use different calling conventions, we cannot pass
4906   // parameters on stack since offsets for the parameter area may be different.
4907   if (Caller.getCallingConv() != CalleeCC &&
4908       needStackSlotPassParameters(Subtarget, Outs))
4909     return false;
4910 
4911   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4912   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4913   // callee potentially have different TOC bases then we cannot tail call since
4914   // we need to restore the TOC pointer after the call.
4915   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4916   // We cannot guarantee this for indirect calls or calls to external functions.
4917   // When PC-Relative addressing is used, the concept of the TOC is no longer
4918   // applicable so this check is not required.
4919   // Check first for indirect calls.
4920   if (!Subtarget.isUsingPCRelativeCalls() &&
4921       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4922     return false;
4923 
4924   // Check if we share the TOC base.
4925   if (!Subtarget.isUsingPCRelativeCalls() &&
4926       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4927     return false;
4928 
4929   // TCO allows altering callee ABI, so we don't have to check further.
4930   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4931     return true;
4932 
4933   if (DisableSCO) return false;
4934 
4935   // If callee use the same argument list that caller is using, then we can
4936   // apply SCO on this case. If it is not, then we need to check if callee needs
4937   // stack for passing arguments.
4938   // PC Relative tail calls may not have a CallBase.
4939   // If there is no CallBase we cannot verify if we have the same argument
4940   // list so assume that we don't have the same argument list.
4941   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4942       needStackSlotPassParameters(Subtarget, Outs))
4943     return false;
4944   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4945     return false;
4946 
4947   return true;
4948 }
4949 
4950 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4951 /// for tail call optimization. Targets which want to do tail call
4952 /// optimization should implement this function.
4953 bool
4954 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4955                                                      CallingConv::ID CalleeCC,
4956                                                      bool isVarArg,
4957                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4958                                                      SelectionDAG& DAG) const {
4959   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4960     return false;
4961 
4962   // Variable argument functions are not supported.
4963   if (isVarArg)
4964     return false;
4965 
4966   MachineFunction &MF = DAG.getMachineFunction();
4967   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4968   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4969     // Functions containing by val parameters are not supported.
4970     for (unsigned i = 0; i != Ins.size(); i++) {
4971        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4972        if (Flags.isByVal()) return false;
4973     }
4974 
4975     // Non-PIC/GOT tail calls are supported.
4976     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4977       return true;
4978 
4979     // At the moment we can only do local tail calls (in same module, hidden
4980     // or protected) if we are generating PIC.
4981     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4982       return G->getGlobal()->hasHiddenVisibility()
4983           || G->getGlobal()->hasProtectedVisibility();
4984   }
4985 
4986   return false;
4987 }
4988 
4989 /// isCallCompatibleAddress - Return the immediate to use if the specified
4990 /// 32-bit value is representable in the immediate field of a BxA instruction.
4991 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4992   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4993   if (!C) return nullptr;
4994 
4995   int Addr = C->getZExtValue();
4996   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4997       SignExtend32<26>(Addr) != Addr)
4998     return nullptr;  // Top 6 bits have to be sext of immediate.
4999 
5000   return DAG
5001       .getConstant(
5002           (int)C->getZExtValue() >> 2, SDLoc(Op),
5003           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
5004       .getNode();
5005 }
5006 
5007 namespace {
5008 
5009 struct TailCallArgumentInfo {
5010   SDValue Arg;
5011   SDValue FrameIdxOp;
5012   int FrameIdx = 0;
5013 
5014   TailCallArgumentInfo() = default;
5015 };
5016 
5017 } // end anonymous namespace
5018 
5019 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5020 static void StoreTailCallArgumentsToStackSlot(
5021     SelectionDAG &DAG, SDValue Chain,
5022     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5023     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5024   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5025     SDValue Arg = TailCallArgs[i].Arg;
5026     SDValue FIN = TailCallArgs[i].FrameIdxOp;
5027     int FI = TailCallArgs[i].FrameIdx;
5028     // Store relative to framepointer.
5029     MemOpChains.push_back(DAG.getStore(
5030         Chain, dl, Arg, FIN,
5031         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
5032   }
5033 }
5034 
5035 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5036 /// the appropriate stack slot for the tail call optimized function call.
5037 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
5038                                              SDValue OldRetAddr, SDValue OldFP,
5039                                              int SPDiff, const SDLoc &dl) {
5040   if (SPDiff) {
5041     // Calculate the new stack slot for the return address.
5042     MachineFunction &MF = DAG.getMachineFunction();
5043     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5044     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5045     bool isPPC64 = Subtarget.isPPC64();
5046     int SlotSize = isPPC64 ? 8 : 4;
5047     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5048     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5049                                                          NewRetAddrLoc, true);
5050     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5051     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5052     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5053                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5054   }
5055   return Chain;
5056 }
5057 
5058 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5059 /// the position of the argument.
5060 static void
5061 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5062                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5063                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5064   int Offset = ArgOffset + SPDiff;
5065   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5066   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5067   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5068   SDValue FIN = DAG.getFrameIndex(FI, VT);
5069   TailCallArgumentInfo Info;
5070   Info.Arg = Arg;
5071   Info.FrameIdxOp = FIN;
5072   Info.FrameIdx = FI;
5073   TailCallArguments.push_back(Info);
5074 }
5075 
5076 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5077 /// stack slot. Returns the chain as result and the loaded frame pointers in
5078 /// LROpOut/FPOpout. Used when tail calling.
5079 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5080     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5081     SDValue &FPOpOut, const SDLoc &dl) const {
5082   if (SPDiff) {
5083     // Load the LR and FP stack slot for later adjusting.
5084     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5085     LROpOut = getReturnAddrFrameIndex(DAG);
5086     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5087     Chain = SDValue(LROpOut.getNode(), 1);
5088   }
5089   return Chain;
5090 }
5091 
5092 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5093 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5094 /// specified by the specific parameter attribute. The copy will be passed as
5095 /// a byval function parameter.
5096 /// Sometimes what we are copying is the end of a larger object, the part that
5097 /// does not fit in registers.
5098 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5099                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5100                                          SelectionDAG &DAG, const SDLoc &dl) {
5101   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5102   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5103                        Flags.getNonZeroByValAlign(), false, false, false,
5104                        MachinePointerInfo(), MachinePointerInfo());
5105 }
5106 
5107 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5108 /// tail calls.
5109 static void LowerMemOpCallTo(
5110     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5111     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5112     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5113     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5114   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5115   if (!isTailCall) {
5116     if (isVector) {
5117       SDValue StackPtr;
5118       if (isPPC64)
5119         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5120       else
5121         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5122       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5123                            DAG.getConstant(ArgOffset, dl, PtrVT));
5124     }
5125     MemOpChains.push_back(
5126         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5127     // Calculate and remember argument location.
5128   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5129                                   TailCallArguments);
5130 }
5131 
5132 static void
5133 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5134                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5135                 SDValue FPOp,
5136                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5137   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5138   // might overwrite each other in case of tail call optimization.
5139   SmallVector<SDValue, 8> MemOpChains2;
5140   // Do not flag preceding copytoreg stuff together with the following stuff.
5141   InFlag = SDValue();
5142   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5143                                     MemOpChains2, dl);
5144   if (!MemOpChains2.empty())
5145     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5146 
5147   // Store the return address to the appropriate stack slot.
5148   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5149 
5150   // Emit callseq_end just before tailcall node.
5151   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5152                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5153   InFlag = Chain.getValue(1);
5154 }
5155 
5156 // Is this global address that of a function that can be called by name? (as
5157 // opposed to something that must hold a descriptor for an indirect call).
5158 static bool isFunctionGlobalAddress(SDValue Callee) {
5159   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5160     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5161         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5162       return false;
5163 
5164     return G->getGlobal()->getValueType()->isFunctionTy();
5165   }
5166 
5167   return false;
5168 }
5169 
5170 SDValue PPCTargetLowering::LowerCallResult(
5171     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5172     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5173     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5174   SmallVector<CCValAssign, 16> RVLocs;
5175   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5176                     *DAG.getContext());
5177 
5178   CCRetInfo.AnalyzeCallResult(
5179       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5180                ? RetCC_PPC_Cold
5181                : RetCC_PPC);
5182 
5183   // Copy all of the result registers out of their specified physreg.
5184   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5185     CCValAssign &VA = RVLocs[i];
5186     assert(VA.isRegLoc() && "Can only return in registers!");
5187 
5188     SDValue Val;
5189 
5190     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5191       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5192                                       InFlag);
5193       Chain = Lo.getValue(1);
5194       InFlag = Lo.getValue(2);
5195       VA = RVLocs[++i]; // skip ahead to next loc
5196       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5197                                       InFlag);
5198       Chain = Hi.getValue(1);
5199       InFlag = Hi.getValue(2);
5200       if (!Subtarget.isLittleEndian())
5201         std::swap (Lo, Hi);
5202       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5203     } else {
5204       Val = DAG.getCopyFromReg(Chain, dl,
5205                                VA.getLocReg(), VA.getLocVT(), InFlag);
5206       Chain = Val.getValue(1);
5207       InFlag = Val.getValue(2);
5208     }
5209 
5210     switch (VA.getLocInfo()) {
5211     default: llvm_unreachable("Unknown loc info!");
5212     case CCValAssign::Full: break;
5213     case CCValAssign::AExt:
5214       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5215       break;
5216     case CCValAssign::ZExt:
5217       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5218                         DAG.getValueType(VA.getValVT()));
5219       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5220       break;
5221     case CCValAssign::SExt:
5222       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5223                         DAG.getValueType(VA.getValVT()));
5224       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5225       break;
5226     }
5227 
5228     InVals.push_back(Val);
5229   }
5230 
5231   return Chain;
5232 }
5233 
5234 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5235                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5236   // PatchPoint calls are not indirect.
5237   if (isPatchPoint)
5238     return false;
5239 
5240   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5241     return false;
5242 
5243   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5244   // becuase the immediate function pointer points to a descriptor instead of
5245   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5246   // pointer immediate points to the global entry point, while the BLA would
5247   // need to jump to the local entry point (see rL211174).
5248   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5249       isBLACompatibleAddress(Callee, DAG))
5250     return false;
5251 
5252   return true;
5253 }
5254 
5255 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5256 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5257   return Subtarget.isAIXABI() ||
5258          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5259 }
5260 
5261 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5262                               const Function &Caller,
5263                               const SDValue &Callee,
5264                               const PPCSubtarget &Subtarget,
5265                               const TargetMachine &TM) {
5266   if (CFlags.IsTailCall)
5267     return PPCISD::TC_RETURN;
5268 
5269   // This is a call through a function pointer.
5270   if (CFlags.IsIndirect) {
5271     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5272     // indirect calls. The save of the caller's TOC pointer to the stack will be
5273     // inserted into the DAG as part of call lowering. The restore of the TOC
5274     // pointer is modeled by using a pseudo instruction for the call opcode that
5275     // represents the 2 instruction sequence of an indirect branch and link,
5276     // immediately followed by a load of the TOC pointer from the the stack save
5277     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5278     // as it is not saved or used.
5279     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5280                                                : PPCISD::BCTRL;
5281   }
5282 
5283   if (Subtarget.isUsingPCRelativeCalls()) {
5284     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5285     return PPCISD::CALL_NOTOC;
5286   }
5287 
5288   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5289   // immediately following the call instruction if the caller and callee may
5290   // have different TOC bases. At link time if the linker determines the calls
5291   // may not share a TOC base, the call is redirected to a trampoline inserted
5292   // by the linker. The trampoline will (among other things) save the callers
5293   // TOC pointer at an ABI designated offset in the linkage area and the linker
5294   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5295   // into gpr2.
5296   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5297     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5298                                                   : PPCISD::CALL_NOP;
5299 
5300   return PPCISD::CALL;
5301 }
5302 
5303 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5304                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5305   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5306     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5307       return SDValue(Dest, 0);
5308 
5309   // Returns true if the callee is local, and false otherwise.
5310   auto isLocalCallee = [&]() {
5311     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5312     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5313     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5314 
5315     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5316            !dyn_cast_or_null<GlobalIFunc>(GV);
5317   };
5318 
5319   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5320   // a static relocation model causes some versions of GNU LD (2.17.50, at
5321   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5322   // built with secure-PLT.
5323   bool UsePlt =
5324       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5325       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5326 
5327   // On AIX, direct function calls reference the symbol for the function's
5328   // entry point, which is named by prepending a "." before the function's
5329   // C-linkage name.
5330   const auto getAIXFuncEntryPointSymbolSDNode =
5331       [&](StringRef FuncName, bool IsDeclaration,
5332           const XCOFF::StorageClass &SC) {
5333         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5334 
5335         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5336             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5337 
5338         if (IsDeclaration && !S->hasRepresentedCsectSet()) {
5339           // On AIX, an undefined symbol needs to be associated with a
5340           // MCSectionXCOFF to get the correct storage mapping class.
5341           // In this case, XCOFF::XMC_PR.
5342           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5343               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5344               SectionKind::getMetadata());
5345           S->setRepresentedCsect(Sec);
5346         }
5347 
5348         MVT PtrVT =
5349             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5350         return DAG.getMCSymbol(S, PtrVT);
5351       };
5352 
5353   if (isFunctionGlobalAddress(Callee)) {
5354     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5355     const GlobalValue *GV = G->getGlobal();
5356 
5357     if (!Subtarget.isAIXABI())
5358       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5359                                         UsePlt ? PPCII::MO_PLT : 0);
5360 
5361     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5362     const GlobalObject *GO = cast<GlobalObject>(GV);
5363     const XCOFF::StorageClass SC =
5364         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5365     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5366                                             SC);
5367   }
5368 
5369   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5370     const char *SymName = S->getSymbol();
5371     if (!Subtarget.isAIXABI())
5372       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5373                                          UsePlt ? PPCII::MO_PLT : 0);
5374 
5375     // If there exists a user-declared function whose name is the same as the
5376     // ExternalSymbol's, then we pick up the user-declared version.
5377     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5378     if (const Function *F =
5379             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5380       const XCOFF::StorageClass SC =
5381           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5382       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5383                                               SC);
5384     }
5385 
5386     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5387   }
5388 
5389   // No transformation needed.
5390   assert(Callee.getNode() && "What no callee?");
5391   return Callee;
5392 }
5393 
5394 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5395   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5396          "Expected a CALLSEQ_STARTSDNode.");
5397 
5398   // The last operand is the chain, except when the node has glue. If the node
5399   // has glue, then the last operand is the glue, and the chain is the second
5400   // last operand.
5401   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5402   if (LastValue.getValueType() != MVT::Glue)
5403     return LastValue;
5404 
5405   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5406 }
5407 
5408 // Creates the node that moves a functions address into the count register
5409 // to prepare for an indirect call instruction.
5410 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5411                                 SDValue &Glue, SDValue &Chain,
5412                                 const SDLoc &dl) {
5413   SDValue MTCTROps[] = {Chain, Callee, Glue};
5414   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5415   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5416                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5417   // The glue is the second value produced.
5418   Glue = Chain.getValue(1);
5419 }
5420 
5421 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5422                                           SDValue &Glue, SDValue &Chain,
5423                                           SDValue CallSeqStart,
5424                                           const CallBase *CB, const SDLoc &dl,
5425                                           bool hasNest,
5426                                           const PPCSubtarget &Subtarget) {
5427   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5428   // entry point, but to the function descriptor (the function entry point
5429   // address is part of the function descriptor though).
5430   // The function descriptor is a three doubleword structure with the
5431   // following fields: function entry point, TOC base address and
5432   // environment pointer.
5433   // Thus for a call through a function pointer, the following actions need
5434   // to be performed:
5435   //   1. Save the TOC of the caller in the TOC save area of its stack
5436   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5437   //   2. Load the address of the function entry point from the function
5438   //      descriptor.
5439   //   3. Load the TOC of the callee from the function descriptor into r2.
5440   //   4. Load the environment pointer from the function descriptor into
5441   //      r11.
5442   //   5. Branch to the function entry point address.
5443   //   6. On return of the callee, the TOC of the caller needs to be
5444   //      restored (this is done in FinishCall()).
5445   //
5446   // The loads are scheduled at the beginning of the call sequence, and the
5447   // register copies are flagged together to ensure that no other
5448   // operations can be scheduled in between. E.g. without flagging the
5449   // copies together, a TOC access in the caller could be scheduled between
5450   // the assignment of the callee TOC and the branch to the callee, which leads
5451   // to incorrect code.
5452 
5453   // Start by loading the function address from the descriptor.
5454   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5455   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5456                       ? (MachineMemOperand::MODereferenceable |
5457                          MachineMemOperand::MOInvariant)
5458                       : MachineMemOperand::MONone;
5459 
5460   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5461 
5462   // Registers used in building the DAG.
5463   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5464   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5465 
5466   // Offsets of descriptor members.
5467   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5468   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5469 
5470   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5471   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5472 
5473   // One load for the functions entry point address.
5474   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5475                                     Alignment, MMOFlags);
5476 
5477   // One for loading the TOC anchor for the module that contains the called
5478   // function.
5479   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5480   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5481   SDValue TOCPtr =
5482       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5483                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5484 
5485   // One for loading the environment pointer.
5486   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5487   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5488   SDValue LoadEnvPtr =
5489       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5490                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5491 
5492 
5493   // Then copy the newly loaded TOC anchor to the TOC pointer.
5494   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5495   Chain = TOCVal.getValue(0);
5496   Glue = TOCVal.getValue(1);
5497 
5498   // If the function call has an explicit 'nest' parameter, it takes the
5499   // place of the environment pointer.
5500   assert((!hasNest || !Subtarget.isAIXABI()) &&
5501          "Nest parameter is not supported on AIX.");
5502   if (!hasNest) {
5503     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5504     Chain = EnvVal.getValue(0);
5505     Glue = EnvVal.getValue(1);
5506   }
5507 
5508   // The rest of the indirect call sequence is the same as the non-descriptor
5509   // DAG.
5510   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5511 }
5512 
5513 static void
5514 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5515                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5516                   SelectionDAG &DAG,
5517                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5518                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5519                   const PPCSubtarget &Subtarget) {
5520   const bool IsPPC64 = Subtarget.isPPC64();
5521   // MVT for a general purpose register.
5522   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5523 
5524   // First operand is always the chain.
5525   Ops.push_back(Chain);
5526 
5527   // If it's a direct call pass the callee as the second operand.
5528   if (!CFlags.IsIndirect)
5529     Ops.push_back(Callee);
5530   else {
5531     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5532 
5533     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5534     // on the stack (this would have been done in `LowerCall_64SVR4` or
5535     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5536     // represents both the indirect branch and a load that restores the TOC
5537     // pointer from the linkage area. The operand for the TOC restore is an add
5538     // of the TOC save offset to the stack pointer. This must be the second
5539     // operand: after the chain input but before any other variadic arguments.
5540     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5541     // saved or used.
5542     if (isTOCSaveRestoreRequired(Subtarget)) {
5543       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5544 
5545       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5546       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5547       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5548       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5549       Ops.push_back(AddTOC);
5550     }
5551 
5552     // Add the register used for the environment pointer.
5553     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5554       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5555                                     RegVT));
5556 
5557 
5558     // Add CTR register as callee so a bctr can be emitted later.
5559     if (CFlags.IsTailCall)
5560       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5561   }
5562 
5563   // If this is a tail call add stack pointer delta.
5564   if (CFlags.IsTailCall)
5565     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5566 
5567   // Add argument registers to the end of the list so that they are known live
5568   // into the call.
5569   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5570     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5571                                   RegsToPass[i].second.getValueType()));
5572 
5573   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5574   // no way to mark dependencies as implicit here.
5575   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5576   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5577        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5578     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5579 
5580   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5581   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5582     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5583 
5584   // Add a register mask operand representing the call-preserved registers.
5585   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5586   const uint32_t *Mask =
5587       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5588   assert(Mask && "Missing call preserved mask for calling convention");
5589   Ops.push_back(DAG.getRegisterMask(Mask));
5590 
5591   // If the glue is valid, it is the last operand.
5592   if (Glue.getNode())
5593     Ops.push_back(Glue);
5594 }
5595 
5596 SDValue PPCTargetLowering::FinishCall(
5597     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5598     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5599     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5600     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5601     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5602 
5603   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5604       Subtarget.isAIXABI())
5605     setUsesTOCBasePtr(DAG);
5606 
5607   unsigned CallOpc =
5608       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5609                     Subtarget, DAG.getTarget());
5610 
5611   if (!CFlags.IsIndirect)
5612     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5613   else if (Subtarget.usesFunctionDescriptors())
5614     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5615                                   dl, CFlags.HasNest, Subtarget);
5616   else
5617     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5618 
5619   // Build the operand list for the call instruction.
5620   SmallVector<SDValue, 8> Ops;
5621   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5622                     SPDiff, Subtarget);
5623 
5624   // Emit tail call.
5625   if (CFlags.IsTailCall) {
5626     // Indirect tail call when using PC Relative calls do not have the same
5627     // constraints.
5628     assert(((Callee.getOpcode() == ISD::Register &&
5629              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5630             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5631             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5632             isa<ConstantSDNode>(Callee) ||
5633             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5634            "Expecting a global address, external symbol, absolute value, "
5635            "register or an indirect tail call when PC Relative calls are "
5636            "used.");
5637     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5638     assert(CallOpc == PPCISD::TC_RETURN &&
5639            "Unexpected call opcode for a tail call.");
5640     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5641     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5642   }
5643 
5644   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5645   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5646   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5647   Glue = Chain.getValue(1);
5648 
5649   // When performing tail call optimization the callee pops its arguments off
5650   // the stack. Account for this here so these bytes can be pushed back on in
5651   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5652   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5653                          getTargetMachine().Options.GuaranteedTailCallOpt)
5654                             ? NumBytes
5655                             : 0;
5656 
5657   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5658                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5659                              Glue, dl);
5660   Glue = Chain.getValue(1);
5661 
5662   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5663                          DAG, InVals);
5664 }
5665 
5666 SDValue
5667 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5668                              SmallVectorImpl<SDValue> &InVals) const {
5669   SelectionDAG &DAG                     = CLI.DAG;
5670   SDLoc &dl                             = CLI.DL;
5671   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5672   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5673   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5674   SDValue Chain                         = CLI.Chain;
5675   SDValue Callee                        = CLI.Callee;
5676   bool &isTailCall                      = CLI.IsTailCall;
5677   CallingConv::ID CallConv              = CLI.CallConv;
5678   bool isVarArg                         = CLI.IsVarArg;
5679   bool isPatchPoint                     = CLI.IsPatchPoint;
5680   const CallBase *CB                    = CLI.CB;
5681 
5682   if (isTailCall) {
5683     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5684       isTailCall = false;
5685     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5686       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5687           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5688     else
5689       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5690                                                      Ins, DAG);
5691     if (isTailCall) {
5692       ++NumTailCalls;
5693       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5694         ++NumSiblingCalls;
5695 
5696       // PC Relative calls no longer guarantee that the callee is a Global
5697       // Address Node. The callee could be an indirect tail call in which
5698       // case the SDValue for the callee could be a load (to load the address
5699       // of a function pointer) or it may be a register copy (to move the
5700       // address of the callee from a function parameter into a virtual
5701       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5702       assert((Subtarget.isUsingPCRelativeCalls() ||
5703               isa<GlobalAddressSDNode>(Callee)) &&
5704              "Callee should be an llvm::Function object.");
5705 
5706       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5707                         << "\nTCO callee: ");
5708       LLVM_DEBUG(Callee.dump());
5709     }
5710   }
5711 
5712   if (!isTailCall && CB && CB->isMustTailCall())
5713     report_fatal_error("failed to perform tail call elimination on a call "
5714                        "site marked musttail");
5715 
5716   // When long calls (i.e. indirect calls) are always used, calls are always
5717   // made via function pointer. If we have a function name, first translate it
5718   // into a pointer.
5719   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5720       !isTailCall)
5721     Callee = LowerGlobalAddress(Callee, DAG);
5722 
5723   CallFlags CFlags(
5724       CallConv, isTailCall, isVarArg, isPatchPoint,
5725       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5726       // hasNest
5727       Subtarget.is64BitELFABI() &&
5728           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5729       CLI.NoMerge);
5730 
5731   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5732     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5733                             InVals, CB);
5734 
5735   if (Subtarget.isSVR4ABI())
5736     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5737                             InVals, CB);
5738 
5739   if (Subtarget.isAIXABI())
5740     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5741                          InVals, CB);
5742 
5743   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5744                           InVals, CB);
5745 }
5746 
5747 SDValue PPCTargetLowering::LowerCall_32SVR4(
5748     SDValue Chain, SDValue Callee, CallFlags CFlags,
5749     const SmallVectorImpl<ISD::OutputArg> &Outs,
5750     const SmallVectorImpl<SDValue> &OutVals,
5751     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5752     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5753     const CallBase *CB) const {
5754   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5755   // of the 32-bit SVR4 ABI stack frame layout.
5756 
5757   const CallingConv::ID CallConv = CFlags.CallConv;
5758   const bool IsVarArg = CFlags.IsVarArg;
5759   const bool IsTailCall = CFlags.IsTailCall;
5760 
5761   assert((CallConv == CallingConv::C ||
5762           CallConv == CallingConv::Cold ||
5763           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5764 
5765   const Align PtrAlign(4);
5766 
5767   MachineFunction &MF = DAG.getMachineFunction();
5768 
5769   // Mark this function as potentially containing a function that contains a
5770   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5771   // and restoring the callers stack pointer in this functions epilog. This is
5772   // done because by tail calling the called function might overwrite the value
5773   // in this function's (MF) stack pointer stack slot 0(SP).
5774   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5775       CallConv == CallingConv::Fast)
5776     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5777 
5778   // Count how many bytes are to be pushed on the stack, including the linkage
5779   // area, parameter list area and the part of the local variable space which
5780   // contains copies of aggregates which are passed by value.
5781 
5782   // Assign locations to all of the outgoing arguments.
5783   SmallVector<CCValAssign, 16> ArgLocs;
5784   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5785 
5786   // Reserve space for the linkage area on the stack.
5787   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5788                        PtrAlign);
5789   if (useSoftFloat())
5790     CCInfo.PreAnalyzeCallOperands(Outs);
5791 
5792   if (IsVarArg) {
5793     // Handle fixed and variable vector arguments differently.
5794     // Fixed vector arguments go into registers as long as registers are
5795     // available. Variable vector arguments always go into memory.
5796     unsigned NumArgs = Outs.size();
5797 
5798     for (unsigned i = 0; i != NumArgs; ++i) {
5799       MVT ArgVT = Outs[i].VT;
5800       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5801       bool Result;
5802 
5803       if (Outs[i].IsFixed) {
5804         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5805                                CCInfo);
5806       } else {
5807         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5808                                       ArgFlags, CCInfo);
5809       }
5810 
5811       if (Result) {
5812 #ifndef NDEBUG
5813         errs() << "Call operand #" << i << " has unhandled type "
5814              << EVT(ArgVT).getEVTString() << "\n";
5815 #endif
5816         llvm_unreachable(nullptr);
5817       }
5818     }
5819   } else {
5820     // All arguments are treated the same.
5821     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5822   }
5823   CCInfo.clearWasPPCF128();
5824 
5825   // Assign locations to all of the outgoing aggregate by value arguments.
5826   SmallVector<CCValAssign, 16> ByValArgLocs;
5827   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5828 
5829   // Reserve stack space for the allocations in CCInfo.
5830   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5831 
5832   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5833 
5834   // Size of the linkage area, parameter list area and the part of the local
5835   // space variable where copies of aggregates which are passed by value are
5836   // stored.
5837   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5838 
5839   // Calculate by how many bytes the stack has to be adjusted in case of tail
5840   // call optimization.
5841   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5842 
5843   // Adjust the stack pointer for the new arguments...
5844   // These operations are automatically eliminated by the prolog/epilog pass
5845   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5846   SDValue CallSeqStart = Chain;
5847 
5848   // Load the return address and frame pointer so it can be moved somewhere else
5849   // later.
5850   SDValue LROp, FPOp;
5851   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5852 
5853   // Set up a copy of the stack pointer for use loading and storing any
5854   // arguments that may not fit in the registers available for argument
5855   // passing.
5856   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5857 
5858   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5859   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5860   SmallVector<SDValue, 8> MemOpChains;
5861 
5862   bool seenFloatArg = false;
5863   // Walk the register/memloc assignments, inserting copies/loads.
5864   // i - Tracks the index into the list of registers allocated for the call
5865   // RealArgIdx - Tracks the index into the list of actual function arguments
5866   // j - Tracks the index into the list of byval arguments
5867   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5868        i != e;
5869        ++i, ++RealArgIdx) {
5870     CCValAssign &VA = ArgLocs[i];
5871     SDValue Arg = OutVals[RealArgIdx];
5872     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5873 
5874     if (Flags.isByVal()) {
5875       // Argument is an aggregate which is passed by value, thus we need to
5876       // create a copy of it in the local variable space of the current stack
5877       // frame (which is the stack frame of the caller) and pass the address of
5878       // this copy to the callee.
5879       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5880       CCValAssign &ByValVA = ByValArgLocs[j++];
5881       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5882 
5883       // Memory reserved in the local variable space of the callers stack frame.
5884       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5885 
5886       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5887       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5888                            StackPtr, PtrOff);
5889 
5890       // Create a copy of the argument in the local area of the current
5891       // stack frame.
5892       SDValue MemcpyCall =
5893         CreateCopyOfByValArgument(Arg, PtrOff,
5894                                   CallSeqStart.getNode()->getOperand(0),
5895                                   Flags, DAG, dl);
5896 
5897       // This must go outside the CALLSEQ_START..END.
5898       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5899                                                      SDLoc(MemcpyCall));
5900       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5901                              NewCallSeqStart.getNode());
5902       Chain = CallSeqStart = NewCallSeqStart;
5903 
5904       // Pass the address of the aggregate copy on the stack either in a
5905       // physical register or in the parameter list area of the current stack
5906       // frame to the callee.
5907       Arg = PtrOff;
5908     }
5909 
5910     // When useCRBits() is true, there can be i1 arguments.
5911     // It is because getRegisterType(MVT::i1) => MVT::i1,
5912     // and for other integer types getRegisterType() => MVT::i32.
5913     // Extend i1 and ensure callee will get i32.
5914     if (Arg.getValueType() == MVT::i1)
5915       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5916                         dl, MVT::i32, Arg);
5917 
5918     if (VA.isRegLoc()) {
5919       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5920       // Put argument in a physical register.
5921       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5922         bool IsLE = Subtarget.isLittleEndian();
5923         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5924                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5925         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5926         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5927                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5928         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5929                              SVal.getValue(0)));
5930       } else
5931         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5932     } else {
5933       // Put argument in the parameter list area of the current stack frame.
5934       assert(VA.isMemLoc());
5935       unsigned LocMemOffset = VA.getLocMemOffset();
5936 
5937       if (!IsTailCall) {
5938         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5939         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5940                              StackPtr, PtrOff);
5941 
5942         MemOpChains.push_back(
5943             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5944       } else {
5945         // Calculate and remember argument location.
5946         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5947                                  TailCallArguments);
5948       }
5949     }
5950   }
5951 
5952   if (!MemOpChains.empty())
5953     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5954 
5955   // Build a sequence of copy-to-reg nodes chained together with token chain
5956   // and flag operands which copy the outgoing args into the appropriate regs.
5957   SDValue InFlag;
5958   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5959     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5960                              RegsToPass[i].second, InFlag);
5961     InFlag = Chain.getValue(1);
5962   }
5963 
5964   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5965   // registers.
5966   if (IsVarArg) {
5967     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5968     SDValue Ops[] = { Chain, InFlag };
5969 
5970     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5971                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5972 
5973     InFlag = Chain.getValue(1);
5974   }
5975 
5976   if (IsTailCall)
5977     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5978                     TailCallArguments);
5979 
5980   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5981                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5982 }
5983 
5984 // Copy an argument into memory, being careful to do this outside the
5985 // call sequence for the call to which the argument belongs.
5986 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5987     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5988     SelectionDAG &DAG, const SDLoc &dl) const {
5989   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5990                         CallSeqStart.getNode()->getOperand(0),
5991                         Flags, DAG, dl);
5992   // The MEMCPY must go outside the CALLSEQ_START..END.
5993   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5994   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5995                                                  SDLoc(MemcpyCall));
5996   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5997                          NewCallSeqStart.getNode());
5998   return NewCallSeqStart;
5999 }
6000 
6001 SDValue PPCTargetLowering::LowerCall_64SVR4(
6002     SDValue Chain, SDValue Callee, CallFlags CFlags,
6003     const SmallVectorImpl<ISD::OutputArg> &Outs,
6004     const SmallVectorImpl<SDValue> &OutVals,
6005     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6006     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6007     const CallBase *CB) const {
6008   bool isELFv2ABI = Subtarget.isELFv2ABI();
6009   bool isLittleEndian = Subtarget.isLittleEndian();
6010   unsigned NumOps = Outs.size();
6011   bool IsSibCall = false;
6012   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
6013 
6014   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6015   unsigned PtrByteSize = 8;
6016 
6017   MachineFunction &MF = DAG.getMachineFunction();
6018 
6019   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6020     IsSibCall = true;
6021 
6022   // Mark this function as potentially containing a function that contains a
6023   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6024   // and restoring the callers stack pointer in this functions epilog. This is
6025   // done because by tail calling the called function might overwrite the value
6026   // in this function's (MF) stack pointer stack slot 0(SP).
6027   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6028     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6029 
6030   assert(!(IsFastCall && CFlags.IsVarArg) &&
6031          "fastcc not supported on varargs functions");
6032 
6033   // Count how many bytes are to be pushed on the stack, including the linkage
6034   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
6035   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6036   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6037   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6038   unsigned NumBytes = LinkageSize;
6039   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6040   unsigned &QFPR_idx = FPR_idx;
6041 
6042   static const MCPhysReg GPR[] = {
6043     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6044     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6045   };
6046   static const MCPhysReg VR[] = {
6047     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6048     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6049   };
6050 
6051   const unsigned NumGPRs = array_lengthof(GPR);
6052   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6053   const unsigned NumVRs  = array_lengthof(VR);
6054   const unsigned NumQFPRs = NumFPRs;
6055 
6056   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6057   // can be passed to the callee in registers.
6058   // For the fast calling convention, there is another check below.
6059   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6060   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6061   if (!HasParameterArea) {
6062     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6063     unsigned AvailableFPRs = NumFPRs;
6064     unsigned AvailableVRs = NumVRs;
6065     unsigned NumBytesTmp = NumBytes;
6066     for (unsigned i = 0; i != NumOps; ++i) {
6067       if (Outs[i].Flags.isNest()) continue;
6068       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6069                                 PtrByteSize, LinkageSize, ParamAreaSize,
6070                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
6071                                 Subtarget.hasQPX()))
6072         HasParameterArea = true;
6073     }
6074   }
6075 
6076   // When using the fast calling convention, we don't provide backing for
6077   // arguments that will be in registers.
6078   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6079 
6080   // Avoid allocating parameter area for fastcc functions if all the arguments
6081   // can be passed in the registers.
6082   if (IsFastCall)
6083     HasParameterArea = false;
6084 
6085   // Add up all the space actually used.
6086   for (unsigned i = 0; i != NumOps; ++i) {
6087     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6088     EVT ArgVT = Outs[i].VT;
6089     EVT OrigVT = Outs[i].ArgVT;
6090 
6091     if (Flags.isNest())
6092       continue;
6093 
6094     if (IsFastCall) {
6095       if (Flags.isByVal()) {
6096         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6097         if (NumGPRsUsed > NumGPRs)
6098           HasParameterArea = true;
6099       } else {
6100         switch (ArgVT.getSimpleVT().SimpleTy) {
6101         default: llvm_unreachable("Unexpected ValueType for argument!");
6102         case MVT::i1:
6103         case MVT::i32:
6104         case MVT::i64:
6105           if (++NumGPRsUsed <= NumGPRs)
6106             continue;
6107           break;
6108         case MVT::v4i32:
6109         case MVT::v8i16:
6110         case MVT::v16i8:
6111         case MVT::v2f64:
6112         case MVT::v2i64:
6113         case MVT::v1i128:
6114         case MVT::f128:
6115           if (++NumVRsUsed <= NumVRs)
6116             continue;
6117           break;
6118         case MVT::v4f32:
6119           // When using QPX, this is handled like a FP register, otherwise, it
6120           // is an Altivec register.
6121           if (Subtarget.hasQPX()) {
6122             if (++NumFPRsUsed <= NumFPRs)
6123               continue;
6124           } else {
6125             if (++NumVRsUsed <= NumVRs)
6126               continue;
6127           }
6128           break;
6129         case MVT::f32:
6130         case MVT::f64:
6131         case MVT::v4f64: // QPX
6132         case MVT::v4i1:  // QPX
6133           if (++NumFPRsUsed <= NumFPRs)
6134             continue;
6135           break;
6136         }
6137         HasParameterArea = true;
6138       }
6139     }
6140 
6141     /* Respect alignment of argument on the stack.  */
6142     auto Alignement =
6143         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6144     NumBytes = alignTo(NumBytes, Alignement);
6145 
6146     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6147     if (Flags.isInConsecutiveRegsLast())
6148       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6149   }
6150 
6151   unsigned NumBytesActuallyUsed = NumBytes;
6152 
6153   // In the old ELFv1 ABI,
6154   // the prolog code of the callee may store up to 8 GPR argument registers to
6155   // the stack, allowing va_start to index over them in memory if its varargs.
6156   // Because we cannot tell if this is needed on the caller side, we have to
6157   // conservatively assume that it is needed.  As such, make sure we have at
6158   // least enough stack space for the caller to store the 8 GPRs.
6159   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6160   // really requires memory operands, e.g. a vararg function.
6161   if (HasParameterArea)
6162     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6163   else
6164     NumBytes = LinkageSize;
6165 
6166   // Tail call needs the stack to be aligned.
6167   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6168     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6169 
6170   int SPDiff = 0;
6171 
6172   // Calculate by how many bytes the stack has to be adjusted in case of tail
6173   // call optimization.
6174   if (!IsSibCall)
6175     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6176 
6177   // To protect arguments on the stack from being clobbered in a tail call,
6178   // force all the loads to happen before doing any other lowering.
6179   if (CFlags.IsTailCall)
6180     Chain = DAG.getStackArgumentTokenFactor(Chain);
6181 
6182   // Adjust the stack pointer for the new arguments...
6183   // These operations are automatically eliminated by the prolog/epilog pass
6184   if (!IsSibCall)
6185     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6186   SDValue CallSeqStart = Chain;
6187 
6188   // Load the return address and frame pointer so it can be move somewhere else
6189   // later.
6190   SDValue LROp, FPOp;
6191   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6192 
6193   // Set up a copy of the stack pointer for use loading and storing any
6194   // arguments that may not fit in the registers available for argument
6195   // passing.
6196   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6197 
6198   // Figure out which arguments are going to go in registers, and which in
6199   // memory.  Also, if this is a vararg function, floating point operations
6200   // must be stored to our stack, and loaded into integer regs as well, if
6201   // any integer regs are available for argument passing.
6202   unsigned ArgOffset = LinkageSize;
6203 
6204   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6205   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6206 
6207   SmallVector<SDValue, 8> MemOpChains;
6208   for (unsigned i = 0; i != NumOps; ++i) {
6209     SDValue Arg = OutVals[i];
6210     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6211     EVT ArgVT = Outs[i].VT;
6212     EVT OrigVT = Outs[i].ArgVT;
6213 
6214     // PtrOff will be used to store the current argument to the stack if a
6215     // register cannot be found for it.
6216     SDValue PtrOff;
6217 
6218     // We re-align the argument offset for each argument, except when using the
6219     // fast calling convention, when we need to make sure we do that only when
6220     // we'll actually use a stack slot.
6221     auto ComputePtrOff = [&]() {
6222       /* Respect alignment of argument on the stack.  */
6223       auto Alignment =
6224           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6225       ArgOffset = alignTo(ArgOffset, Alignment);
6226 
6227       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6228 
6229       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6230     };
6231 
6232     if (!IsFastCall) {
6233       ComputePtrOff();
6234 
6235       /* Compute GPR index associated with argument offset.  */
6236       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6237       GPR_idx = std::min(GPR_idx, NumGPRs);
6238     }
6239 
6240     // Promote integers to 64-bit values.
6241     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6242       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6243       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6244       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6245     }
6246 
6247     // FIXME memcpy is used way more than necessary.  Correctness first.
6248     // Note: "by value" is code for passing a structure by value, not
6249     // basic types.
6250     if (Flags.isByVal()) {
6251       // Note: Size includes alignment padding, so
6252       //   struct x { short a; char b; }
6253       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6254       // These are the proper values we need for right-justifying the
6255       // aggregate in a parameter register.
6256       unsigned Size = Flags.getByValSize();
6257 
6258       // An empty aggregate parameter takes up no storage and no
6259       // registers.
6260       if (Size == 0)
6261         continue;
6262 
6263       if (IsFastCall)
6264         ComputePtrOff();
6265 
6266       // All aggregates smaller than 8 bytes must be passed right-justified.
6267       if (Size==1 || Size==2 || Size==4) {
6268         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6269         if (GPR_idx != NumGPRs) {
6270           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6271                                         MachinePointerInfo(), VT);
6272           MemOpChains.push_back(Load.getValue(1));
6273           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6274 
6275           ArgOffset += PtrByteSize;
6276           continue;
6277         }
6278       }
6279 
6280       if (GPR_idx == NumGPRs && Size < 8) {
6281         SDValue AddPtr = PtrOff;
6282         if (!isLittleEndian) {
6283           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6284                                           PtrOff.getValueType());
6285           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6286         }
6287         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6288                                                           CallSeqStart,
6289                                                           Flags, DAG, dl);
6290         ArgOffset += PtrByteSize;
6291         continue;
6292       }
6293       // Copy entire object into memory.  There are cases where gcc-generated
6294       // code assumes it is there, even if it could be put entirely into
6295       // registers.  (This is not what the doc says.)
6296 
6297       // FIXME: The above statement is likely due to a misunderstanding of the
6298       // documents.  All arguments must be copied into the parameter area BY
6299       // THE CALLEE in the event that the callee takes the address of any
6300       // formal argument.  That has not yet been implemented.  However, it is
6301       // reasonable to use the stack area as a staging area for the register
6302       // load.
6303 
6304       // Skip this for small aggregates, as we will use the same slot for a
6305       // right-justified copy, below.
6306       if (Size >= 8)
6307         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6308                                                           CallSeqStart,
6309                                                           Flags, DAG, dl);
6310 
6311       // When a register is available, pass a small aggregate right-justified.
6312       if (Size < 8 && GPR_idx != NumGPRs) {
6313         // The easiest way to get this right-justified in a register
6314         // is to copy the structure into the rightmost portion of a
6315         // local variable slot, then load the whole slot into the
6316         // register.
6317         // FIXME: The memcpy seems to produce pretty awful code for
6318         // small aggregates, particularly for packed ones.
6319         // FIXME: It would be preferable to use the slot in the
6320         // parameter save area instead of a new local variable.
6321         SDValue AddPtr = PtrOff;
6322         if (!isLittleEndian) {
6323           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6324           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6325         }
6326         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6327                                                           CallSeqStart,
6328                                                           Flags, DAG, dl);
6329 
6330         // Load the slot into the register.
6331         SDValue Load =
6332             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6333         MemOpChains.push_back(Load.getValue(1));
6334         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6335 
6336         // Done with this argument.
6337         ArgOffset += PtrByteSize;
6338         continue;
6339       }
6340 
6341       // For aggregates larger than PtrByteSize, copy the pieces of the
6342       // object that fit into registers from the parameter save area.
6343       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6344         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6345         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6346         if (GPR_idx != NumGPRs) {
6347           SDValue Load =
6348               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6349           MemOpChains.push_back(Load.getValue(1));
6350           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6351           ArgOffset += PtrByteSize;
6352         } else {
6353           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6354           break;
6355         }
6356       }
6357       continue;
6358     }
6359 
6360     switch (Arg.getSimpleValueType().SimpleTy) {
6361     default: llvm_unreachable("Unexpected ValueType for argument!");
6362     case MVT::i1:
6363     case MVT::i32:
6364     case MVT::i64:
6365       if (Flags.isNest()) {
6366         // The 'nest' parameter, if any, is passed in R11.
6367         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6368         break;
6369       }
6370 
6371       // These can be scalar arguments or elements of an integer array type
6372       // passed directly.  Clang may use those instead of "byval" aggregate
6373       // types to avoid forcing arguments to memory unnecessarily.
6374       if (GPR_idx != NumGPRs) {
6375         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6376       } else {
6377         if (IsFastCall)
6378           ComputePtrOff();
6379 
6380         assert(HasParameterArea &&
6381                "Parameter area must exist to pass an argument in memory.");
6382         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6383                          true, CFlags.IsTailCall, false, MemOpChains,
6384                          TailCallArguments, dl);
6385         if (IsFastCall)
6386           ArgOffset += PtrByteSize;
6387       }
6388       if (!IsFastCall)
6389         ArgOffset += PtrByteSize;
6390       break;
6391     case MVT::f32:
6392     case MVT::f64: {
6393       // These can be scalar arguments or elements of a float array type
6394       // passed directly.  The latter are used to implement ELFv2 homogenous
6395       // float aggregates.
6396 
6397       // Named arguments go into FPRs first, and once they overflow, the
6398       // remaining arguments go into GPRs and then the parameter save area.
6399       // Unnamed arguments for vararg functions always go to GPRs and
6400       // then the parameter save area.  For now, put all arguments to vararg
6401       // routines always in both locations (FPR *and* GPR or stack slot).
6402       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6403       bool NeededLoad = false;
6404 
6405       // First load the argument into the next available FPR.
6406       if (FPR_idx != NumFPRs)
6407         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6408 
6409       // Next, load the argument into GPR or stack slot if needed.
6410       if (!NeedGPROrStack)
6411         ;
6412       else if (GPR_idx != NumGPRs && !IsFastCall) {
6413         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6414         // once we support fp <-> gpr moves.
6415 
6416         // In the non-vararg case, this can only ever happen in the
6417         // presence of f32 array types, since otherwise we never run
6418         // out of FPRs before running out of GPRs.
6419         SDValue ArgVal;
6420 
6421         // Double values are always passed in a single GPR.
6422         if (Arg.getValueType() != MVT::f32) {
6423           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6424 
6425         // Non-array float values are extended and passed in a GPR.
6426         } else if (!Flags.isInConsecutiveRegs()) {
6427           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6428           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6429 
6430         // If we have an array of floats, we collect every odd element
6431         // together with its predecessor into one GPR.
6432         } else if (ArgOffset % PtrByteSize != 0) {
6433           SDValue Lo, Hi;
6434           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6435           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6436           if (!isLittleEndian)
6437             std::swap(Lo, Hi);
6438           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6439 
6440         // The final element, if even, goes into the first half of a GPR.
6441         } else if (Flags.isInConsecutiveRegsLast()) {
6442           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6443           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6444           if (!isLittleEndian)
6445             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6446                                  DAG.getConstant(32, dl, MVT::i32));
6447 
6448         // Non-final even elements are skipped; they will be handled
6449         // together the with subsequent argument on the next go-around.
6450         } else
6451           ArgVal = SDValue();
6452 
6453         if (ArgVal.getNode())
6454           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6455       } else {
6456         if (IsFastCall)
6457           ComputePtrOff();
6458 
6459         // Single-precision floating-point values are mapped to the
6460         // second (rightmost) word of the stack doubleword.
6461         if (Arg.getValueType() == MVT::f32 &&
6462             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6463           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6464           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6465         }
6466 
6467         assert(HasParameterArea &&
6468                "Parameter area must exist to pass an argument in memory.");
6469         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6470                          true, CFlags.IsTailCall, false, MemOpChains,
6471                          TailCallArguments, dl);
6472 
6473         NeededLoad = true;
6474       }
6475       // When passing an array of floats, the array occupies consecutive
6476       // space in the argument area; only round up to the next doubleword
6477       // at the end of the array.  Otherwise, each float takes 8 bytes.
6478       if (!IsFastCall || NeededLoad) {
6479         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6480                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6481         if (Flags.isInConsecutiveRegsLast())
6482           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6483       }
6484       break;
6485     }
6486     case MVT::v4f32:
6487     case MVT::v4i32:
6488     case MVT::v8i16:
6489     case MVT::v16i8:
6490     case MVT::v2f64:
6491     case MVT::v2i64:
6492     case MVT::v1i128:
6493     case MVT::f128:
6494       if (!Subtarget.hasQPX()) {
6495       // These can be scalar arguments or elements of a vector array type
6496       // passed directly.  The latter are used to implement ELFv2 homogenous
6497       // vector aggregates.
6498 
6499       // For a varargs call, named arguments go into VRs or on the stack as
6500       // usual; unnamed arguments always go to the stack or the corresponding
6501       // GPRs when within range.  For now, we always put the value in both
6502       // locations (or even all three).
6503       if (CFlags.IsVarArg) {
6504         assert(HasParameterArea &&
6505                "Parameter area must exist if we have a varargs call.");
6506         // We could elide this store in the case where the object fits
6507         // entirely in R registers.  Maybe later.
6508         SDValue Store =
6509             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6510         MemOpChains.push_back(Store);
6511         if (VR_idx != NumVRs) {
6512           SDValue Load =
6513               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6514           MemOpChains.push_back(Load.getValue(1));
6515           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6516         }
6517         ArgOffset += 16;
6518         for (unsigned i=0; i<16; i+=PtrByteSize) {
6519           if (GPR_idx == NumGPRs)
6520             break;
6521           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6522                                    DAG.getConstant(i, dl, PtrVT));
6523           SDValue Load =
6524               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6525           MemOpChains.push_back(Load.getValue(1));
6526           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6527         }
6528         break;
6529       }
6530 
6531       // Non-varargs Altivec params go into VRs or on the stack.
6532       if (VR_idx != NumVRs) {
6533         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6534       } else {
6535         if (IsFastCall)
6536           ComputePtrOff();
6537 
6538         assert(HasParameterArea &&
6539                "Parameter area must exist to pass an argument in memory.");
6540         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6541                          true, CFlags.IsTailCall, true, MemOpChains,
6542                          TailCallArguments, dl);
6543         if (IsFastCall)
6544           ArgOffset += 16;
6545       }
6546 
6547       if (!IsFastCall)
6548         ArgOffset += 16;
6549       break;
6550       } // not QPX
6551 
6552       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6553              "Invalid QPX parameter type");
6554 
6555       LLVM_FALLTHROUGH;
6556     case MVT::v4f64:
6557     case MVT::v4i1: {
6558       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6559       if (CFlags.IsVarArg) {
6560         assert(HasParameterArea &&
6561                "Parameter area must exist if we have a varargs call.");
6562         // We could elide this store in the case where the object fits
6563         // entirely in R registers.  Maybe later.
6564         SDValue Store =
6565             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6566         MemOpChains.push_back(Store);
6567         if (QFPR_idx != NumQFPRs) {
6568           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6569                                      PtrOff, MachinePointerInfo());
6570           MemOpChains.push_back(Load.getValue(1));
6571           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6572         }
6573         ArgOffset += (IsF32 ? 16 : 32);
6574         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6575           if (GPR_idx == NumGPRs)
6576             break;
6577           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6578                                    DAG.getConstant(i, dl, PtrVT));
6579           SDValue Load =
6580               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6581           MemOpChains.push_back(Load.getValue(1));
6582           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6583         }
6584         break;
6585       }
6586 
6587       // Non-varargs QPX params go into registers or on the stack.
6588       if (QFPR_idx != NumQFPRs) {
6589         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6590       } else {
6591         if (IsFastCall)
6592           ComputePtrOff();
6593 
6594         assert(HasParameterArea &&
6595                "Parameter area must exist to pass an argument in memory.");
6596         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6597                          true, CFlags.IsTailCall, true, MemOpChains,
6598                          TailCallArguments, dl);
6599         if (IsFastCall)
6600           ArgOffset += (IsF32 ? 16 : 32);
6601       }
6602 
6603       if (!IsFastCall)
6604         ArgOffset += (IsF32 ? 16 : 32);
6605       break;
6606       }
6607     }
6608   }
6609 
6610   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6611          "mismatch in size of parameter area");
6612   (void)NumBytesActuallyUsed;
6613 
6614   if (!MemOpChains.empty())
6615     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6616 
6617   // Check if this is an indirect call (MTCTR/BCTRL).
6618   // See prepareDescriptorIndirectCall and buildCallOperands for more
6619   // information about calls through function pointers in the 64-bit SVR4 ABI.
6620   if (CFlags.IsIndirect) {
6621     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6622     // caller in the TOC save area.
6623     if (isTOCSaveRestoreRequired(Subtarget)) {
6624       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6625       // Load r2 into a virtual register and store it to the TOC save area.
6626       setUsesTOCBasePtr(DAG);
6627       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6628       // TOC save area offset.
6629       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6630       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6631       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6632       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6633                            MachinePointerInfo::getStack(
6634                                DAG.getMachineFunction(), TOCSaveOffset));
6635     }
6636     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6637     // This does not mean the MTCTR instruction must use R12; it's easier
6638     // to model this as an extra parameter, so do that.
6639     if (isELFv2ABI && !CFlags.IsPatchPoint)
6640       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6641   }
6642 
6643   // Build a sequence of copy-to-reg nodes chained together with token chain
6644   // and flag operands which copy the outgoing args into the appropriate regs.
6645   SDValue InFlag;
6646   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6647     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6648                              RegsToPass[i].second, InFlag);
6649     InFlag = Chain.getValue(1);
6650   }
6651 
6652   if (CFlags.IsTailCall && !IsSibCall)
6653     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6654                     TailCallArguments);
6655 
6656   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6657                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6658 }
6659 
6660 SDValue PPCTargetLowering::LowerCall_Darwin(
6661     SDValue Chain, SDValue Callee, CallFlags CFlags,
6662     const SmallVectorImpl<ISD::OutputArg> &Outs,
6663     const SmallVectorImpl<SDValue> &OutVals,
6664     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6665     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6666     const CallBase *CB) const {
6667   unsigned NumOps = Outs.size();
6668 
6669   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6670   bool isPPC64 = PtrVT == MVT::i64;
6671   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6672 
6673   MachineFunction &MF = DAG.getMachineFunction();
6674 
6675   // Mark this function as potentially containing a function that contains a
6676   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6677   // and restoring the callers stack pointer in this functions epilog. This is
6678   // done because by tail calling the called function might overwrite the value
6679   // in this function's (MF) stack pointer stack slot 0(SP).
6680   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6681       CFlags.CallConv == CallingConv::Fast)
6682     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6683 
6684   // Count how many bytes are to be pushed on the stack, including the linkage
6685   // area, and parameter passing area.  We start with 24/48 bytes, which is
6686   // prereserved space for [SP][CR][LR][3 x unused].
6687   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6688   unsigned NumBytes = LinkageSize;
6689 
6690   // Add up all the space actually used.
6691   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6692   // they all go in registers, but we must reserve stack space for them for
6693   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6694   // assigned stack space in order, with padding so Altivec parameters are
6695   // 16-byte aligned.
6696   unsigned nAltivecParamsAtEnd = 0;
6697   for (unsigned i = 0; i != NumOps; ++i) {
6698     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6699     EVT ArgVT = Outs[i].VT;
6700     // Varargs Altivec parameters are padded to a 16 byte boundary.
6701     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6702         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6703         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6704       if (!CFlags.IsVarArg && !isPPC64) {
6705         // Non-varargs Altivec parameters go after all the non-Altivec
6706         // parameters; handle those later so we know how much padding we need.
6707         nAltivecParamsAtEnd++;
6708         continue;
6709       }
6710       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6711       NumBytes = ((NumBytes+15)/16)*16;
6712     }
6713     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6714   }
6715 
6716   // Allow for Altivec parameters at the end, if needed.
6717   if (nAltivecParamsAtEnd) {
6718     NumBytes = ((NumBytes+15)/16)*16;
6719     NumBytes += 16*nAltivecParamsAtEnd;
6720   }
6721 
6722   // The prolog code of the callee may store up to 8 GPR argument registers to
6723   // the stack, allowing va_start to index over them in memory if its varargs.
6724   // Because we cannot tell if this is needed on the caller side, we have to
6725   // conservatively assume that it is needed.  As such, make sure we have at
6726   // least enough stack space for the caller to store the 8 GPRs.
6727   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6728 
6729   // Tail call needs the stack to be aligned.
6730   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6731       CFlags.CallConv == CallingConv::Fast)
6732     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6733 
6734   // Calculate by how many bytes the stack has to be adjusted in case of tail
6735   // call optimization.
6736   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6737 
6738   // To protect arguments on the stack from being clobbered in a tail call,
6739   // force all the loads to happen before doing any other lowering.
6740   if (CFlags.IsTailCall)
6741     Chain = DAG.getStackArgumentTokenFactor(Chain);
6742 
6743   // Adjust the stack pointer for the new arguments...
6744   // These operations are automatically eliminated by the prolog/epilog pass
6745   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6746   SDValue CallSeqStart = Chain;
6747 
6748   // Load the return address and frame pointer so it can be move somewhere else
6749   // later.
6750   SDValue LROp, FPOp;
6751   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6752 
6753   // Set up a copy of the stack pointer for use loading and storing any
6754   // arguments that may not fit in the registers available for argument
6755   // passing.
6756   SDValue StackPtr;
6757   if (isPPC64)
6758     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6759   else
6760     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6761 
6762   // Figure out which arguments are going to go in registers, and which in
6763   // memory.  Also, if this is a vararg function, floating point operations
6764   // must be stored to our stack, and loaded into integer regs as well, if
6765   // any integer regs are available for argument passing.
6766   unsigned ArgOffset = LinkageSize;
6767   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6768 
6769   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6770     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6771     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6772   };
6773   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6774     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6775     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6776   };
6777   static const MCPhysReg VR[] = {
6778     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6779     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6780   };
6781   const unsigned NumGPRs = array_lengthof(GPR_32);
6782   const unsigned NumFPRs = 13;
6783   const unsigned NumVRs  = array_lengthof(VR);
6784 
6785   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6786 
6787   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6788   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6789 
6790   SmallVector<SDValue, 8> MemOpChains;
6791   for (unsigned i = 0; i != NumOps; ++i) {
6792     SDValue Arg = OutVals[i];
6793     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6794 
6795     // PtrOff will be used to store the current argument to the stack if a
6796     // register cannot be found for it.
6797     SDValue PtrOff;
6798 
6799     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6800 
6801     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6802 
6803     // On PPC64, promote integers to 64-bit values.
6804     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6805       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6806       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6807       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6808     }
6809 
6810     // FIXME memcpy is used way more than necessary.  Correctness first.
6811     // Note: "by value" is code for passing a structure by value, not
6812     // basic types.
6813     if (Flags.isByVal()) {
6814       unsigned Size = Flags.getByValSize();
6815       // Very small objects are passed right-justified.  Everything else is
6816       // passed left-justified.
6817       if (Size==1 || Size==2) {
6818         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6819         if (GPR_idx != NumGPRs) {
6820           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6821                                         MachinePointerInfo(), VT);
6822           MemOpChains.push_back(Load.getValue(1));
6823           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6824 
6825           ArgOffset += PtrByteSize;
6826         } else {
6827           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6828                                           PtrOff.getValueType());
6829           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6830           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6831                                                             CallSeqStart,
6832                                                             Flags, DAG, dl);
6833           ArgOffset += PtrByteSize;
6834         }
6835         continue;
6836       }
6837       // Copy entire object into memory.  There are cases where gcc-generated
6838       // code assumes it is there, even if it could be put entirely into
6839       // registers.  (This is not what the doc says.)
6840       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6841                                                         CallSeqStart,
6842                                                         Flags, DAG, dl);
6843 
6844       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6845       // copy the pieces of the object that fit into registers from the
6846       // parameter save area.
6847       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6848         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6849         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6850         if (GPR_idx != NumGPRs) {
6851           SDValue Load =
6852               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6853           MemOpChains.push_back(Load.getValue(1));
6854           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6855           ArgOffset += PtrByteSize;
6856         } else {
6857           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6858           break;
6859         }
6860       }
6861       continue;
6862     }
6863 
6864     switch (Arg.getSimpleValueType().SimpleTy) {
6865     default: llvm_unreachable("Unexpected ValueType for argument!");
6866     case MVT::i1:
6867     case MVT::i32:
6868     case MVT::i64:
6869       if (GPR_idx != NumGPRs) {
6870         if (Arg.getValueType() == MVT::i1)
6871           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6872 
6873         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6874       } else {
6875         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6876                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6877                          TailCallArguments, dl);
6878       }
6879       ArgOffset += PtrByteSize;
6880       break;
6881     case MVT::f32:
6882     case MVT::f64:
6883       if (FPR_idx != NumFPRs) {
6884         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6885 
6886         if (CFlags.IsVarArg) {
6887           SDValue Store =
6888               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6889           MemOpChains.push_back(Store);
6890 
6891           // Float varargs are always shadowed in available integer registers
6892           if (GPR_idx != NumGPRs) {
6893             SDValue Load =
6894                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6895             MemOpChains.push_back(Load.getValue(1));
6896             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6897           }
6898           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6899             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6900             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6901             SDValue Load =
6902                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6903             MemOpChains.push_back(Load.getValue(1));
6904             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6905           }
6906         } else {
6907           // If we have any FPRs remaining, we may also have GPRs remaining.
6908           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6909           // GPRs.
6910           if (GPR_idx != NumGPRs)
6911             ++GPR_idx;
6912           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6913               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6914             ++GPR_idx;
6915         }
6916       } else
6917         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6918                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6919                          TailCallArguments, dl);
6920       if (isPPC64)
6921         ArgOffset += 8;
6922       else
6923         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6924       break;
6925     case MVT::v4f32:
6926     case MVT::v4i32:
6927     case MVT::v8i16:
6928     case MVT::v16i8:
6929       if (CFlags.IsVarArg) {
6930         // These go aligned on the stack, or in the corresponding R registers
6931         // when within range.  The Darwin PPC ABI doc claims they also go in
6932         // V registers; in fact gcc does this only for arguments that are
6933         // prototyped, not for those that match the ...  We do it for all
6934         // arguments, seems to work.
6935         while (ArgOffset % 16 !=0) {
6936           ArgOffset += PtrByteSize;
6937           if (GPR_idx != NumGPRs)
6938             GPR_idx++;
6939         }
6940         // We could elide this store in the case where the object fits
6941         // entirely in R registers.  Maybe later.
6942         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6943                              DAG.getConstant(ArgOffset, dl, PtrVT));
6944         SDValue Store =
6945             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6946         MemOpChains.push_back(Store);
6947         if (VR_idx != NumVRs) {
6948           SDValue Load =
6949               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6950           MemOpChains.push_back(Load.getValue(1));
6951           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6952         }
6953         ArgOffset += 16;
6954         for (unsigned i=0; i<16; i+=PtrByteSize) {
6955           if (GPR_idx == NumGPRs)
6956             break;
6957           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6958                                    DAG.getConstant(i, dl, PtrVT));
6959           SDValue Load =
6960               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6961           MemOpChains.push_back(Load.getValue(1));
6962           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6963         }
6964         break;
6965       }
6966 
6967       // Non-varargs Altivec params generally go in registers, but have
6968       // stack space allocated at the end.
6969       if (VR_idx != NumVRs) {
6970         // Doesn't have GPR space allocated.
6971         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6972       } else if (nAltivecParamsAtEnd==0) {
6973         // We are emitting Altivec params in order.
6974         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6975                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6976                          TailCallArguments, dl);
6977         ArgOffset += 16;
6978       }
6979       break;
6980     }
6981   }
6982   // If all Altivec parameters fit in registers, as they usually do,
6983   // they get stack space following the non-Altivec parameters.  We
6984   // don't track this here because nobody below needs it.
6985   // If there are more Altivec parameters than fit in registers emit
6986   // the stores here.
6987   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6988     unsigned j = 0;
6989     // Offset is aligned; skip 1st 12 params which go in V registers.
6990     ArgOffset = ((ArgOffset+15)/16)*16;
6991     ArgOffset += 12*16;
6992     for (unsigned i = 0; i != NumOps; ++i) {
6993       SDValue Arg = OutVals[i];
6994       EVT ArgType = Outs[i].VT;
6995       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6996           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6997         if (++j > NumVRs) {
6998           SDValue PtrOff;
6999           // We are emitting Altivec params in order.
7000           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
7001                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
7002                            TailCallArguments, dl);
7003           ArgOffset += 16;
7004         }
7005       }
7006     }
7007   }
7008 
7009   if (!MemOpChains.empty())
7010     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7011 
7012   // On Darwin, R12 must contain the address of an indirect callee.  This does
7013   // not mean the MTCTR instruction must use R12; it's easier to model this as
7014   // an extra parameter, so do that.
7015   if (CFlags.IsIndirect) {
7016     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7017     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
7018                                                    PPC::R12), Callee));
7019   }
7020 
7021   // Build a sequence of copy-to-reg nodes chained together with token chain
7022   // and flag operands which copy the outgoing args into the appropriate regs.
7023   SDValue InFlag;
7024   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
7025     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
7026                              RegsToPass[i].second, InFlag);
7027     InFlag = Chain.getValue(1);
7028   }
7029 
7030   if (CFlags.IsTailCall)
7031     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
7032                     TailCallArguments);
7033 
7034   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7035                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7036 }
7037 
7038 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
7039                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
7040                    CCState &State) {
7041 
7042   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
7043       State.getMachineFunction().getSubtarget());
7044   const bool IsPPC64 = Subtarget.isPPC64();
7045   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
7046   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
7047 
7048   assert((!ValVT.isInteger() ||
7049           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
7050          "Integer argument exceeds register size: should have been legalized");
7051 
7052   if (ValVT == MVT::f128)
7053     report_fatal_error("f128 is unimplemented on AIX.");
7054 
7055   if (ArgFlags.isNest())
7056     report_fatal_error("Nest arguments are unimplemented.");
7057 
7058   if (ValVT.isVector() || LocVT.isVector())
7059     report_fatal_error("Vector arguments are unimplemented on AIX.");
7060 
7061   static const MCPhysReg GPR_32[] = {// 32-bit registers.
7062                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7063                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7064   static const MCPhysReg GPR_64[] = {// 64-bit registers.
7065                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7066                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7067 
7068   if (ArgFlags.isByVal()) {
7069     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
7070       report_fatal_error("Pass-by-value arguments with alignment greater than "
7071                          "register width are not supported.");
7072 
7073     const unsigned ByValSize = ArgFlags.getByValSize();
7074 
7075     // An empty aggregate parameter takes up no storage and no registers,
7076     // but needs a MemLoc for a stack slot for the formal arguments side.
7077     if (ByValSize == 0) {
7078       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7079                                        State.getNextStackOffset(), RegVT,
7080                                        LocInfo));
7081       return false;
7082     }
7083 
7084     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
7085     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
7086     for (const unsigned E = Offset + StackSize; Offset < E;
7087          Offset += PtrAlign.value()) {
7088       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7089         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7090       else {
7091         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7092                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
7093                                          LocInfo));
7094         break;
7095       }
7096     }
7097     return false;
7098   }
7099 
7100   // Arguments always reserve parameter save area.
7101   switch (ValVT.SimpleTy) {
7102   default:
7103     report_fatal_error("Unhandled value type for argument.");
7104   case MVT::i64:
7105     // i64 arguments should have been split to i32 for PPC32.
7106     assert(IsPPC64 && "PPC32 should have split i64 values.");
7107     LLVM_FALLTHROUGH;
7108   case MVT::i1:
7109   case MVT::i32: {
7110     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
7111     // AIX integer arguments are always passed in register width.
7112     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
7113       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
7114                                   : CCValAssign::LocInfo::ZExt;
7115     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7116       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7117     else
7118       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
7119 
7120     return false;
7121   }
7122   case MVT::f32:
7123   case MVT::f64: {
7124     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7125     const unsigned StoreSize = LocVT.getStoreSize();
7126     // Floats are always 4-byte aligned in the PSA on AIX.
7127     // This includes f64 in 64-bit mode for ABI compatibility.
7128     const unsigned Offset =
7129         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
7130     unsigned FReg = State.AllocateReg(FPR);
7131     if (FReg)
7132       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7133 
7134     // Reserve and initialize GPRs or initialize the PSA as required.
7135     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
7136       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7137         assert(FReg && "An FPR should be available when a GPR is reserved.");
7138         if (State.isVarArg()) {
7139           // Successfully reserved GPRs are only initialized for vararg calls.
7140           // Custom handling is required for:
7141           //   f64 in PPC32 needs to be split into 2 GPRs.
7142           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7143           State.addLoc(
7144               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7145         }
7146       } else {
7147         // If there are insufficient GPRs, the PSA needs to be initialized.
7148         // Initialization occurs even if an FPR was initialized for
7149         // compatibility with the AIX XL compiler. The full memory for the
7150         // argument will be initialized even if a prior word is saved in GPR.
7151         // A custom memLoc is used when the argument also passes in FPR so
7152         // that the callee handling can skip over it easily.
7153         State.addLoc(
7154             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7155                                              LocInfo)
7156                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7157         break;
7158       }
7159     }
7160 
7161     return false;
7162   }
7163   }
7164   return true;
7165 }
7166 
7167 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7168                                                     bool IsPPC64) {
7169   assert((IsPPC64 || SVT != MVT::i64) &&
7170          "i64 should have been split for 32-bit codegen.");
7171 
7172   switch (SVT) {
7173   default:
7174     report_fatal_error("Unexpected value type for formal argument");
7175   case MVT::i1:
7176   case MVT::i32:
7177   case MVT::i64:
7178     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7179   case MVT::f32:
7180     return &PPC::F4RCRegClass;
7181   case MVT::f64:
7182     return &PPC::F8RCRegClass;
7183   }
7184 }
7185 
7186 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7187                                         SelectionDAG &DAG, SDValue ArgValue,
7188                                         MVT LocVT, const SDLoc &dl) {
7189   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7190   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7191 
7192   if (Flags.isSExt())
7193     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7194                            DAG.getValueType(ValVT));
7195   else if (Flags.isZExt())
7196     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7197                            DAG.getValueType(ValVT));
7198 
7199   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7200 }
7201 
7202 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7203   const unsigned LASize = FL->getLinkageSize();
7204 
7205   if (PPC::GPRCRegClass.contains(Reg)) {
7206     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7207            "Reg must be a valid argument register!");
7208     return LASize + 4 * (Reg - PPC::R3);
7209   }
7210 
7211   if (PPC::G8RCRegClass.contains(Reg)) {
7212     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7213            "Reg must be a valid argument register!");
7214     return LASize + 8 * (Reg - PPC::X3);
7215   }
7216 
7217   llvm_unreachable("Only general purpose registers expected.");
7218 }
7219 
7220 //   AIX ABI Stack Frame Layout:
7221 //
7222 //   Low Memory +--------------------------------------------+
7223 //   SP   +---> | Back chain                                 | ---+
7224 //        |     +--------------------------------------------+    |
7225 //        |     | Saved Condition Register                   |    |
7226 //        |     +--------------------------------------------+    |
7227 //        |     | Saved Linkage Register                     |    |
7228 //        |     +--------------------------------------------+    | Linkage Area
7229 //        |     | Reserved for compilers                     |    |
7230 //        |     +--------------------------------------------+    |
7231 //        |     | Reserved for binders                       |    |
7232 //        |     +--------------------------------------------+    |
7233 //        |     | Saved TOC pointer                          | ---+
7234 //        |     +--------------------------------------------+
7235 //        |     | Parameter save area                        |
7236 //        |     +--------------------------------------------+
7237 //        |     | Alloca space                               |
7238 //        |     +--------------------------------------------+
7239 //        |     | Local variable space                       |
7240 //        |     +--------------------------------------------+
7241 //        |     | Float/int conversion temporary             |
7242 //        |     +--------------------------------------------+
7243 //        |     | Save area for AltiVec registers            |
7244 //        |     +--------------------------------------------+
7245 //        |     | AltiVec alignment padding                  |
7246 //        |     +--------------------------------------------+
7247 //        |     | Save area for VRSAVE register              |
7248 //        |     +--------------------------------------------+
7249 //        |     | Save area for General Purpose registers    |
7250 //        |     +--------------------------------------------+
7251 //        |     | Save area for Floating Point registers     |
7252 //        |     +--------------------------------------------+
7253 //        +---- | Back chain                                 |
7254 // High Memory  +--------------------------------------------+
7255 //
7256 //  Specifications:
7257 //  AIX 7.2 Assembler Language Reference
7258 //  Subroutine linkage convention
7259 
7260 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7261     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7262     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7263     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7264 
7265   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7266           CallConv == CallingConv::Fast) &&
7267          "Unexpected calling convention!");
7268 
7269   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7270     report_fatal_error("Tail call support is unimplemented on AIX.");
7271 
7272   if (useSoftFloat())
7273     report_fatal_error("Soft float support is unimplemented on AIX.");
7274 
7275   const PPCSubtarget &Subtarget =
7276       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7277   if (Subtarget.hasQPX())
7278     report_fatal_error("QPX support is not supported on AIX.");
7279 
7280   const bool IsPPC64 = Subtarget.isPPC64();
7281   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7282 
7283   // Assign locations to all of the incoming arguments.
7284   SmallVector<CCValAssign, 16> ArgLocs;
7285   MachineFunction &MF = DAG.getMachineFunction();
7286   MachineFrameInfo &MFI = MF.getFrameInfo();
7287   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7288 
7289   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7290   // Reserve space for the linkage area on the stack.
7291   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7292   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7293   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7294 
7295   SmallVector<SDValue, 8> MemOps;
7296 
7297   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7298     CCValAssign &VA = ArgLocs[I++];
7299     MVT LocVT = VA.getLocVT();
7300     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7301 
7302     // For compatibility with the AIX XL compiler, the float args in the
7303     // parameter save area are initialized even if the argument is available
7304     // in register.  The caller is required to initialize both the register
7305     // and memory, however, the callee can choose to expect it in either.
7306     // The memloc is dismissed here because the argument is retrieved from
7307     // the register.
7308     if (VA.isMemLoc() && VA.needsCustom())
7309       continue;
7310 
7311     if (Flags.isByVal() && VA.isMemLoc()) {
7312       const unsigned Size =
7313           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7314                   PtrByteSize);
7315       const int FI = MF.getFrameInfo().CreateFixedObject(
7316           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7317           /* IsAliased */ true);
7318       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7319       InVals.push_back(FIN);
7320 
7321       continue;
7322     }
7323 
7324     if (Flags.isByVal()) {
7325       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7326 
7327       const MCPhysReg ArgReg = VA.getLocReg();
7328       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7329 
7330       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7331         report_fatal_error("Over aligned byvals not supported yet.");
7332 
7333       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7334       const int FI = MF.getFrameInfo().CreateFixedObject(
7335           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7336           /* IsAliased */ true);
7337       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7338       InVals.push_back(FIN);
7339 
7340       // Add live ins for all the RegLocs for the same ByVal.
7341       const TargetRegisterClass *RegClass =
7342           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7343 
7344       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7345                                                unsigned Offset) {
7346         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7347         // Since the callers side has left justified the aggregate in the
7348         // register, we can simply store the entire register into the stack
7349         // slot.
7350         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7351         // The store to the fixedstack object is needed becuase accessing a
7352         // field of the ByVal will use a gep and load. Ideally we will optimize
7353         // to extracting the value from the register directly, and elide the
7354         // stores when the arguments address is not taken, but that will need to
7355         // be future work.
7356         SDValue Store =
7357             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7358                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7359                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7360 
7361         MemOps.push_back(Store);
7362       };
7363 
7364       unsigned Offset = 0;
7365       HandleRegLoc(VA.getLocReg(), Offset);
7366       Offset += PtrByteSize;
7367       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7368            Offset += PtrByteSize) {
7369         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7370                "RegLocs should be for ByVal argument.");
7371 
7372         const CCValAssign RL = ArgLocs[I++];
7373         HandleRegLoc(RL.getLocReg(), Offset);
7374       }
7375 
7376       if (Offset != StackSize) {
7377         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7378                "Expected MemLoc for remaining bytes.");
7379         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7380         // Consume the MemLoc.The InVal has already been emitted, so nothing
7381         // more needs to be done.
7382         ++I;
7383       }
7384 
7385       continue;
7386     }
7387 
7388     EVT ValVT = VA.getValVT();
7389     if (VA.isRegLoc() && !VA.needsCustom()) {
7390       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7391       unsigned VReg =
7392           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7393       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7394       if (ValVT.isScalarInteger() &&
7395           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7396         ArgValue =
7397             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7398       }
7399       InVals.push_back(ArgValue);
7400       continue;
7401     }
7402     if (VA.isMemLoc()) {
7403       const unsigned LocSize = LocVT.getStoreSize();
7404       const unsigned ValSize = ValVT.getStoreSize();
7405       assert((ValSize <= LocSize) &&
7406              "Object size is larger than size of MemLoc");
7407       int CurArgOffset = VA.getLocMemOffset();
7408       // Objects are right-justified because AIX is big-endian.
7409       if (LocSize > ValSize)
7410         CurArgOffset += LocSize - ValSize;
7411       // Potential tail calls could cause overwriting of argument stack slots.
7412       const bool IsImmutable =
7413           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7414             (CallConv == CallingConv::Fast));
7415       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7416       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7417       SDValue ArgValue =
7418           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7419       InVals.push_back(ArgValue);
7420       continue;
7421     }
7422   }
7423 
7424   // On AIX a minimum of 8 words is saved to the parameter save area.
7425   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7426   // Area that is at least reserved in the caller of this function.
7427   unsigned CallerReservedArea =
7428       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7429 
7430   // Set the size that is at least reserved in caller of this function. Tail
7431   // call optimized function's reserved stack space needs to be aligned so
7432   // that taking the difference between two stack areas will result in an
7433   // aligned stack.
7434   CallerReservedArea =
7435       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7436   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7437   FuncInfo->setMinReservedArea(CallerReservedArea);
7438 
7439   if (isVarArg) {
7440     FuncInfo->setVarArgsFrameIndex(
7441         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7442     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7443 
7444     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7445                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7446 
7447     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7448                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7449     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7450 
7451     // The fixed integer arguments of a variadic function are stored to the
7452     // VarArgsFrameIndex on the stack so that they may be loaded by
7453     // dereferencing the result of va_next.
7454     for (unsigned GPRIndex =
7455              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7456          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7457 
7458       const unsigned VReg =
7459           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7460                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7461 
7462       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7463       SDValue Store =
7464           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7465       MemOps.push_back(Store);
7466       // Increment the address for the next argument to store.
7467       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7468       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7469     }
7470   }
7471 
7472   if (!MemOps.empty())
7473     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7474 
7475   return Chain;
7476 }
7477 
7478 SDValue PPCTargetLowering::LowerCall_AIX(
7479     SDValue Chain, SDValue Callee, CallFlags CFlags,
7480     const SmallVectorImpl<ISD::OutputArg> &Outs,
7481     const SmallVectorImpl<SDValue> &OutVals,
7482     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7483     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7484     const CallBase *CB) const {
7485   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7486   // AIX ABI stack frame layout.
7487 
7488   assert((CFlags.CallConv == CallingConv::C ||
7489           CFlags.CallConv == CallingConv::Cold ||
7490           CFlags.CallConv == CallingConv::Fast) &&
7491          "Unexpected calling convention!");
7492 
7493   if (CFlags.IsPatchPoint)
7494     report_fatal_error("This call type is unimplemented on AIX.");
7495 
7496   const PPCSubtarget& Subtarget =
7497       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7498   if (Subtarget.hasQPX())
7499     report_fatal_error("QPX is not supported on AIX.");
7500   if (Subtarget.hasAltivec())
7501     report_fatal_error("Altivec support is unimplemented on AIX.");
7502 
7503   MachineFunction &MF = DAG.getMachineFunction();
7504   SmallVector<CCValAssign, 16> ArgLocs;
7505   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7506                  *DAG.getContext());
7507 
7508   // Reserve space for the linkage save area (LSA) on the stack.
7509   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7510   //   [SP][CR][LR][2 x reserved][TOC].
7511   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7512   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7513   const bool IsPPC64 = Subtarget.isPPC64();
7514   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7515   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7516   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7517   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7518 
7519   // The prolog code of the callee may store up to 8 GPR argument registers to
7520   // the stack, allowing va_start to index over them in memory if the callee
7521   // is variadic.
7522   // Because we cannot tell if this is needed on the caller side, we have to
7523   // conservatively assume that it is needed.  As such, make sure we have at
7524   // least enough stack space for the caller to store the 8 GPRs.
7525   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7526   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7527                                      CCInfo.getNextStackOffset());
7528 
7529   // Adjust the stack pointer for the new arguments...
7530   // These operations are automatically eliminated by the prolog/epilog pass.
7531   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7532   SDValue CallSeqStart = Chain;
7533 
7534   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7535   SmallVector<SDValue, 8> MemOpChains;
7536 
7537   // Set up a copy of the stack pointer for loading and storing any
7538   // arguments that may not fit in the registers available for argument
7539   // passing.
7540   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7541                                    : DAG.getRegister(PPC::R1, MVT::i32);
7542 
7543   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7544     const unsigned ValNo = ArgLocs[I].getValNo();
7545     SDValue Arg = OutVals[ValNo];
7546     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7547 
7548     if (Flags.isByVal()) {
7549       const unsigned ByValSize = Flags.getByValSize();
7550 
7551       // Nothing to do for zero-sized ByVals on the caller side.
7552       if (!ByValSize) {
7553         ++I;
7554         continue;
7555       }
7556 
7557       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7558         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7559                               (LoadOffset != 0)
7560                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7561                                   : Arg,
7562                               MachinePointerInfo(), VT);
7563       };
7564 
7565       unsigned LoadOffset = 0;
7566 
7567       // Initialize registers, which are fully occupied by the by-val argument.
7568       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7569         SDValue Load = GetLoad(PtrVT, LoadOffset);
7570         MemOpChains.push_back(Load.getValue(1));
7571         LoadOffset += PtrByteSize;
7572         const CCValAssign &ByValVA = ArgLocs[I++];
7573         assert(ByValVA.getValNo() == ValNo &&
7574                "Unexpected location for pass-by-value argument.");
7575         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7576       }
7577 
7578       if (LoadOffset == ByValSize)
7579         continue;
7580 
7581       // There must be one more loc to handle the remainder.
7582       assert(ArgLocs[I].getValNo() == ValNo &&
7583              "Expected additional location for by-value argument.");
7584 
7585       if (ArgLocs[I].isMemLoc()) {
7586         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7587         const CCValAssign &ByValVA = ArgLocs[I++];
7588         ISD::ArgFlagsTy MemcpyFlags = Flags;
7589         // Only memcpy the bytes that don't pass in register.
7590         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7591         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7592             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7593                               : Arg,
7594             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7595             CallSeqStart, MemcpyFlags, DAG, dl);
7596         continue;
7597       }
7598 
7599       // Initialize the final register residue.
7600       // Any residue that occupies the final by-val arg register must be
7601       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7602       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7603       // 2 and 1 byte loads.
7604       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7605       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7606              "Unexpected register residue for by-value argument.");
7607       SDValue ResidueVal;
7608       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7609         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7610         const MVT VT =
7611             N == 1 ? MVT::i8
7612                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7613         SDValue Load = GetLoad(VT, LoadOffset);
7614         MemOpChains.push_back(Load.getValue(1));
7615         LoadOffset += N;
7616         Bytes += N;
7617 
7618         // By-val arguments are passed left-justfied in register.
7619         // Every load here needs to be shifted, otherwise a full register load
7620         // should have been used.
7621         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7622                "Unexpected load emitted during handling of pass-by-value "
7623                "argument.");
7624         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7625         EVT ShiftAmountTy =
7626             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7627         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7628         SDValue ShiftedLoad =
7629             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7630         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7631                                               ShiftedLoad)
7632                                 : ShiftedLoad;
7633       }
7634 
7635       const CCValAssign &ByValVA = ArgLocs[I++];
7636       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7637       continue;
7638     }
7639 
7640     CCValAssign &VA = ArgLocs[I++];
7641     const MVT LocVT = VA.getLocVT();
7642     const MVT ValVT = VA.getValVT();
7643 
7644     switch (VA.getLocInfo()) {
7645     default:
7646       report_fatal_error("Unexpected argument extension type.");
7647     case CCValAssign::Full:
7648       break;
7649     case CCValAssign::ZExt:
7650       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7651       break;
7652     case CCValAssign::SExt:
7653       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7654       break;
7655     }
7656 
7657     if (VA.isRegLoc() && !VA.needsCustom()) {
7658       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7659       continue;
7660     }
7661 
7662     if (VA.isMemLoc()) {
7663       SDValue PtrOff =
7664           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7665       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7666       MemOpChains.push_back(
7667           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7668 
7669       continue;
7670     }
7671 
7672     // Custom handling is used for GPR initializations for vararg float
7673     // arguments.
7674     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7675            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7676            "Unexpected register handling for calling convention.");
7677 
7678     SDValue ArgAsInt =
7679         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7680 
7681     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7682       // f32 in 32-bit GPR
7683       // f64 in 64-bit GPR
7684       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7685     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7686       // f32 in 64-bit GPR.
7687       RegsToPass.push_back(std::make_pair(
7688           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7689     else {
7690       // f64 in two 32-bit GPRs
7691       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7692       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7693              "Unexpected custom register for argument!");
7694       CCValAssign &GPR1 = VA;
7695       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7696                                      DAG.getConstant(32, dl, MVT::i8));
7697       RegsToPass.push_back(std::make_pair(
7698           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7699 
7700       if (I != E) {
7701         // If only 1 GPR was available, there will only be one custom GPR and
7702         // the argument will also pass in memory.
7703         CCValAssign &PeekArg = ArgLocs[I];
7704         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7705           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7706           CCValAssign &GPR2 = ArgLocs[I++];
7707           RegsToPass.push_back(std::make_pair(
7708               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7709         }
7710       }
7711     }
7712   }
7713 
7714   if (!MemOpChains.empty())
7715     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7716 
7717   // For indirect calls, we need to save the TOC base to the stack for
7718   // restoration after the call.
7719   if (CFlags.IsIndirect) {
7720     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7721     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7722     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7723     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7724     const unsigned TOCSaveOffset =
7725         Subtarget.getFrameLowering()->getTOCSaveOffset();
7726 
7727     setUsesTOCBasePtr(DAG);
7728     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7729     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7730     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7731     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7732     Chain = DAG.getStore(
7733         Val.getValue(1), dl, Val, AddPtr,
7734         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7735   }
7736 
7737   // Build a sequence of copy-to-reg nodes chained together with token chain
7738   // and flag operands which copy the outgoing args into the appropriate regs.
7739   SDValue InFlag;
7740   for (auto Reg : RegsToPass) {
7741     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7742     InFlag = Chain.getValue(1);
7743   }
7744 
7745   const int SPDiff = 0;
7746   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7747                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7748 }
7749 
7750 bool
7751 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7752                                   MachineFunction &MF, bool isVarArg,
7753                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7754                                   LLVMContext &Context) const {
7755   SmallVector<CCValAssign, 16> RVLocs;
7756   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7757   return CCInfo.CheckReturn(
7758       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7759                 ? RetCC_PPC_Cold
7760                 : RetCC_PPC);
7761 }
7762 
7763 SDValue
7764 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7765                                bool isVarArg,
7766                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7767                                const SmallVectorImpl<SDValue> &OutVals,
7768                                const SDLoc &dl, SelectionDAG &DAG) const {
7769   SmallVector<CCValAssign, 16> RVLocs;
7770   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7771                  *DAG.getContext());
7772   CCInfo.AnalyzeReturn(Outs,
7773                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7774                            ? RetCC_PPC_Cold
7775                            : RetCC_PPC);
7776 
7777   SDValue Flag;
7778   SmallVector<SDValue, 4> RetOps(1, Chain);
7779 
7780   // Copy the result values into the output registers.
7781   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7782     CCValAssign &VA = RVLocs[i];
7783     assert(VA.isRegLoc() && "Can only return in registers!");
7784 
7785     SDValue Arg = OutVals[RealResIdx];
7786 
7787     switch (VA.getLocInfo()) {
7788     default: llvm_unreachable("Unknown loc info!");
7789     case CCValAssign::Full: break;
7790     case CCValAssign::AExt:
7791       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7792       break;
7793     case CCValAssign::ZExt:
7794       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7795       break;
7796     case CCValAssign::SExt:
7797       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7798       break;
7799     }
7800     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7801       bool isLittleEndian = Subtarget.isLittleEndian();
7802       // Legalize ret f64 -> ret 2 x i32.
7803       SDValue SVal =
7804           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7805                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7806       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7807       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7808       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7809                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7810       Flag = Chain.getValue(1);
7811       VA = RVLocs[++i]; // skip ahead to next loc
7812       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7813     } else
7814       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7815     Flag = Chain.getValue(1);
7816     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7817   }
7818 
7819   RetOps[0] = Chain;  // Update chain.
7820 
7821   // Add the flag if we have it.
7822   if (Flag.getNode())
7823     RetOps.push_back(Flag);
7824 
7825   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7826 }
7827 
7828 SDValue
7829 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7830                                                 SelectionDAG &DAG) const {
7831   SDLoc dl(Op);
7832 
7833   // Get the correct type for integers.
7834   EVT IntVT = Op.getValueType();
7835 
7836   // Get the inputs.
7837   SDValue Chain = Op.getOperand(0);
7838   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7839   // Build a DYNAREAOFFSET node.
7840   SDValue Ops[2] = {Chain, FPSIdx};
7841   SDVTList VTs = DAG.getVTList(IntVT);
7842   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7843 }
7844 
7845 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7846                                              SelectionDAG &DAG) const {
7847   // When we pop the dynamic allocation we need to restore the SP link.
7848   SDLoc dl(Op);
7849 
7850   // Get the correct type for pointers.
7851   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7852 
7853   // Construct the stack pointer operand.
7854   bool isPPC64 = Subtarget.isPPC64();
7855   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7856   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7857 
7858   // Get the operands for the STACKRESTORE.
7859   SDValue Chain = Op.getOperand(0);
7860   SDValue SaveSP = Op.getOperand(1);
7861 
7862   // Load the old link SP.
7863   SDValue LoadLinkSP =
7864       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7865 
7866   // Restore the stack pointer.
7867   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7868 
7869   // Store the old link SP.
7870   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7871 }
7872 
7873 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7874   MachineFunction &MF = DAG.getMachineFunction();
7875   bool isPPC64 = Subtarget.isPPC64();
7876   EVT PtrVT = getPointerTy(MF.getDataLayout());
7877 
7878   // Get current frame pointer save index.  The users of this index will be
7879   // primarily DYNALLOC instructions.
7880   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7881   int RASI = FI->getReturnAddrSaveIndex();
7882 
7883   // If the frame pointer save index hasn't been defined yet.
7884   if (!RASI) {
7885     // Find out what the fix offset of the frame pointer save area.
7886     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7887     // Allocate the frame index for frame pointer save area.
7888     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7889     // Save the result.
7890     FI->setReturnAddrSaveIndex(RASI);
7891   }
7892   return DAG.getFrameIndex(RASI, PtrVT);
7893 }
7894 
7895 SDValue
7896 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7897   MachineFunction &MF = DAG.getMachineFunction();
7898   bool isPPC64 = Subtarget.isPPC64();
7899   EVT PtrVT = getPointerTy(MF.getDataLayout());
7900 
7901   // Get current frame pointer save index.  The users of this index will be
7902   // primarily DYNALLOC instructions.
7903   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7904   int FPSI = FI->getFramePointerSaveIndex();
7905 
7906   // If the frame pointer save index hasn't been defined yet.
7907   if (!FPSI) {
7908     // Find out what the fix offset of the frame pointer save area.
7909     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7910     // Allocate the frame index for frame pointer save area.
7911     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7912     // Save the result.
7913     FI->setFramePointerSaveIndex(FPSI);
7914   }
7915   return DAG.getFrameIndex(FPSI, PtrVT);
7916 }
7917 
7918 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7919                                                    SelectionDAG &DAG) const {
7920   // Get the inputs.
7921   SDValue Chain = Op.getOperand(0);
7922   SDValue Size  = Op.getOperand(1);
7923   SDLoc dl(Op);
7924 
7925   // Get the correct type for pointers.
7926   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7927   // Negate the size.
7928   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7929                                 DAG.getConstant(0, dl, PtrVT), Size);
7930   // Construct a node for the frame pointer save index.
7931   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7932   // Build a DYNALLOC node.
7933   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7934   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7935   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7936 }
7937 
7938 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7939                                                      SelectionDAG &DAG) const {
7940   MachineFunction &MF = DAG.getMachineFunction();
7941 
7942   bool isPPC64 = Subtarget.isPPC64();
7943   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7944 
7945   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7946   return DAG.getFrameIndex(FI, PtrVT);
7947 }
7948 
7949 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7950                                                SelectionDAG &DAG) const {
7951   SDLoc DL(Op);
7952   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7953                      DAG.getVTList(MVT::i32, MVT::Other),
7954                      Op.getOperand(0), Op.getOperand(1));
7955 }
7956 
7957 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7958                                                 SelectionDAG &DAG) const {
7959   SDLoc DL(Op);
7960   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7961                      Op.getOperand(0), Op.getOperand(1));
7962 }
7963 
7964 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7965   if (Op.getValueType().isVector())
7966     return LowerVectorLoad(Op, DAG);
7967 
7968   assert(Op.getValueType() == MVT::i1 &&
7969          "Custom lowering only for i1 loads");
7970 
7971   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7972 
7973   SDLoc dl(Op);
7974   LoadSDNode *LD = cast<LoadSDNode>(Op);
7975 
7976   SDValue Chain = LD->getChain();
7977   SDValue BasePtr = LD->getBasePtr();
7978   MachineMemOperand *MMO = LD->getMemOperand();
7979 
7980   SDValue NewLD =
7981       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7982                      BasePtr, MVT::i8, MMO);
7983   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7984 
7985   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7986   return DAG.getMergeValues(Ops, dl);
7987 }
7988 
7989 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7990   if (Op.getOperand(1).getValueType().isVector())
7991     return LowerVectorStore(Op, DAG);
7992 
7993   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7994          "Custom lowering only for i1 stores");
7995 
7996   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7997 
7998   SDLoc dl(Op);
7999   StoreSDNode *ST = cast<StoreSDNode>(Op);
8000 
8001   SDValue Chain = ST->getChain();
8002   SDValue BasePtr = ST->getBasePtr();
8003   SDValue Value = ST->getValue();
8004   MachineMemOperand *MMO = ST->getMemOperand();
8005 
8006   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
8007                       Value);
8008   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
8009 }
8010 
8011 // FIXME: Remove this once the ANDI glue bug is fixed:
8012 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8013   assert(Op.getValueType() == MVT::i1 &&
8014          "Custom lowering only for i1 results");
8015 
8016   SDLoc DL(Op);
8017   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
8018 }
8019 
8020 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
8021                                                SelectionDAG &DAG) const {
8022 
8023   // Implements a vector truncate that fits in a vector register as a shuffle.
8024   // We want to legalize vector truncates down to where the source fits in
8025   // a vector register (and target is therefore smaller than vector register
8026   // size).  At that point legalization will try to custom lower the sub-legal
8027   // result and get here - where we can contain the truncate as a single target
8028   // operation.
8029 
8030   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
8031   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
8032   //
8033   // We will implement it for big-endian ordering as this (where x denotes
8034   // undefined):
8035   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
8036   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
8037   //
8038   // The same operation in little-endian ordering will be:
8039   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
8040   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
8041 
8042   assert(Op.getValueType().isVector() && "Vector type expected.");
8043 
8044   SDLoc DL(Op);
8045   SDValue N1 = Op.getOperand(0);
8046   unsigned SrcSize = N1.getValueType().getSizeInBits();
8047   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
8048   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
8049 
8050   EVT TrgVT = Op.getValueType();
8051   unsigned TrgNumElts = TrgVT.getVectorNumElements();
8052   EVT EltVT = TrgVT.getVectorElementType();
8053   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8054   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8055 
8056   // First list the elements we want to keep.
8057   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
8058   SmallVector<int, 16> ShuffV;
8059   if (Subtarget.isLittleEndian())
8060     for (unsigned i = 0; i < TrgNumElts; ++i)
8061       ShuffV.push_back(i * SizeMult);
8062   else
8063     for (unsigned i = 1; i <= TrgNumElts; ++i)
8064       ShuffV.push_back(i * SizeMult - 1);
8065 
8066   // Populate the remaining elements with undefs.
8067   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8068     // ShuffV.push_back(i + WideNumElts);
8069     ShuffV.push_back(WideNumElts + 1);
8070 
8071   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
8072   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
8073 }
8074 
8075 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8076 /// possible.
8077 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8078   // Not FP? Not a fsel.
8079   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
8080       !Op.getOperand(2).getValueType().isFloatingPoint())
8081     return Op;
8082 
8083   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8084 
8085   EVT ResVT = Op.getValueType();
8086   EVT CmpVT = Op.getOperand(0).getValueType();
8087   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8088   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
8089   SDLoc dl(Op);
8090   SDNodeFlags Flags = Op.getNode()->getFlags();
8091 
8092   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
8093   // presence of infinities.
8094   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8095     switch (CC) {
8096     default:
8097       break;
8098     case ISD::SETOGT:
8099     case ISD::SETGT:
8100       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
8101     case ISD::SETOLT:
8102     case ISD::SETLT:
8103       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
8104     }
8105   }
8106 
8107   // We might be able to do better than this under some circumstances, but in
8108   // general, fsel-based lowering of select is a finite-math-only optimization.
8109   // For more information, see section F.3 of the 2.06 ISA specification.
8110   // With ISA 3.0
8111   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
8112       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
8113     return Op;
8114 
8115   // If the RHS of the comparison is a 0.0, we don't need to do the
8116   // subtraction at all.
8117   SDValue Sel1;
8118   if (isFloatingPointZero(RHS))
8119     switch (CC) {
8120     default: break;       // SETUO etc aren't handled by fsel.
8121     case ISD::SETNE:
8122       std::swap(TV, FV);
8123       LLVM_FALLTHROUGH;
8124     case ISD::SETEQ:
8125       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8126         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8127       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8128       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8129         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8130       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8131                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8132     case ISD::SETULT:
8133     case ISD::SETLT:
8134       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8135       LLVM_FALLTHROUGH;
8136     case ISD::SETOGE:
8137     case ISD::SETGE:
8138       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8139         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8140       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8141     case ISD::SETUGT:
8142     case ISD::SETGT:
8143       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8144       LLVM_FALLTHROUGH;
8145     case ISD::SETOLE:
8146     case ISD::SETLE:
8147       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8148         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8149       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8150                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8151     }
8152 
8153   SDValue Cmp;
8154   switch (CC) {
8155   default: break;       // SETUO etc aren't handled by fsel.
8156   case ISD::SETNE:
8157     std::swap(TV, FV);
8158     LLVM_FALLTHROUGH;
8159   case ISD::SETEQ:
8160     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8161     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8162       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8163     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8164     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8165       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8166     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8167                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8168   case ISD::SETULT:
8169   case ISD::SETLT:
8170     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8171     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8172       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8173     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8174   case ISD::SETOGE:
8175   case ISD::SETGE:
8176     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8177     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8178       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8179     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8180   case ISD::SETUGT:
8181   case ISD::SETGT:
8182     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8183     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8184       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8185     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8186   case ISD::SETOLE:
8187   case ISD::SETLE:
8188     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8189     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8190       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8191     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8192   }
8193   return Op;
8194 }
8195 
8196 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8197                                                SelectionDAG &DAG,
8198                                                const SDLoc &dl) const {
8199   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8200   SDValue Src = Op.getOperand(0);
8201   if (Src.getValueType() == MVT::f32)
8202     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8203 
8204   SDValue Tmp;
8205   switch (Op.getSimpleValueType().SimpleTy) {
8206   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8207   case MVT::i32:
8208     Tmp = DAG.getNode(
8209         Op.getOpcode() == ISD::FP_TO_SINT
8210             ? PPCISD::FCTIWZ
8211             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8212         dl, MVT::f64, Src);
8213     break;
8214   case MVT::i64:
8215     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8216            "i64 FP_TO_UINT is supported only with FPCVT");
8217     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8218                                                         PPCISD::FCTIDUZ,
8219                       dl, MVT::f64, Src);
8220     break;
8221   }
8222 
8223   // Convert the FP value to an int value through memory.
8224   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8225     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
8226   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8227   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8228   MachinePointerInfo MPI =
8229       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8230 
8231   // Emit a store to the stack slot.
8232   SDValue Chain;
8233   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8234   if (i32Stack) {
8235     MachineFunction &MF = DAG.getMachineFunction();
8236     Alignment = Align(4);
8237     MachineMemOperand *MMO =
8238         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8239     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
8240     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8241               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8242   } else
8243     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
8244 
8245   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8246   // add in a bias on big endian.
8247   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8248     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8249                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8250     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8251   }
8252 
8253   RLI.Chain = Chain;
8254   RLI.Ptr = FIPtr;
8255   RLI.MPI = MPI;
8256   RLI.Alignment = Alignment;
8257 }
8258 
8259 /// Custom lowers floating point to integer conversions to use
8260 /// the direct move instructions available in ISA 2.07 to avoid the
8261 /// need for load/store combinations.
8262 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8263                                                     SelectionDAG &DAG,
8264                                                     const SDLoc &dl) const {
8265   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8266   SDValue Src = Op.getOperand(0);
8267 
8268   if (Src.getValueType() == MVT::f32)
8269     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8270 
8271   SDValue Tmp;
8272   switch (Op.getSimpleValueType().SimpleTy) {
8273   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8274   case MVT::i32:
8275     Tmp = DAG.getNode(
8276         Op.getOpcode() == ISD::FP_TO_SINT
8277             ? PPCISD::FCTIWZ
8278             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8279         dl, MVT::f64, Src);
8280     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
8281     break;
8282   case MVT::i64:
8283     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8284            "i64 FP_TO_UINT is supported only with FPCVT");
8285     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8286                                                         PPCISD::FCTIDUZ,
8287                       dl, MVT::f64, Src);
8288     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
8289     break;
8290   }
8291   return Tmp;
8292 }
8293 
8294 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8295                                           const SDLoc &dl) const {
8296 
8297   // FP to INT conversions are legal for f128.
8298   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
8299     return Op;
8300 
8301   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8302   // PPC (the libcall is not available).
8303   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
8304     if (Op.getValueType() == MVT::i32) {
8305       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8306         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8307                                  MVT::f64, Op.getOperand(0),
8308                                  DAG.getIntPtrConstant(0, dl));
8309         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8310                                  MVT::f64, Op.getOperand(0),
8311                                  DAG.getIntPtrConstant(1, dl));
8312 
8313         // Add the two halves of the long double in round-to-zero mode.
8314         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8315 
8316         // Now use a smaller FP_TO_SINT.
8317         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8318       }
8319       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8320         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8321         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8322         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8323         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8324         // FIXME: generated code sucks.
8325         // TODO: Are there fast-math-flags to propagate to this FSUB?
8326         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
8327                                    Op.getOperand(0), Tmp);
8328         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8329         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8330                            DAG.getConstant(0x80000000, dl, MVT::i32));
8331         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
8332                                     Op.getOperand(0));
8333         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8334                                ISD::SETGE);
8335       }
8336     }
8337 
8338     return SDValue();
8339   }
8340 
8341   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8342     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8343 
8344   ReuseLoadInfo RLI;
8345   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8346 
8347   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8348                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8349 }
8350 
8351 // We're trying to insert a regular store, S, and then a load, L. If the
8352 // incoming value, O, is a load, we might just be able to have our load use the
8353 // address used by O. However, we don't know if anything else will store to
8354 // that address before we can load from it. To prevent this situation, we need
8355 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8356 // the same chain operand as O, we create a token factor from the chain results
8357 // of O and L, and we replace all uses of O's chain result with that token
8358 // factor (see spliceIntoChain below for this last part).
8359 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8360                                             ReuseLoadInfo &RLI,
8361                                             SelectionDAG &DAG,
8362                                             ISD::LoadExtType ET) const {
8363   SDLoc dl(Op);
8364   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8365                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8366   if (ET == ISD::NON_EXTLOAD &&
8367       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8368       isOperationLegalOrCustom(Op.getOpcode(),
8369                                Op.getOperand(0).getValueType())) {
8370 
8371     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8372     return true;
8373   }
8374 
8375   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8376   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8377       LD->isNonTemporal())
8378     return false;
8379   if (LD->getMemoryVT() != MemVT)
8380     return false;
8381 
8382   RLI.Ptr = LD->getBasePtr();
8383   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8384     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8385            "Non-pre-inc AM on PPC?");
8386     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8387                           LD->getOffset());
8388   }
8389 
8390   RLI.Chain = LD->getChain();
8391   RLI.MPI = LD->getPointerInfo();
8392   RLI.IsDereferenceable = LD->isDereferenceable();
8393   RLI.IsInvariant = LD->isInvariant();
8394   RLI.Alignment = LD->getAlign();
8395   RLI.AAInfo = LD->getAAInfo();
8396   RLI.Ranges = LD->getRanges();
8397 
8398   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8399   return true;
8400 }
8401 
8402 // Given the head of the old chain, ResChain, insert a token factor containing
8403 // it and NewResChain, and make users of ResChain now be users of that token
8404 // factor.
8405 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8406 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8407                                         SDValue NewResChain,
8408                                         SelectionDAG &DAG) const {
8409   if (!ResChain)
8410     return;
8411 
8412   SDLoc dl(NewResChain);
8413 
8414   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8415                            NewResChain, DAG.getUNDEF(MVT::Other));
8416   assert(TF.getNode() != NewResChain.getNode() &&
8417          "A new TF really is required here");
8418 
8419   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8420   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8421 }
8422 
8423 /// Analyze profitability of direct move
8424 /// prefer float load to int load plus direct move
8425 /// when there is no integer use of int load
8426 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8427   SDNode *Origin = Op.getOperand(0).getNode();
8428   if (Origin->getOpcode() != ISD::LOAD)
8429     return true;
8430 
8431   // If there is no LXSIBZX/LXSIHZX, like Power8,
8432   // prefer direct move if the memory size is 1 or 2 bytes.
8433   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8434   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8435     return true;
8436 
8437   for (SDNode::use_iterator UI = Origin->use_begin(),
8438                             UE = Origin->use_end();
8439        UI != UE; ++UI) {
8440 
8441     // Only look at the users of the loaded value.
8442     if (UI.getUse().get().getResNo() != 0)
8443       continue;
8444 
8445     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8446         UI->getOpcode() != ISD::UINT_TO_FP)
8447       return true;
8448   }
8449 
8450   return false;
8451 }
8452 
8453 /// Custom lowers integer to floating point conversions to use
8454 /// the direct move instructions available in ISA 2.07 to avoid the
8455 /// need for load/store combinations.
8456 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8457                                                     SelectionDAG &DAG,
8458                                                     const SDLoc &dl) const {
8459   assert((Op.getValueType() == MVT::f32 ||
8460           Op.getValueType() == MVT::f64) &&
8461          "Invalid floating point type as target of conversion");
8462   assert(Subtarget.hasFPCVT() &&
8463          "Int to FP conversions with direct moves require FPCVT");
8464   SDValue FP;
8465   SDValue Src = Op.getOperand(0);
8466   bool SinglePrec = Op.getValueType() == MVT::f32;
8467   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8468   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8469   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8470                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8471 
8472   if (WordInt) {
8473     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8474                      dl, MVT::f64, Src);
8475     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8476   }
8477   else {
8478     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8479     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8480   }
8481 
8482   return FP;
8483 }
8484 
8485 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8486 
8487   EVT VecVT = Vec.getValueType();
8488   assert(VecVT.isVector() && "Expected a vector type.");
8489   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8490 
8491   EVT EltVT = VecVT.getVectorElementType();
8492   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8493   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8494 
8495   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8496   SmallVector<SDValue, 16> Ops(NumConcat);
8497   Ops[0] = Vec;
8498   SDValue UndefVec = DAG.getUNDEF(VecVT);
8499   for (unsigned i = 1; i < NumConcat; ++i)
8500     Ops[i] = UndefVec;
8501 
8502   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8503 }
8504 
8505 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8506                                                 const SDLoc &dl) const {
8507 
8508   unsigned Opc = Op.getOpcode();
8509   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8510          "Unexpected conversion type");
8511   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8512          "Supports conversions to v2f64/v4f32 only.");
8513 
8514   bool SignedConv = Opc == ISD::SINT_TO_FP;
8515   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8516 
8517   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8518   EVT WideVT = Wide.getValueType();
8519   unsigned WideNumElts = WideVT.getVectorNumElements();
8520   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8521 
8522   SmallVector<int, 16> ShuffV;
8523   for (unsigned i = 0; i < WideNumElts; ++i)
8524     ShuffV.push_back(i + WideNumElts);
8525 
8526   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8527   int SaveElts = FourEltRes ? 4 : 2;
8528   if (Subtarget.isLittleEndian())
8529     for (int i = 0; i < SaveElts; i++)
8530       ShuffV[i * Stride] = i;
8531   else
8532     for (int i = 1; i <= SaveElts; i++)
8533       ShuffV[i * Stride - 1] = i - 1;
8534 
8535   SDValue ShuffleSrc2 =
8536       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8537   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8538 
8539   SDValue Extend;
8540   if (SignedConv) {
8541     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8542     EVT ExtVT = Op.getOperand(0).getValueType();
8543     if (Subtarget.hasP9Altivec())
8544       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8545                                IntermediateVT.getVectorNumElements());
8546 
8547     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8548                          DAG.getValueType(ExtVT));
8549   } else
8550     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8551 
8552   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8553 }
8554 
8555 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8556                                           SelectionDAG &DAG) const {
8557   SDLoc dl(Op);
8558 
8559   EVT InVT = Op.getOperand(0).getValueType();
8560   EVT OutVT = Op.getValueType();
8561   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8562       isOperationCustom(Op.getOpcode(), InVT))
8563     return LowerINT_TO_FPVector(Op, DAG, dl);
8564 
8565   // Conversions to f128 are legal.
8566   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8567     return Op;
8568 
8569   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8570     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8571       return SDValue();
8572 
8573     SDValue Value = Op.getOperand(0);
8574     // The values are now known to be -1 (false) or 1 (true). To convert this
8575     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8576     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8577     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8578 
8579     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8580 
8581     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8582 
8583     if (Op.getValueType() != MVT::v4f64)
8584       Value = DAG.getNode(ISD::FP_ROUND, dl,
8585                           Op.getValueType(), Value,
8586                           DAG.getIntPtrConstant(1, dl));
8587     return Value;
8588   }
8589 
8590   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8591   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8592     return SDValue();
8593 
8594   if (Op.getOperand(0).getValueType() == MVT::i1)
8595     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8596                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8597                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8598 
8599   // If we have direct moves, we can do all the conversion, skip the store/load
8600   // however, without FPCVT we can't do most conversions.
8601   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8602       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8603     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8604 
8605   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8606          "UINT_TO_FP is supported only with FPCVT");
8607 
8608   // If we have FCFIDS, then use it when converting to single-precision.
8609   // Otherwise, convert to double-precision and then round.
8610   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8611                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8612                                                             : PPCISD::FCFIDS)
8613                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8614                                                             : PPCISD::FCFID);
8615   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8616                   ? MVT::f32
8617                   : MVT::f64;
8618 
8619   if (Op.getOperand(0).getValueType() == MVT::i64) {
8620     SDValue SINT = Op.getOperand(0);
8621     // When converting to single-precision, we actually need to convert
8622     // to double-precision first and then round to single-precision.
8623     // To avoid double-rounding effects during that operation, we have
8624     // to prepare the input operand.  Bits that might be truncated when
8625     // converting to double-precision are replaced by a bit that won't
8626     // be lost at this stage, but is below the single-precision rounding
8627     // position.
8628     //
8629     // However, if -enable-unsafe-fp-math is in effect, accept double
8630     // rounding to avoid the extra overhead.
8631     if (Op.getValueType() == MVT::f32 &&
8632         !Subtarget.hasFPCVT() &&
8633         !DAG.getTarget().Options.UnsafeFPMath) {
8634 
8635       // Twiddle input to make sure the low 11 bits are zero.  (If this
8636       // is the case, we are guaranteed the value will fit into the 53 bit
8637       // mantissa of an IEEE double-precision value without rounding.)
8638       // If any of those low 11 bits were not zero originally, make sure
8639       // bit 12 (value 2048) is set instead, so that the final rounding
8640       // to single-precision gets the correct result.
8641       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8642                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8643       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8644                           Round, DAG.getConstant(2047, dl, MVT::i64));
8645       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8646       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8647                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8648 
8649       // However, we cannot use that value unconditionally: if the magnitude
8650       // of the input value is small, the bit-twiddling we did above might
8651       // end up visibly changing the output.  Fortunately, in that case, we
8652       // don't need to twiddle bits since the original input will convert
8653       // exactly to double-precision floating-point already.  Therefore,
8654       // construct a conditional to use the original value if the top 11
8655       // bits are all sign-bit copies, and use the rounded value computed
8656       // above otherwise.
8657       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8658                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8659       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8660                          Cond, DAG.getConstant(1, dl, MVT::i64));
8661       Cond = DAG.getSetCC(
8662           dl,
8663           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8664           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8665 
8666       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8667     }
8668 
8669     ReuseLoadInfo RLI;
8670     SDValue Bits;
8671 
8672     MachineFunction &MF = DAG.getMachineFunction();
8673     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8674       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8675                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8676       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8677     } else if (Subtarget.hasLFIWAX() &&
8678                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8679       MachineMemOperand *MMO =
8680         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8681                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8682       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8683       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8684                                      DAG.getVTList(MVT::f64, MVT::Other),
8685                                      Ops, MVT::i32, MMO);
8686       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8687     } else if (Subtarget.hasFPCVT() &&
8688                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8689       MachineMemOperand *MMO =
8690         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8691                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8692       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8693       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8694                                      DAG.getVTList(MVT::f64, MVT::Other),
8695                                      Ops, MVT::i32, MMO);
8696       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8697     } else if (((Subtarget.hasLFIWAX() &&
8698                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8699                 (Subtarget.hasFPCVT() &&
8700                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8701                SINT.getOperand(0).getValueType() == MVT::i32) {
8702       MachineFrameInfo &MFI = MF.getFrameInfo();
8703       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8704 
8705       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8706       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8707 
8708       SDValue Store =
8709           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8710                        MachinePointerInfo::getFixedStack(
8711                            DAG.getMachineFunction(), FrameIdx));
8712 
8713       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8714              "Expected an i32 store");
8715 
8716       RLI.Ptr = FIdx;
8717       RLI.Chain = Store;
8718       RLI.MPI =
8719           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8720       RLI.Alignment = Align(4);
8721 
8722       MachineMemOperand *MMO =
8723         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8724                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8725       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8726       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8727                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8728                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8729                                      Ops, MVT::i32, MMO);
8730     } else
8731       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8732 
8733     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8734 
8735     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8736       FP = DAG.getNode(ISD::FP_ROUND, dl,
8737                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8738     return FP;
8739   }
8740 
8741   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8742          "Unhandled INT_TO_FP type in custom expander!");
8743   // Since we only generate this in 64-bit mode, we can take advantage of
8744   // 64-bit registers.  In particular, sign extend the input value into the
8745   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8746   // then lfd it and fcfid it.
8747   MachineFunction &MF = DAG.getMachineFunction();
8748   MachineFrameInfo &MFI = MF.getFrameInfo();
8749   EVT PtrVT = getPointerTy(MF.getDataLayout());
8750 
8751   SDValue Ld;
8752   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8753     ReuseLoadInfo RLI;
8754     bool ReusingLoad;
8755     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8756                                             DAG))) {
8757       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8758       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8759 
8760       SDValue Store =
8761           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8762                        MachinePointerInfo::getFixedStack(
8763                            DAG.getMachineFunction(), FrameIdx));
8764 
8765       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8766              "Expected an i32 store");
8767 
8768       RLI.Ptr = FIdx;
8769       RLI.Chain = Store;
8770       RLI.MPI =
8771           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8772       RLI.Alignment = Align(4);
8773     }
8774 
8775     MachineMemOperand *MMO =
8776       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8777                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8778     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8779     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8780                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8781                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8782                                  Ops, MVT::i32, MMO);
8783     if (ReusingLoad)
8784       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8785   } else {
8786     assert(Subtarget.isPPC64() &&
8787            "i32->FP without LFIWAX supported only on PPC64");
8788 
8789     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8790     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8791 
8792     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8793                                 Op.getOperand(0));
8794 
8795     // STD the extended value into the stack slot.
8796     SDValue Store = DAG.getStore(
8797         DAG.getEntryNode(), dl, Ext64, FIdx,
8798         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8799 
8800     // Load the value as a double.
8801     Ld = DAG.getLoad(
8802         MVT::f64, dl, Store, FIdx,
8803         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8804   }
8805 
8806   // FCFID it and return it.
8807   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8808   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8809     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8810                      DAG.getIntPtrConstant(0, dl));
8811   return FP;
8812 }
8813 
8814 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8815                                             SelectionDAG &DAG) const {
8816   SDLoc dl(Op);
8817   /*
8818    The rounding mode is in bits 30:31 of FPSR, and has the following
8819    settings:
8820      00 Round to nearest
8821      01 Round to 0
8822      10 Round to +inf
8823      11 Round to -inf
8824 
8825   FLT_ROUNDS, on the other hand, expects the following:
8826     -1 Undefined
8827      0 Round to 0
8828      1 Round to nearest
8829      2 Round to +inf
8830      3 Round to -inf
8831 
8832   To perform the conversion, we do:
8833     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8834   */
8835 
8836   MachineFunction &MF = DAG.getMachineFunction();
8837   EVT VT = Op.getValueType();
8838   EVT PtrVT = getPointerTy(MF.getDataLayout());
8839 
8840   // Save FP Control Word to register
8841   SDValue Chain = Op.getOperand(0);
8842   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8843   Chain = MFFS.getValue(1);
8844 
8845   // Save FP register to stack slot
8846   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8847   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8848   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8849 
8850   // Load FP Control Word from low 32 bits of stack slot.
8851   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8852   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8853   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8854   Chain = CWD.getValue(1);
8855 
8856   // Transform as necessary
8857   SDValue CWD1 =
8858     DAG.getNode(ISD::AND, dl, MVT::i32,
8859                 CWD, DAG.getConstant(3, dl, MVT::i32));
8860   SDValue CWD2 =
8861     DAG.getNode(ISD::SRL, dl, MVT::i32,
8862                 DAG.getNode(ISD::AND, dl, MVT::i32,
8863                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8864                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8865                             DAG.getConstant(3, dl, MVT::i32)),
8866                 DAG.getConstant(1, dl, MVT::i32));
8867 
8868   SDValue RetVal =
8869     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8870 
8871   RetVal =
8872       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8873                   dl, VT, RetVal);
8874 
8875   return DAG.getMergeValues({RetVal, Chain}, dl);
8876 }
8877 
8878 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8879   EVT VT = Op.getValueType();
8880   unsigned BitWidth = VT.getSizeInBits();
8881   SDLoc dl(Op);
8882   assert(Op.getNumOperands() == 3 &&
8883          VT == Op.getOperand(1).getValueType() &&
8884          "Unexpected SHL!");
8885 
8886   // Expand into a bunch of logical ops.  Note that these ops
8887   // depend on the PPC behavior for oversized shift amounts.
8888   SDValue Lo = Op.getOperand(0);
8889   SDValue Hi = Op.getOperand(1);
8890   SDValue Amt = Op.getOperand(2);
8891   EVT AmtVT = Amt.getValueType();
8892 
8893   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8894                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8895   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8896   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8897   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8898   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8899                              DAG.getConstant(-BitWidth, dl, AmtVT));
8900   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8901   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8902   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8903   SDValue OutOps[] = { OutLo, OutHi };
8904   return DAG.getMergeValues(OutOps, dl);
8905 }
8906 
8907 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8908   EVT VT = Op.getValueType();
8909   SDLoc dl(Op);
8910   unsigned BitWidth = VT.getSizeInBits();
8911   assert(Op.getNumOperands() == 3 &&
8912          VT == Op.getOperand(1).getValueType() &&
8913          "Unexpected SRL!");
8914 
8915   // Expand into a bunch of logical ops.  Note that these ops
8916   // depend on the PPC behavior for oversized shift amounts.
8917   SDValue Lo = Op.getOperand(0);
8918   SDValue Hi = Op.getOperand(1);
8919   SDValue Amt = Op.getOperand(2);
8920   EVT AmtVT = Amt.getValueType();
8921 
8922   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8923                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8924   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8925   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8926   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8927   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8928                              DAG.getConstant(-BitWidth, dl, AmtVT));
8929   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8930   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8931   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8932   SDValue OutOps[] = { OutLo, OutHi };
8933   return DAG.getMergeValues(OutOps, dl);
8934 }
8935 
8936 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8937   SDLoc dl(Op);
8938   EVT VT = Op.getValueType();
8939   unsigned BitWidth = VT.getSizeInBits();
8940   assert(Op.getNumOperands() == 3 &&
8941          VT == Op.getOperand(1).getValueType() &&
8942          "Unexpected SRA!");
8943 
8944   // Expand into a bunch of logical ops, followed by a select_cc.
8945   SDValue Lo = Op.getOperand(0);
8946   SDValue Hi = Op.getOperand(1);
8947   SDValue Amt = Op.getOperand(2);
8948   EVT AmtVT = Amt.getValueType();
8949 
8950   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8951                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8952   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8953   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8954   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8955   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8956                              DAG.getConstant(-BitWidth, dl, AmtVT));
8957   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8958   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8959   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8960                                   Tmp4, Tmp6, ISD::SETLE);
8961   SDValue OutOps[] = { OutLo, OutHi };
8962   return DAG.getMergeValues(OutOps, dl);
8963 }
8964 
8965 //===----------------------------------------------------------------------===//
8966 // Vector related lowering.
8967 //
8968 
8969 /// BuildSplatI - Build a canonical splati of Val with an element size of
8970 /// SplatSize.  Cast the result to VT.
8971 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8972                            SelectionDAG &DAG, const SDLoc &dl) {
8973   static const MVT VTys[] = { // canonical VT to use for each size.
8974     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8975   };
8976 
8977   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8978 
8979   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8980   if (Val == -1)
8981     SplatSize = 1;
8982 
8983   EVT CanonicalVT = VTys[SplatSize-1];
8984 
8985   // Build a canonical splat for this value.
8986   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8987 }
8988 
8989 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8990 /// specified intrinsic ID.
8991 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8992                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8993   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8994   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8995                      DAG.getConstant(IID, dl, MVT::i32), Op);
8996 }
8997 
8998 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8999 /// specified intrinsic ID.
9000 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
9001                                 SelectionDAG &DAG, const SDLoc &dl,
9002                                 EVT DestVT = MVT::Other) {
9003   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9004   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9005                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9006 }
9007 
9008 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9009 /// specified intrinsic ID.
9010 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9011                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9012                                 EVT DestVT = MVT::Other) {
9013   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9014   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9015                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9016 }
9017 
9018 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9019 /// amount.  The result has the specified value type.
9020 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9021                            SelectionDAG &DAG, const SDLoc &dl) {
9022   // Force LHS/RHS to be the right type.
9023   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9024   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9025 
9026   int Ops[16];
9027   for (unsigned i = 0; i != 16; ++i)
9028     Ops[i] = i + Amt;
9029   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9030   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9031 }
9032 
9033 /// Do we have an efficient pattern in a .td file for this node?
9034 ///
9035 /// \param V - pointer to the BuildVectorSDNode being matched
9036 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9037 ///
9038 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9039 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9040 /// the opposite is true (expansion is beneficial) are:
9041 /// - The node builds a vector out of integers that are not 32 or 64-bits
9042 /// - The node builds a vector out of constants
9043 /// - The node is a "load-and-splat"
9044 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9045 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9046                                             bool HasDirectMove,
9047                                             bool HasP8Vector) {
9048   EVT VecVT = V->getValueType(0);
9049   bool RightType = VecVT == MVT::v2f64 ||
9050     (HasP8Vector && VecVT == MVT::v4f32) ||
9051     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9052   if (!RightType)
9053     return false;
9054 
9055   bool IsSplat = true;
9056   bool IsLoad = false;
9057   SDValue Op0 = V->getOperand(0);
9058 
9059   // This function is called in a block that confirms the node is not a constant
9060   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9061   // different constants.
9062   if (V->isConstant())
9063     return false;
9064   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9065     if (V->getOperand(i).isUndef())
9066       return false;
9067     // We want to expand nodes that represent load-and-splat even if the
9068     // loaded value is a floating point truncation or conversion to int.
9069     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9070         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9071          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9072         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9073          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9074         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9075          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9076       IsLoad = true;
9077     // If the operands are different or the input is not a load and has more
9078     // uses than just this BV node, then it isn't a splat.
9079     if (V->getOperand(i) != Op0 ||
9080         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9081       IsSplat = false;
9082   }
9083   return !(IsSplat && IsLoad);
9084 }
9085 
9086 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9087 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9088 
9089   SDLoc dl(Op);
9090   SDValue Op0 = Op->getOperand(0);
9091 
9092   if (!EnableQuadPrecision ||
9093       (Op.getValueType() != MVT::f128 ) ||
9094       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9095       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
9096       (Op0.getOperand(1).getValueType() != MVT::i64))
9097     return SDValue();
9098 
9099   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9100                      Op0.getOperand(1));
9101 }
9102 
9103 static const SDValue *getNormalLoadInput(const SDValue &Op) {
9104   const SDValue *InputLoad = &Op;
9105   if (InputLoad->getOpcode() == ISD::BITCAST)
9106     InputLoad = &InputLoad->getOperand(0);
9107   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9108       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED)
9109     InputLoad = &InputLoad->getOperand(0);
9110   if (InputLoad->getOpcode() != ISD::LOAD)
9111     return nullptr;
9112   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9113   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9114 }
9115 
9116 // If this is a case we can't handle, return null and let the default
9117 // expansion code take care of it.  If we CAN select this case, and if it
9118 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9119 // this case more efficiently than a constant pool load, lower it to the
9120 // sequence of ops that should be used.
9121 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9122                                              SelectionDAG &DAG) const {
9123   SDLoc dl(Op);
9124   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9125   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9126 
9127   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
9128     // We first build an i32 vector, load it into a QPX register,
9129     // then convert it to a floating-point vector and compare it
9130     // to a zero vector to get the boolean result.
9131     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9132     int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
9133     MachinePointerInfo PtrInfo =
9134         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9135     EVT PtrVT = getPointerTy(DAG.getDataLayout());
9136     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9137 
9138     assert(BVN->getNumOperands() == 4 &&
9139       "BUILD_VECTOR for v4i1 does not have 4 operands");
9140 
9141     bool IsConst = true;
9142     for (unsigned i = 0; i < 4; ++i) {
9143       if (BVN->getOperand(i).isUndef()) continue;
9144       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
9145         IsConst = false;
9146         break;
9147       }
9148     }
9149 
9150     if (IsConst) {
9151       Constant *One =
9152         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
9153       Constant *NegOne =
9154         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
9155 
9156       Constant *CV[4];
9157       for (unsigned i = 0; i < 4; ++i) {
9158         if (BVN->getOperand(i).isUndef())
9159           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
9160         else if (isNullConstant(BVN->getOperand(i)))
9161           CV[i] = NegOne;
9162         else
9163           CV[i] = One;
9164       }
9165 
9166       Constant *CP = ConstantVector::get(CV);
9167       SDValue CPIdx =
9168           DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16));
9169 
9170       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
9171       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
9172       return DAG.getMemIntrinsicNode(
9173           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
9174           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
9175     }
9176 
9177     SmallVector<SDValue, 4> Stores;
9178     for (unsigned i = 0; i < 4; ++i) {
9179       if (BVN->getOperand(i).isUndef()) continue;
9180 
9181       unsigned Offset = 4*i;
9182       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9183       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9184 
9185       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
9186       if (StoreSize > 4) {
9187         Stores.push_back(
9188             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
9189                               PtrInfo.getWithOffset(Offset), MVT::i32));
9190       } else {
9191         SDValue StoreValue = BVN->getOperand(i);
9192         if (StoreSize < 4)
9193           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
9194 
9195         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
9196                                       PtrInfo.getWithOffset(Offset)));
9197       }
9198     }
9199 
9200     SDValue StoreChain;
9201     if (!Stores.empty())
9202       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9203     else
9204       StoreChain = DAG.getEntryNode();
9205 
9206     // Now load from v4i32 into the QPX register; this will extend it to
9207     // v4i64 but not yet convert it to a floating point. Nevertheless, this
9208     // is typed as v4f64 because the QPX register integer states are not
9209     // explicitly represented.
9210 
9211     SDValue Ops[] = {StoreChain,
9212                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
9213                      FIdx};
9214     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
9215 
9216     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
9217       dl, VTs, Ops, MVT::v4i32, PtrInfo);
9218     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9219       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
9220       LoadedVect);
9221 
9222     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
9223 
9224     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
9225   }
9226 
9227   // All other QPX vectors are handled by generic code.
9228   if (Subtarget.hasQPX())
9229     return SDValue();
9230 
9231   // Check if this is a splat of a constant value.
9232   APInt APSplatBits, APSplatUndef;
9233   unsigned SplatBitSize;
9234   bool HasAnyUndefs;
9235   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9236                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9237       SplatBitSize > 32) {
9238 
9239     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
9240     // Handle load-and-splat patterns as we have instructions that will do this
9241     // in one go.
9242     if (InputLoad && DAG.isSplatValue(Op, true)) {
9243       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9244 
9245       // We have handling for 4 and 8 byte elements.
9246       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9247 
9248       // Checking for a single use of this load, we have to check for vector
9249       // width (128 bits) / ElementSize uses (since each operand of the
9250       // BUILD_VECTOR is a separate use of the value.
9251       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9252           ((Subtarget.hasVSX() && ElementSize == 64) ||
9253            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9254         SDValue Ops[] = {
9255           LD->getChain(),    // Chain
9256           LD->getBasePtr(),  // Ptr
9257           DAG.getValueType(Op.getValueType()) // VT
9258         };
9259         return
9260           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9261                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9262                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9263       }
9264     }
9265 
9266     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9267     // lowered to VSX instructions under certain conditions.
9268     // Without VSX, there is no pattern more efficient than expanding the node.
9269     if (Subtarget.hasVSX() &&
9270         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9271                                         Subtarget.hasP8Vector()))
9272       return Op;
9273     return SDValue();
9274   }
9275 
9276   unsigned SplatBits = APSplatBits.getZExtValue();
9277   unsigned SplatUndef = APSplatUndef.getZExtValue();
9278   unsigned SplatSize = SplatBitSize / 8;
9279 
9280   // First, handle single instruction cases.
9281 
9282   // All zeros?
9283   if (SplatBits == 0) {
9284     // Canonicalize all zero vectors to be v4i32.
9285     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9286       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9287       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9288     }
9289     return Op;
9290   }
9291 
9292   // We have XXSPLTIB for constant splats one byte wide
9293   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
9294   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
9295   if (Subtarget.hasP9Vector() && SplatSize == 1)
9296     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
9297 
9298   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9299   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9300                     (32-SplatBitSize));
9301   if (SextVal >= -16 && SextVal <= 15)
9302     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
9303 
9304   // Two instruction sequences.
9305 
9306   // If this value is in the range [-32,30] and is even, use:
9307   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9308   // If this value is in the range [17,31] and is odd, use:
9309   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9310   // If this value is in the range [-31,-17] and is odd, use:
9311   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9312   // Note the last two are three-instruction sequences.
9313   if (SextVal >= -32 && SextVal <= 31) {
9314     // To avoid having these optimizations undone by constant folding,
9315     // we convert to a pseudo that will be expanded later into one of
9316     // the above forms.
9317     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9318     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9319               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9320     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9321     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9322     if (VT == Op.getValueType())
9323       return RetVal;
9324     else
9325       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9326   }
9327 
9328   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9329   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9330   // for fneg/fabs.
9331   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9332     // Make -1 and vspltisw -1:
9333     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
9334 
9335     // Make the VSLW intrinsic, computing 0x8000_0000.
9336     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9337                                    OnesV, DAG, dl);
9338 
9339     // xor by OnesV to invert it.
9340     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9341     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9342   }
9343 
9344   // Check to see if this is a wide variety of vsplti*, binop self cases.
9345   static const signed char SplatCsts[] = {
9346     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9347     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9348   };
9349 
9350   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9351     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9352     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9353     int i = SplatCsts[idx];
9354 
9355     // Figure out what shift amount will be used by altivec if shifted by i in
9356     // this splat size.
9357     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9358 
9359     // vsplti + shl self.
9360     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9361       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9362       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9363         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9364         Intrinsic::ppc_altivec_vslw
9365       };
9366       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9367       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9368     }
9369 
9370     // vsplti + srl self.
9371     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9372       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9373       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9374         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9375         Intrinsic::ppc_altivec_vsrw
9376       };
9377       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9378       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9379     }
9380 
9381     // vsplti + sra self.
9382     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9383       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9384       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9385         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9386         Intrinsic::ppc_altivec_vsraw
9387       };
9388       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9389       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9390     }
9391 
9392     // vsplti + rol self.
9393     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9394                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9395       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9396       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9397         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9398         Intrinsic::ppc_altivec_vrlw
9399       };
9400       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9401       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9402     }
9403 
9404     // t = vsplti c, result = vsldoi t, t, 1
9405     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9406       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9407       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9408       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9409     }
9410     // t = vsplti c, result = vsldoi t, t, 2
9411     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9412       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9413       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9414       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9415     }
9416     // t = vsplti c, result = vsldoi t, t, 3
9417     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9418       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9419       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9420       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9421     }
9422   }
9423 
9424   return SDValue();
9425 }
9426 
9427 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9428 /// the specified operations to build the shuffle.
9429 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9430                                       SDValue RHS, SelectionDAG &DAG,
9431                                       const SDLoc &dl) {
9432   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9433   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9434   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9435 
9436   enum {
9437     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9438     OP_VMRGHW,
9439     OP_VMRGLW,
9440     OP_VSPLTISW0,
9441     OP_VSPLTISW1,
9442     OP_VSPLTISW2,
9443     OP_VSPLTISW3,
9444     OP_VSLDOI4,
9445     OP_VSLDOI8,
9446     OP_VSLDOI12
9447   };
9448 
9449   if (OpNum == OP_COPY) {
9450     if (LHSID == (1*9+2)*9+3) return LHS;
9451     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9452     return RHS;
9453   }
9454 
9455   SDValue OpLHS, OpRHS;
9456   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9457   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9458 
9459   int ShufIdxs[16];
9460   switch (OpNum) {
9461   default: llvm_unreachable("Unknown i32 permute!");
9462   case OP_VMRGHW:
9463     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9464     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9465     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9466     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9467     break;
9468   case OP_VMRGLW:
9469     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9470     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9471     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9472     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9473     break;
9474   case OP_VSPLTISW0:
9475     for (unsigned i = 0; i != 16; ++i)
9476       ShufIdxs[i] = (i&3)+0;
9477     break;
9478   case OP_VSPLTISW1:
9479     for (unsigned i = 0; i != 16; ++i)
9480       ShufIdxs[i] = (i&3)+4;
9481     break;
9482   case OP_VSPLTISW2:
9483     for (unsigned i = 0; i != 16; ++i)
9484       ShufIdxs[i] = (i&3)+8;
9485     break;
9486   case OP_VSPLTISW3:
9487     for (unsigned i = 0; i != 16; ++i)
9488       ShufIdxs[i] = (i&3)+12;
9489     break;
9490   case OP_VSLDOI4:
9491     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9492   case OP_VSLDOI8:
9493     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9494   case OP_VSLDOI12:
9495     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9496   }
9497   EVT VT = OpLHS.getValueType();
9498   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9499   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9500   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9501   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9502 }
9503 
9504 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9505 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9506 /// SDValue.
9507 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9508                                            SelectionDAG &DAG) const {
9509   const unsigned BytesInVector = 16;
9510   bool IsLE = Subtarget.isLittleEndian();
9511   SDLoc dl(N);
9512   SDValue V1 = N->getOperand(0);
9513   SDValue V2 = N->getOperand(1);
9514   unsigned ShiftElts = 0, InsertAtByte = 0;
9515   bool Swap = false;
9516 
9517   // Shifts required to get the byte we want at element 7.
9518   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9519                                    0, 15, 14, 13, 12, 11, 10, 9};
9520   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9521                                 1, 2,  3,  4,  5,  6,  7,  8};
9522 
9523   ArrayRef<int> Mask = N->getMask();
9524   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9525 
9526   // For each mask element, find out if we're just inserting something
9527   // from V2 into V1 or vice versa.
9528   // Possible permutations inserting an element from V2 into V1:
9529   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9530   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9531   //   ...
9532   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9533   // Inserting from V1 into V2 will be similar, except mask range will be
9534   // [16,31].
9535 
9536   bool FoundCandidate = false;
9537   // If both vector operands for the shuffle are the same vector, the mask
9538   // will contain only elements from the first one and the second one will be
9539   // undef.
9540   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9541   // Go through the mask of half-words to find an element that's being moved
9542   // from one vector to the other.
9543   for (unsigned i = 0; i < BytesInVector; ++i) {
9544     unsigned CurrentElement = Mask[i];
9545     // If 2nd operand is undefined, we should only look for element 7 in the
9546     // Mask.
9547     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9548       continue;
9549 
9550     bool OtherElementsInOrder = true;
9551     // Examine the other elements in the Mask to see if they're in original
9552     // order.
9553     for (unsigned j = 0; j < BytesInVector; ++j) {
9554       if (j == i)
9555         continue;
9556       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9557       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9558       // in which we always assume we're always picking from the 1st operand.
9559       int MaskOffset =
9560           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9561       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9562         OtherElementsInOrder = false;
9563         break;
9564       }
9565     }
9566     // If other elements are in original order, we record the number of shifts
9567     // we need to get the element we want into element 7. Also record which byte
9568     // in the vector we should insert into.
9569     if (OtherElementsInOrder) {
9570       // If 2nd operand is undefined, we assume no shifts and no swapping.
9571       if (V2.isUndef()) {
9572         ShiftElts = 0;
9573         Swap = false;
9574       } else {
9575         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9576         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9577                          : BigEndianShifts[CurrentElement & 0xF];
9578         Swap = CurrentElement < BytesInVector;
9579       }
9580       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9581       FoundCandidate = true;
9582       break;
9583     }
9584   }
9585 
9586   if (!FoundCandidate)
9587     return SDValue();
9588 
9589   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9590   // optionally with VECSHL if shift is required.
9591   if (Swap)
9592     std::swap(V1, V2);
9593   if (V2.isUndef())
9594     V2 = V1;
9595   if (ShiftElts) {
9596     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9597                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9598     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9599                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9600   }
9601   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9602                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9603 }
9604 
9605 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9606 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9607 /// SDValue.
9608 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9609                                            SelectionDAG &DAG) const {
9610   const unsigned NumHalfWords = 8;
9611   const unsigned BytesInVector = NumHalfWords * 2;
9612   // Check that the shuffle is on half-words.
9613   if (!isNByteElemShuffleMask(N, 2, 1))
9614     return SDValue();
9615 
9616   bool IsLE = Subtarget.isLittleEndian();
9617   SDLoc dl(N);
9618   SDValue V1 = N->getOperand(0);
9619   SDValue V2 = N->getOperand(1);
9620   unsigned ShiftElts = 0, InsertAtByte = 0;
9621   bool Swap = false;
9622 
9623   // Shifts required to get the half-word we want at element 3.
9624   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9625   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9626 
9627   uint32_t Mask = 0;
9628   uint32_t OriginalOrderLow = 0x1234567;
9629   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9630   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9631   // 32-bit space, only need 4-bit nibbles per element.
9632   for (unsigned i = 0; i < NumHalfWords; ++i) {
9633     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9634     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9635   }
9636 
9637   // For each mask element, find out if we're just inserting something
9638   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9639   // from V2 into V1:
9640   //   X, 1, 2, 3, 4, 5, 6, 7
9641   //   0, X, 2, 3, 4, 5, 6, 7
9642   //   0, 1, X, 3, 4, 5, 6, 7
9643   //   0, 1, 2, X, 4, 5, 6, 7
9644   //   0, 1, 2, 3, X, 5, 6, 7
9645   //   0, 1, 2, 3, 4, X, 6, 7
9646   //   0, 1, 2, 3, 4, 5, X, 7
9647   //   0, 1, 2, 3, 4, 5, 6, X
9648   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9649 
9650   bool FoundCandidate = false;
9651   // Go through the mask of half-words to find an element that's being moved
9652   // from one vector to the other.
9653   for (unsigned i = 0; i < NumHalfWords; ++i) {
9654     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9655     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9656     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9657     uint32_t TargetOrder = 0x0;
9658 
9659     // If both vector operands for the shuffle are the same vector, the mask
9660     // will contain only elements from the first one and the second one will be
9661     // undef.
9662     if (V2.isUndef()) {
9663       ShiftElts = 0;
9664       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9665       TargetOrder = OriginalOrderLow;
9666       Swap = false;
9667       // Skip if not the correct element or mask of other elements don't equal
9668       // to our expected order.
9669       if (MaskOneElt == VINSERTHSrcElem &&
9670           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9671         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9672         FoundCandidate = true;
9673         break;
9674       }
9675     } else { // If both operands are defined.
9676       // Target order is [8,15] if the current mask is between [0,7].
9677       TargetOrder =
9678           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9679       // Skip if mask of other elements don't equal our expected order.
9680       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9681         // We only need the last 3 bits for the number of shifts.
9682         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9683                          : BigEndianShifts[MaskOneElt & 0x7];
9684         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9685         Swap = MaskOneElt < NumHalfWords;
9686         FoundCandidate = true;
9687         break;
9688       }
9689     }
9690   }
9691 
9692   if (!FoundCandidate)
9693     return SDValue();
9694 
9695   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9696   // optionally with VECSHL if shift is required.
9697   if (Swap)
9698     std::swap(V1, V2);
9699   if (V2.isUndef())
9700     V2 = V1;
9701   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9702   if (ShiftElts) {
9703     // Double ShiftElts because we're left shifting on v16i8 type.
9704     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9705                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9706     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9707     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9708                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9709     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9710   }
9711   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9712   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9713                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9714   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9715 }
9716 
9717 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9718 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9719 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9720 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9721 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9722   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9723   assert(Op.getValueType() == MVT::v1i128 &&
9724          "Only set v1i128 as custom, other type shouldn't reach here!");
9725   SDLoc dl(Op);
9726   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9727   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9728   unsigned SHLAmt = N1.getConstantOperandVal(0);
9729   if (SHLAmt % 8 == 0) {
9730     SmallVector<int, 16> Mask(16, 0);
9731     std::iota(Mask.begin(), Mask.end(), 0);
9732     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9733     if (SDValue Shuffle =
9734             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9735                                  DAG.getUNDEF(MVT::v16i8), Mask))
9736       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9737   }
9738   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9739   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9740                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9741   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9742                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9743   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9744   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9745 }
9746 
9747 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9748 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9749 /// return the code it can be lowered into.  Worst case, it can always be
9750 /// lowered into a vperm.
9751 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9752                                                SelectionDAG &DAG) const {
9753   SDLoc dl(Op);
9754   SDValue V1 = Op.getOperand(0);
9755   SDValue V2 = Op.getOperand(1);
9756   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9757 
9758   // Any nodes that were combined in the target-independent combiner prior
9759   // to vector legalization will not be sent to the target combine. Try to
9760   // combine it here.
9761   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9762     DAG.ReplaceAllUsesOfValueWith(Op, NewShuffle);
9763     Op = NewShuffle;
9764     SVOp = cast<ShuffleVectorSDNode>(Op);
9765   }
9766   EVT VT = Op.getValueType();
9767   bool isLittleEndian = Subtarget.isLittleEndian();
9768 
9769   unsigned ShiftElts, InsertAtByte;
9770   bool Swap = false;
9771 
9772   // If this is a load-and-splat, we can do that with a single instruction
9773   // in some cases. However if the load has multiple uses, we don't want to
9774   // combine it because that will just produce multiple loads.
9775   const SDValue *InputLoad = getNormalLoadInput(V1);
9776   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9777       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9778       InputLoad->hasOneUse()) {
9779     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9780     int SplatIdx =
9781       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9782 
9783     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9784     // For 4-byte load-and-splat, we need Power9.
9785     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9786       uint64_t Offset = 0;
9787       if (IsFourByte)
9788         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9789       else
9790         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9791 
9792       // If we are loading a partial vector, it does not make sense to adjust
9793       // the base pointer. This happens with (splat (s_to_v_permuted (ld))).
9794       if (LD->getMemoryVT().getSizeInBits() == (IsFourByte ? 32 : 64))
9795         Offset = 0;
9796       SDValue BasePtr = LD->getBasePtr();
9797       if (Offset != 0)
9798         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9799                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9800       SDValue Ops[] = {
9801         LD->getChain(),    // Chain
9802         BasePtr,           // BasePtr
9803         DAG.getValueType(Op.getValueType()) // VT
9804       };
9805       SDVTList VTL =
9806         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9807       SDValue LdSplt =
9808         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9809                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9810       if (LdSplt.getValueType() != SVOp->getValueType(0))
9811         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9812       return LdSplt;
9813     }
9814   }
9815   if (Subtarget.hasP9Vector() &&
9816       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9817                            isLittleEndian)) {
9818     if (Swap)
9819       std::swap(V1, V2);
9820     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9821     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9822     if (ShiftElts) {
9823       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9824                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9825       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9826                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9827       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9828     }
9829     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9830                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9831     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9832   }
9833 
9834   if (Subtarget.hasP9Altivec()) {
9835     SDValue NewISDNode;
9836     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9837       return NewISDNode;
9838 
9839     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9840       return NewISDNode;
9841   }
9842 
9843   if (Subtarget.hasVSX() &&
9844       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9845     if (Swap)
9846       std::swap(V1, V2);
9847     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9848     SDValue Conv2 =
9849         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9850 
9851     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9852                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9853     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9854   }
9855 
9856   if (Subtarget.hasVSX() &&
9857     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9858     if (Swap)
9859       std::swap(V1, V2);
9860     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9861     SDValue Conv2 =
9862         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9863 
9864     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9865                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9866     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9867   }
9868 
9869   if (Subtarget.hasP9Vector()) {
9870      if (PPC::isXXBRHShuffleMask(SVOp)) {
9871       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9872       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9873       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9874     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9875       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9876       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9877       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9878     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9879       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9880       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9881       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9882     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9883       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9884       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9885       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9886     }
9887   }
9888 
9889   if (Subtarget.hasVSX()) {
9890     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9891       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9892 
9893       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9894       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9895                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9896       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9897     }
9898 
9899     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9900     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9901       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9902       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9903       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9904     }
9905   }
9906 
9907   if (Subtarget.hasQPX()) {
9908     if (VT.getVectorNumElements() != 4)
9909       return SDValue();
9910 
9911     if (V2.isUndef()) V2 = V1;
9912 
9913     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9914     if (AlignIdx != -1) {
9915       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9916                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9917     } else if (SVOp->isSplat()) {
9918       int SplatIdx = SVOp->getSplatIndex();
9919       if (SplatIdx >= 4) {
9920         std::swap(V1, V2);
9921         SplatIdx -= 4;
9922       }
9923 
9924       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9925                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9926     }
9927 
9928     // Lower this into a qvgpci/qvfperm pair.
9929 
9930     // Compute the qvgpci literal
9931     unsigned idx = 0;
9932     for (unsigned i = 0; i < 4; ++i) {
9933       int m = SVOp->getMaskElt(i);
9934       unsigned mm = m >= 0 ? (unsigned) m : i;
9935       idx |= mm << (3-i)*3;
9936     }
9937 
9938     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9939                              DAG.getConstant(idx, dl, MVT::i32));
9940     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9941   }
9942 
9943   // Cases that are handled by instructions that take permute immediates
9944   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9945   // selected by the instruction selector.
9946   if (V2.isUndef()) {
9947     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9948         PPC::isSplatShuffleMask(SVOp, 2) ||
9949         PPC::isSplatShuffleMask(SVOp, 4) ||
9950         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9951         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9952         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9953         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9954         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9955         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9956         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9957         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9958         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9959         (Subtarget.hasP8Altivec() && (
9960          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9961          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9962          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9963       return Op;
9964     }
9965   }
9966 
9967   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9968   // and produce a fixed permutation.  If any of these match, do not lower to
9969   // VPERM.
9970   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9971   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9972       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9973       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9974       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9975       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9976       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9977       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9978       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9979       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9980       (Subtarget.hasP8Altivec() && (
9981        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9982        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9983        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9984     return Op;
9985 
9986   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9987   // perfect shuffle table to emit an optimal matching sequence.
9988   ArrayRef<int> PermMask = SVOp->getMask();
9989 
9990   unsigned PFIndexes[4];
9991   bool isFourElementShuffle = true;
9992   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9993     unsigned EltNo = 8;   // Start out undef.
9994     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9995       if (PermMask[i*4+j] < 0)
9996         continue;   // Undef, ignore it.
9997 
9998       unsigned ByteSource = PermMask[i*4+j];
9999       if ((ByteSource & 3) != j) {
10000         isFourElementShuffle = false;
10001         break;
10002       }
10003 
10004       if (EltNo == 8) {
10005         EltNo = ByteSource/4;
10006       } else if (EltNo != ByteSource/4) {
10007         isFourElementShuffle = false;
10008         break;
10009       }
10010     }
10011     PFIndexes[i] = EltNo;
10012   }
10013 
10014   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10015   // perfect shuffle vector to determine if it is cost effective to do this as
10016   // discrete instructions, or whether we should use a vperm.
10017   // For now, we skip this for little endian until such time as we have a
10018   // little-endian perfect shuffle table.
10019   if (isFourElementShuffle && !isLittleEndian) {
10020     // Compute the index in the perfect shuffle table.
10021     unsigned PFTableIndex =
10022       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
10023 
10024     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10025     unsigned Cost  = (PFEntry >> 30);
10026 
10027     // Determining when to avoid vperm is tricky.  Many things affect the cost
10028     // of vperm, particularly how many times the perm mask needs to be computed.
10029     // For example, if the perm mask can be hoisted out of a loop or is already
10030     // used (perhaps because there are multiple permutes with the same shuffle
10031     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
10032     // the loop requires an extra register.
10033     //
10034     // As a compromise, we only emit discrete instructions if the shuffle can be
10035     // generated in 3 or fewer operations.  When we have loop information
10036     // available, if this block is within a loop, we should avoid using vperm
10037     // for 3-operation perms and use a constant pool load instead.
10038     if (Cost < 3)
10039       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10040   }
10041 
10042   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10043   // vector that will get spilled to the constant pool.
10044   if (V2.isUndef()) V2 = V1;
10045 
10046   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10047   // that it is in input element units, not in bytes.  Convert now.
10048 
10049   // For little endian, the order of the input vectors is reversed, and
10050   // the permutation mask is complemented with respect to 31.  This is
10051   // necessary to produce proper semantics with the big-endian-biased vperm
10052   // instruction.
10053   EVT EltVT = V1.getValueType().getVectorElementType();
10054   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10055 
10056   SmallVector<SDValue, 16> ResultMask;
10057   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10058     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10059 
10060     for (unsigned j = 0; j != BytesPerElement; ++j)
10061       if (isLittleEndian)
10062         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10063                                              dl, MVT::i32));
10064       else
10065         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10066                                              MVT::i32));
10067   }
10068 
10069   ShufflesHandledWithVPERM++;
10070   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10071   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10072   LLVM_DEBUG(SVOp->dump());
10073   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10074   LLVM_DEBUG(VPermMask.dump());
10075 
10076   if (isLittleEndian)
10077     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10078                        V2, V1, VPermMask);
10079   else
10080     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10081                        V1, V2, VPermMask);
10082 }
10083 
10084 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10085 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10086 /// information about the intrinsic.
10087 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10088                                  bool &isDot, const PPCSubtarget &Subtarget) {
10089   unsigned IntrinsicID =
10090       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10091   CompareOpc = -1;
10092   isDot = false;
10093   switch (IntrinsicID) {
10094   default:
10095     return false;
10096   // Comparison predicates.
10097   case Intrinsic::ppc_altivec_vcmpbfp_p:
10098     CompareOpc = 966;
10099     isDot = true;
10100     break;
10101   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10102     CompareOpc = 198;
10103     isDot = true;
10104     break;
10105   case Intrinsic::ppc_altivec_vcmpequb_p:
10106     CompareOpc = 6;
10107     isDot = true;
10108     break;
10109   case Intrinsic::ppc_altivec_vcmpequh_p:
10110     CompareOpc = 70;
10111     isDot = true;
10112     break;
10113   case Intrinsic::ppc_altivec_vcmpequw_p:
10114     CompareOpc = 134;
10115     isDot = true;
10116     break;
10117   case Intrinsic::ppc_altivec_vcmpequd_p:
10118     if (Subtarget.hasP8Altivec()) {
10119       CompareOpc = 199;
10120       isDot = true;
10121     } else
10122       return false;
10123     break;
10124   case Intrinsic::ppc_altivec_vcmpneb_p:
10125   case Intrinsic::ppc_altivec_vcmpneh_p:
10126   case Intrinsic::ppc_altivec_vcmpnew_p:
10127   case Intrinsic::ppc_altivec_vcmpnezb_p:
10128   case Intrinsic::ppc_altivec_vcmpnezh_p:
10129   case Intrinsic::ppc_altivec_vcmpnezw_p:
10130     if (Subtarget.hasP9Altivec()) {
10131       switch (IntrinsicID) {
10132       default:
10133         llvm_unreachable("Unknown comparison intrinsic.");
10134       case Intrinsic::ppc_altivec_vcmpneb_p:
10135         CompareOpc = 7;
10136         break;
10137       case Intrinsic::ppc_altivec_vcmpneh_p:
10138         CompareOpc = 71;
10139         break;
10140       case Intrinsic::ppc_altivec_vcmpnew_p:
10141         CompareOpc = 135;
10142         break;
10143       case Intrinsic::ppc_altivec_vcmpnezb_p:
10144         CompareOpc = 263;
10145         break;
10146       case Intrinsic::ppc_altivec_vcmpnezh_p:
10147         CompareOpc = 327;
10148         break;
10149       case Intrinsic::ppc_altivec_vcmpnezw_p:
10150         CompareOpc = 391;
10151         break;
10152       }
10153       isDot = true;
10154     } else
10155       return false;
10156     break;
10157   case Intrinsic::ppc_altivec_vcmpgefp_p:
10158     CompareOpc = 454;
10159     isDot = true;
10160     break;
10161   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10162     CompareOpc = 710;
10163     isDot = true;
10164     break;
10165   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10166     CompareOpc = 774;
10167     isDot = true;
10168     break;
10169   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10170     CompareOpc = 838;
10171     isDot = true;
10172     break;
10173   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10174     CompareOpc = 902;
10175     isDot = true;
10176     break;
10177   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10178     if (Subtarget.hasP8Altivec()) {
10179       CompareOpc = 967;
10180       isDot = true;
10181     } else
10182       return false;
10183     break;
10184   case Intrinsic::ppc_altivec_vcmpgtub_p:
10185     CompareOpc = 518;
10186     isDot = true;
10187     break;
10188   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10189     CompareOpc = 582;
10190     isDot = true;
10191     break;
10192   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10193     CompareOpc = 646;
10194     isDot = true;
10195     break;
10196   case Intrinsic::ppc_altivec_vcmpgtud_p:
10197     if (Subtarget.hasP8Altivec()) {
10198       CompareOpc = 711;
10199       isDot = true;
10200     } else
10201       return false;
10202     break;
10203 
10204   // VSX predicate comparisons use the same infrastructure
10205   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10206   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10207   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10208   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10209   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10210   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10211     if (Subtarget.hasVSX()) {
10212       switch (IntrinsicID) {
10213       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10214         CompareOpc = 99;
10215         break;
10216       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10217         CompareOpc = 115;
10218         break;
10219       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10220         CompareOpc = 107;
10221         break;
10222       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10223         CompareOpc = 67;
10224         break;
10225       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10226         CompareOpc = 83;
10227         break;
10228       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10229         CompareOpc = 75;
10230         break;
10231       }
10232       isDot = true;
10233     } else
10234       return false;
10235     break;
10236 
10237   // Normal Comparisons.
10238   case Intrinsic::ppc_altivec_vcmpbfp:
10239     CompareOpc = 966;
10240     break;
10241   case Intrinsic::ppc_altivec_vcmpeqfp:
10242     CompareOpc = 198;
10243     break;
10244   case Intrinsic::ppc_altivec_vcmpequb:
10245     CompareOpc = 6;
10246     break;
10247   case Intrinsic::ppc_altivec_vcmpequh:
10248     CompareOpc = 70;
10249     break;
10250   case Intrinsic::ppc_altivec_vcmpequw:
10251     CompareOpc = 134;
10252     break;
10253   case Intrinsic::ppc_altivec_vcmpequd:
10254     if (Subtarget.hasP8Altivec())
10255       CompareOpc = 199;
10256     else
10257       return false;
10258     break;
10259   case Intrinsic::ppc_altivec_vcmpneb:
10260   case Intrinsic::ppc_altivec_vcmpneh:
10261   case Intrinsic::ppc_altivec_vcmpnew:
10262   case Intrinsic::ppc_altivec_vcmpnezb:
10263   case Intrinsic::ppc_altivec_vcmpnezh:
10264   case Intrinsic::ppc_altivec_vcmpnezw:
10265     if (Subtarget.hasP9Altivec())
10266       switch (IntrinsicID) {
10267       default:
10268         llvm_unreachable("Unknown comparison intrinsic.");
10269       case Intrinsic::ppc_altivec_vcmpneb:
10270         CompareOpc = 7;
10271         break;
10272       case Intrinsic::ppc_altivec_vcmpneh:
10273         CompareOpc = 71;
10274         break;
10275       case Intrinsic::ppc_altivec_vcmpnew:
10276         CompareOpc = 135;
10277         break;
10278       case Intrinsic::ppc_altivec_vcmpnezb:
10279         CompareOpc = 263;
10280         break;
10281       case Intrinsic::ppc_altivec_vcmpnezh:
10282         CompareOpc = 327;
10283         break;
10284       case Intrinsic::ppc_altivec_vcmpnezw:
10285         CompareOpc = 391;
10286         break;
10287       }
10288     else
10289       return false;
10290     break;
10291   case Intrinsic::ppc_altivec_vcmpgefp:
10292     CompareOpc = 454;
10293     break;
10294   case Intrinsic::ppc_altivec_vcmpgtfp:
10295     CompareOpc = 710;
10296     break;
10297   case Intrinsic::ppc_altivec_vcmpgtsb:
10298     CompareOpc = 774;
10299     break;
10300   case Intrinsic::ppc_altivec_vcmpgtsh:
10301     CompareOpc = 838;
10302     break;
10303   case Intrinsic::ppc_altivec_vcmpgtsw:
10304     CompareOpc = 902;
10305     break;
10306   case Intrinsic::ppc_altivec_vcmpgtsd:
10307     if (Subtarget.hasP8Altivec())
10308       CompareOpc = 967;
10309     else
10310       return false;
10311     break;
10312   case Intrinsic::ppc_altivec_vcmpgtub:
10313     CompareOpc = 518;
10314     break;
10315   case Intrinsic::ppc_altivec_vcmpgtuh:
10316     CompareOpc = 582;
10317     break;
10318   case Intrinsic::ppc_altivec_vcmpgtuw:
10319     CompareOpc = 646;
10320     break;
10321   case Intrinsic::ppc_altivec_vcmpgtud:
10322     if (Subtarget.hasP8Altivec())
10323       CompareOpc = 711;
10324     else
10325       return false;
10326     break;
10327   }
10328   return true;
10329 }
10330 
10331 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10332 /// lower, do it, otherwise return null.
10333 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10334                                                    SelectionDAG &DAG) const {
10335   unsigned IntrinsicID =
10336     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10337 
10338   SDLoc dl(Op);
10339 
10340   if (IntrinsicID == Intrinsic::thread_pointer) {
10341     // Reads the thread pointer register, used for __builtin_thread_pointer.
10342     if (Subtarget.isPPC64())
10343       return DAG.getRegister(PPC::X13, MVT::i64);
10344     return DAG.getRegister(PPC::R2, MVT::i32);
10345   }
10346 
10347   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10348   // opcode number of the comparison.
10349   int CompareOpc;
10350   bool isDot;
10351   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10352     return SDValue();    // Don't custom lower most intrinsics.
10353 
10354   // If this is a non-dot comparison, make the VCMP node and we are done.
10355   if (!isDot) {
10356     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10357                               Op.getOperand(1), Op.getOperand(2),
10358                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10359     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10360   }
10361 
10362   // Create the PPCISD altivec 'dot' comparison node.
10363   SDValue Ops[] = {
10364     Op.getOperand(2),  // LHS
10365     Op.getOperand(3),  // RHS
10366     DAG.getConstant(CompareOpc, dl, MVT::i32)
10367   };
10368   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10369   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10370 
10371   // Now that we have the comparison, emit a copy from the CR to a GPR.
10372   // This is flagged to the above dot comparison.
10373   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10374                                 DAG.getRegister(PPC::CR6, MVT::i32),
10375                                 CompNode.getValue(1));
10376 
10377   // Unpack the result based on how the target uses it.
10378   unsigned BitNo;   // Bit # of CR6.
10379   bool InvertBit;   // Invert result?
10380   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10381   default:  // Can't happen, don't crash on invalid number though.
10382   case 0:   // Return the value of the EQ bit of CR6.
10383     BitNo = 0; InvertBit = false;
10384     break;
10385   case 1:   // Return the inverted value of the EQ bit of CR6.
10386     BitNo = 0; InvertBit = true;
10387     break;
10388   case 2:   // Return the value of the LT bit of CR6.
10389     BitNo = 2; InvertBit = false;
10390     break;
10391   case 3:   // Return the inverted value of the LT bit of CR6.
10392     BitNo = 2; InvertBit = true;
10393     break;
10394   }
10395 
10396   // Shift the bit into the low position.
10397   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10398                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10399   // Isolate the bit.
10400   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10401                       DAG.getConstant(1, dl, MVT::i32));
10402 
10403   // If we are supposed to, toggle the bit.
10404   if (InvertBit)
10405     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10406                         DAG.getConstant(1, dl, MVT::i32));
10407   return Flags;
10408 }
10409 
10410 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10411                                                SelectionDAG &DAG) const {
10412   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10413   // the beginning of the argument list.
10414   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10415   SDLoc DL(Op);
10416   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10417   case Intrinsic::ppc_cfence: {
10418     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10419     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10420     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10421                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10422                                                   Op.getOperand(ArgStart + 1)),
10423                                       Op.getOperand(0)),
10424                    0);
10425   }
10426   default:
10427     break;
10428   }
10429   return SDValue();
10430 }
10431 
10432 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10433   // Check for a DIV with the same operands as this REM.
10434   for (auto UI : Op.getOperand(1)->uses()) {
10435     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10436         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10437       if (UI->getOperand(0) == Op.getOperand(0) &&
10438           UI->getOperand(1) == Op.getOperand(1))
10439         return SDValue();
10440   }
10441   return Op;
10442 }
10443 
10444 // Lower scalar BSWAP64 to xxbrd.
10445 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10446   SDLoc dl(Op);
10447   // MTVSRDD
10448   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10449                    Op.getOperand(0));
10450   // XXBRD
10451   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10452   // MFVSRD
10453   int VectorIndex = 0;
10454   if (Subtarget.isLittleEndian())
10455     VectorIndex = 1;
10456   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10457                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10458   return Op;
10459 }
10460 
10461 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10462 // compared to a value that is atomically loaded (atomic loads zero-extend).
10463 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10464                                                 SelectionDAG &DAG) const {
10465   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10466          "Expecting an atomic compare-and-swap here.");
10467   SDLoc dl(Op);
10468   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10469   EVT MemVT = AtomicNode->getMemoryVT();
10470   if (MemVT.getSizeInBits() >= 32)
10471     return Op;
10472 
10473   SDValue CmpOp = Op.getOperand(2);
10474   // If this is already correctly zero-extended, leave it alone.
10475   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10476   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10477     return Op;
10478 
10479   // Clear the high bits of the compare operand.
10480   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10481   SDValue NewCmpOp =
10482     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10483                 DAG.getConstant(MaskVal, dl, MVT::i32));
10484 
10485   // Replace the existing compare operand with the properly zero-extended one.
10486   SmallVector<SDValue, 4> Ops;
10487   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10488     Ops.push_back(AtomicNode->getOperand(i));
10489   Ops[2] = NewCmpOp;
10490   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10491   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10492   auto NodeTy =
10493     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10494   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10495 }
10496 
10497 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10498                                                  SelectionDAG &DAG) const {
10499   SDLoc dl(Op);
10500   // Create a stack slot that is 16-byte aligned.
10501   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10502   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10503   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10504   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10505 
10506   // Store the input value into Value#0 of the stack slot.
10507   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10508                                MachinePointerInfo());
10509   // Load it out.
10510   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10511 }
10512 
10513 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10514                                                   SelectionDAG &DAG) const {
10515   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10516          "Should only be called for ISD::INSERT_VECTOR_ELT");
10517 
10518   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10519   // We have legal lowering for constant indices but not for variable ones.
10520   if (!C)
10521     return SDValue();
10522 
10523   EVT VT = Op.getValueType();
10524   SDLoc dl(Op);
10525   SDValue V1 = Op.getOperand(0);
10526   SDValue V2 = Op.getOperand(1);
10527   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10528   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10529     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10530     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10531     unsigned InsertAtElement = C->getZExtValue();
10532     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10533     if (Subtarget.isLittleEndian()) {
10534       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10535     }
10536     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10537                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10538   }
10539   return Op;
10540 }
10541 
10542 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10543                                                    SelectionDAG &DAG) const {
10544   SDLoc dl(Op);
10545   SDNode *N = Op.getNode();
10546 
10547   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10548          "Unknown extract_vector_elt type");
10549 
10550   SDValue Value = N->getOperand(0);
10551 
10552   // The first part of this is like the store lowering except that we don't
10553   // need to track the chain.
10554 
10555   // The values are now known to be -1 (false) or 1 (true). To convert this
10556   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10557   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10558   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10559 
10560   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10561   // understand how to form the extending load.
10562   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10563 
10564   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10565 
10566   // Now convert to an integer and store.
10567   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10568     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10569     Value);
10570 
10571   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10572   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10573   MachinePointerInfo PtrInfo =
10574       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10575   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10576   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10577 
10578   SDValue StoreChain = DAG.getEntryNode();
10579   SDValue Ops[] = {StoreChain,
10580                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10581                    Value, FIdx};
10582   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10583 
10584   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10585     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10586 
10587   // Extract the value requested.
10588   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10589   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10590   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10591 
10592   SDValue IntVal =
10593       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10594 
10595   if (!Subtarget.useCRBits())
10596     return IntVal;
10597 
10598   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10599 }
10600 
10601 /// Lowering for QPX v4i1 loads
10602 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10603                                            SelectionDAG &DAG) const {
10604   SDLoc dl(Op);
10605   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10606   SDValue LoadChain = LN->getChain();
10607   SDValue BasePtr = LN->getBasePtr();
10608 
10609   if (Op.getValueType() == MVT::v4f64 ||
10610       Op.getValueType() == MVT::v4f32) {
10611     EVT MemVT = LN->getMemoryVT();
10612     unsigned Alignment = LN->getAlignment();
10613 
10614     // If this load is properly aligned, then it is legal.
10615     if (Alignment >= MemVT.getStoreSize())
10616       return Op;
10617 
10618     EVT ScalarVT = Op.getValueType().getScalarType(),
10619         ScalarMemVT = MemVT.getScalarType();
10620     unsigned Stride = ScalarMemVT.getStoreSize();
10621 
10622     SDValue Vals[4], LoadChains[4];
10623     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10624       SDValue Load;
10625       if (ScalarVT != ScalarMemVT)
10626         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10627                               BasePtr,
10628                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10629                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10630                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10631       else
10632         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10633                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10634                            MinAlign(Alignment, Idx * Stride),
10635                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10636 
10637       if (Idx == 0 && LN->isIndexed()) {
10638         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10639                "Unknown addressing mode on vector load");
10640         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10641                                   LN->getAddressingMode());
10642       }
10643 
10644       Vals[Idx] = Load;
10645       LoadChains[Idx] = Load.getValue(1);
10646 
10647       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10648                             DAG.getConstant(Stride, dl,
10649                                             BasePtr.getValueType()));
10650     }
10651 
10652     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10653     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10654 
10655     if (LN->isIndexed()) {
10656       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10657       return DAG.getMergeValues(RetOps, dl);
10658     }
10659 
10660     SDValue RetOps[] = { Value, TF };
10661     return DAG.getMergeValues(RetOps, dl);
10662   }
10663 
10664   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10665   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10666 
10667   // To lower v4i1 from a byte array, we load the byte elements of the
10668   // vector and then reuse the BUILD_VECTOR logic.
10669 
10670   SDValue VectElmts[4], VectElmtChains[4];
10671   for (unsigned i = 0; i < 4; ++i) {
10672     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10673     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10674 
10675     VectElmts[i] = DAG.getExtLoad(
10676         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10677         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10678         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10679     VectElmtChains[i] = VectElmts[i].getValue(1);
10680   }
10681 
10682   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10683   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10684 
10685   SDValue RVals[] = { Value, LoadChain };
10686   return DAG.getMergeValues(RVals, dl);
10687 }
10688 
10689 /// Lowering for QPX v4i1 stores
10690 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10691                                             SelectionDAG &DAG) const {
10692   SDLoc dl(Op);
10693   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10694   SDValue StoreChain = SN->getChain();
10695   SDValue BasePtr = SN->getBasePtr();
10696   SDValue Value = SN->getValue();
10697 
10698   if (Value.getValueType() == MVT::v4f64 ||
10699       Value.getValueType() == MVT::v4f32) {
10700     EVT MemVT = SN->getMemoryVT();
10701     unsigned Alignment = SN->getAlignment();
10702 
10703     // If this store is properly aligned, then it is legal.
10704     if (Alignment >= MemVT.getStoreSize())
10705       return Op;
10706 
10707     EVT ScalarVT = Value.getValueType().getScalarType(),
10708         ScalarMemVT = MemVT.getScalarType();
10709     unsigned Stride = ScalarMemVT.getStoreSize();
10710 
10711     SDValue Stores[4];
10712     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10713       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10714                                DAG.getVectorIdxConstant(Idx, dl));
10715       SDValue Store;
10716       if (ScalarVT != ScalarMemVT)
10717         Store =
10718             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10719                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10720                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10721                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10722       else
10723         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10724                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10725                              MinAlign(Alignment, Idx * Stride),
10726                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10727 
10728       if (Idx == 0 && SN->isIndexed()) {
10729         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10730                "Unknown addressing mode on vector store");
10731         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10732                                     SN->getAddressingMode());
10733       }
10734 
10735       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10736                             DAG.getConstant(Stride, dl,
10737                                             BasePtr.getValueType()));
10738       Stores[Idx] = Store;
10739     }
10740 
10741     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10742 
10743     if (SN->isIndexed()) {
10744       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10745       return DAG.getMergeValues(RetOps, dl);
10746     }
10747 
10748     return TF;
10749   }
10750 
10751   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10752   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10753 
10754   // The values are now known to be -1 (false) or 1 (true). To convert this
10755   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10756   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10757   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10758 
10759   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10760   // understand how to form the extending load.
10761   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10762 
10763   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10764 
10765   // Now convert to an integer and store.
10766   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10767     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10768     Value);
10769 
10770   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10771   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10772   MachinePointerInfo PtrInfo =
10773       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10774   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10775   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10776 
10777   SDValue Ops[] = {StoreChain,
10778                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10779                    Value, FIdx};
10780   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10781 
10782   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10783     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10784 
10785   // Move data into the byte array.
10786   SDValue Loads[4], LoadChains[4];
10787   for (unsigned i = 0; i < 4; ++i) {
10788     unsigned Offset = 4*i;
10789     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10790     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10791 
10792     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10793                            PtrInfo.getWithOffset(Offset));
10794     LoadChains[i] = Loads[i].getValue(1);
10795   }
10796 
10797   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10798 
10799   SDValue Stores[4];
10800   for (unsigned i = 0; i < 4; ++i) {
10801     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10802     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10803 
10804     Stores[i] = DAG.getTruncStore(
10805         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10806         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10807         SN->getAAInfo());
10808   }
10809 
10810   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10811 
10812   return StoreChain;
10813 }
10814 
10815 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10816   SDLoc dl(Op);
10817   if (Op.getValueType() == MVT::v4i32) {
10818     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10819 
10820     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10821     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10822 
10823     SDValue RHSSwap =   // = vrlw RHS, 16
10824       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10825 
10826     // Shrinkify inputs to v8i16.
10827     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10828     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10829     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10830 
10831     // Low parts multiplied together, generating 32-bit results (we ignore the
10832     // top parts).
10833     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10834                                         LHS, RHS, DAG, dl, MVT::v4i32);
10835 
10836     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10837                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10838     // Shift the high parts up 16 bits.
10839     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10840                               Neg16, DAG, dl);
10841     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10842   } else if (Op.getValueType() == MVT::v16i8) {
10843     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10844     bool isLittleEndian = Subtarget.isLittleEndian();
10845 
10846     // Multiply the even 8-bit parts, producing 16-bit sums.
10847     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10848                                            LHS, RHS, DAG, dl, MVT::v8i16);
10849     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10850 
10851     // Multiply the odd 8-bit parts, producing 16-bit sums.
10852     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10853                                           LHS, RHS, DAG, dl, MVT::v8i16);
10854     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10855 
10856     // Merge the results together.  Because vmuleub and vmuloub are
10857     // instructions with a big-endian bias, we must reverse the
10858     // element numbering and reverse the meaning of "odd" and "even"
10859     // when generating little endian code.
10860     int Ops[16];
10861     for (unsigned i = 0; i != 8; ++i) {
10862       if (isLittleEndian) {
10863         Ops[i*2  ] = 2*i;
10864         Ops[i*2+1] = 2*i+16;
10865       } else {
10866         Ops[i*2  ] = 2*i+1;
10867         Ops[i*2+1] = 2*i+1+16;
10868       }
10869     }
10870     if (isLittleEndian)
10871       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10872     else
10873       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10874   } else {
10875     llvm_unreachable("Unknown mul to lower!");
10876   }
10877 }
10878 
10879 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10880 
10881   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10882 
10883   EVT VT = Op.getValueType();
10884   assert(VT.isVector() &&
10885          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10886   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10887           VT == MVT::v16i8) &&
10888          "Unexpected vector element type!");
10889   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10890          "Current subtarget doesn't support smax v2i64!");
10891 
10892   // For vector abs, it can be lowered to:
10893   // abs x
10894   // ==>
10895   // y = -x
10896   // smax(x, y)
10897 
10898   SDLoc dl(Op);
10899   SDValue X = Op.getOperand(0);
10900   SDValue Zero = DAG.getConstant(0, dl, VT);
10901   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10902 
10903   // SMAX patch https://reviews.llvm.org/D47332
10904   // hasn't landed yet, so use intrinsic first here.
10905   // TODO: Should use SMAX directly once SMAX patch landed
10906   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10907   if (VT == MVT::v2i64)
10908     BifID = Intrinsic::ppc_altivec_vmaxsd;
10909   else if (VT == MVT::v8i16)
10910     BifID = Intrinsic::ppc_altivec_vmaxsh;
10911   else if (VT == MVT::v16i8)
10912     BifID = Intrinsic::ppc_altivec_vmaxsb;
10913 
10914   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10915 }
10916 
10917 // Custom lowering for fpext vf32 to v2f64
10918 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10919 
10920   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10921          "Should only be called for ISD::FP_EXTEND");
10922 
10923   // FIXME: handle extends from half precision float vectors on P9.
10924   // We only want to custom lower an extend from v2f32 to v2f64.
10925   if (Op.getValueType() != MVT::v2f64 ||
10926       Op.getOperand(0).getValueType() != MVT::v2f32)
10927     return SDValue();
10928 
10929   SDLoc dl(Op);
10930   SDValue Op0 = Op.getOperand(0);
10931 
10932   switch (Op0.getOpcode()) {
10933   default:
10934     return SDValue();
10935   case ISD::EXTRACT_SUBVECTOR: {
10936     assert(Op0.getNumOperands() == 2 &&
10937            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10938            "Node should have 2 operands with second one being a constant!");
10939 
10940     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10941       return SDValue();
10942 
10943     // Custom lower is only done for high or low doubleword.
10944     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10945     if (Idx % 2 != 0)
10946       return SDValue();
10947 
10948     // Since input is v4f32, at this point Idx is either 0 or 2.
10949     // Shift to get the doubleword position we want.
10950     int DWord = Idx >> 1;
10951 
10952     // High and low word positions are different on little endian.
10953     if (Subtarget.isLittleEndian())
10954       DWord ^= 0x1;
10955 
10956     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10957                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10958   }
10959   case ISD::FADD:
10960   case ISD::FMUL:
10961   case ISD::FSUB: {
10962     SDValue NewLoad[2];
10963     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10964       // Ensure both input are loads.
10965       SDValue LdOp = Op0.getOperand(i);
10966       if (LdOp.getOpcode() != ISD::LOAD)
10967         return SDValue();
10968       // Generate new load node.
10969       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10970       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10971       NewLoad[i] = DAG.getMemIntrinsicNode(
10972           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10973           LD->getMemoryVT(), LD->getMemOperand());
10974     }
10975     SDValue NewOp =
10976         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10977                     NewLoad[1], Op0.getNode()->getFlags());
10978     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10979                        DAG.getConstant(0, dl, MVT::i32));
10980   }
10981   case ISD::LOAD: {
10982     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10983     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10984     SDValue NewLd = DAG.getMemIntrinsicNode(
10985         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10986         LD->getMemoryVT(), LD->getMemOperand());
10987     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10988                        DAG.getConstant(0, dl, MVT::i32));
10989   }
10990   }
10991   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10992 }
10993 
10994 /// LowerOperation - Provide custom lowering hooks for some operations.
10995 ///
10996 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10997   switch (Op.getOpcode()) {
10998   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10999   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11000   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11001   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11002   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11003   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11004   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11005   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11006   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11007 
11008   // Variable argument lowering.
11009   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11010   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11011   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11012 
11013   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11014   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11015   case ISD::GET_DYNAMIC_AREA_OFFSET:
11016     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11017 
11018   // Exception handling lowering.
11019   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11020   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11021   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11022 
11023   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11024   case ISD::STORE:              return LowerSTORE(Op, DAG);
11025   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11026   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11027   case ISD::FP_TO_UINT:
11028   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11029   case ISD::UINT_TO_FP:
11030   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11031   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11032 
11033   // Lower 64-bit shifts.
11034   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11035   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11036   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11037 
11038   // Vector-related lowering.
11039   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11040   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11041   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11042   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11043   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11044   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11045   case ISD::MUL:                return LowerMUL(Op, DAG);
11046   case ISD::ABS:                return LowerABS(Op, DAG);
11047   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11048   case ISD::ROTL:               return LowerROTL(Op, DAG);
11049 
11050   // For counter-based loop handling.
11051   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11052 
11053   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11054 
11055   // Frame & Return address.
11056   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11057   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11058 
11059   case ISD::INTRINSIC_VOID:
11060     return LowerINTRINSIC_VOID(Op, DAG);
11061   case ISD::SREM:
11062   case ISD::UREM:
11063     return LowerREM(Op, DAG);
11064   case ISD::BSWAP:
11065     return LowerBSWAP(Op, DAG);
11066   case ISD::ATOMIC_CMP_SWAP:
11067     return LowerATOMIC_CMP_SWAP(Op, DAG);
11068   }
11069 }
11070 
11071 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11072                                            SmallVectorImpl<SDValue>&Results,
11073                                            SelectionDAG &DAG) const {
11074   SDLoc dl(N);
11075   switch (N->getOpcode()) {
11076   default:
11077     llvm_unreachable("Do not know how to custom type legalize this operation!");
11078   case ISD::READCYCLECOUNTER: {
11079     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11080     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11081 
11082     Results.push_back(
11083         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11084     Results.push_back(RTB.getValue(2));
11085     break;
11086   }
11087   case ISD::INTRINSIC_W_CHAIN: {
11088     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11089         Intrinsic::loop_decrement)
11090       break;
11091 
11092     assert(N->getValueType(0) == MVT::i1 &&
11093            "Unexpected result type for CTR decrement intrinsic");
11094     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11095                                  N->getValueType(0));
11096     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11097     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11098                                  N->getOperand(1));
11099 
11100     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11101     Results.push_back(NewInt.getValue(1));
11102     break;
11103   }
11104   case ISD::VAARG: {
11105     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11106       return;
11107 
11108     EVT VT = N->getValueType(0);
11109 
11110     if (VT == MVT::i64) {
11111       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11112 
11113       Results.push_back(NewNode);
11114       Results.push_back(NewNode.getValue(1));
11115     }
11116     return;
11117   }
11118   case ISD::FP_TO_SINT:
11119   case ISD::FP_TO_UINT:
11120     // LowerFP_TO_INT() can only handle f32 and f64.
11121     if (N->getOperand(0).getValueType() == MVT::ppcf128)
11122       return;
11123     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11124     return;
11125   case ISD::TRUNCATE: {
11126     EVT TrgVT = N->getValueType(0);
11127     EVT OpVT = N->getOperand(0).getValueType();
11128     if (TrgVT.isVector() &&
11129         isOperationCustom(N->getOpcode(), TrgVT) &&
11130         OpVT.getSizeInBits() <= 128 &&
11131         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
11132       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
11133     return;
11134   }
11135   case ISD::BITCAST:
11136     // Don't handle bitcast here.
11137     return;
11138   case ISD::FP_EXTEND:
11139     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11140     if (Lowered)
11141       Results.push_back(Lowered);
11142     return;
11143   }
11144 }
11145 
11146 //===----------------------------------------------------------------------===//
11147 //  Other Lowering Code
11148 //===----------------------------------------------------------------------===//
11149 
11150 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
11151   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11152   Function *Func = Intrinsic::getDeclaration(M, Id);
11153   return Builder.CreateCall(Func, {});
11154 }
11155 
11156 // The mappings for emitLeading/TrailingFence is taken from
11157 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11158 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11159                                                  Instruction *Inst,
11160                                                  AtomicOrdering Ord) const {
11161   if (Ord == AtomicOrdering::SequentiallyConsistent)
11162     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11163   if (isReleaseOrStronger(Ord))
11164     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11165   return nullptr;
11166 }
11167 
11168 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11169                                                   Instruction *Inst,
11170                                                   AtomicOrdering Ord) const {
11171   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11172     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11173     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11174     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11175     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11176       return Builder.CreateCall(
11177           Intrinsic::getDeclaration(
11178               Builder.GetInsertBlock()->getParent()->getParent(),
11179               Intrinsic::ppc_cfence, {Inst->getType()}),
11180           {Inst});
11181     // FIXME: Can use isync for rmw operation.
11182     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11183   }
11184   return nullptr;
11185 }
11186 
11187 MachineBasicBlock *
11188 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11189                                     unsigned AtomicSize,
11190                                     unsigned BinOpcode,
11191                                     unsigned CmpOpcode,
11192                                     unsigned CmpPred) const {
11193   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11194   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11195 
11196   auto LoadMnemonic = PPC::LDARX;
11197   auto StoreMnemonic = PPC::STDCX;
11198   switch (AtomicSize) {
11199   default:
11200     llvm_unreachable("Unexpected size of atomic entity");
11201   case 1:
11202     LoadMnemonic = PPC::LBARX;
11203     StoreMnemonic = PPC::STBCX;
11204     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11205     break;
11206   case 2:
11207     LoadMnemonic = PPC::LHARX;
11208     StoreMnemonic = PPC::STHCX;
11209     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11210     break;
11211   case 4:
11212     LoadMnemonic = PPC::LWARX;
11213     StoreMnemonic = PPC::STWCX;
11214     break;
11215   case 8:
11216     LoadMnemonic = PPC::LDARX;
11217     StoreMnemonic = PPC::STDCX;
11218     break;
11219   }
11220 
11221   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11222   MachineFunction *F = BB->getParent();
11223   MachineFunction::iterator It = ++BB->getIterator();
11224 
11225   Register dest = MI.getOperand(0).getReg();
11226   Register ptrA = MI.getOperand(1).getReg();
11227   Register ptrB = MI.getOperand(2).getReg();
11228   Register incr = MI.getOperand(3).getReg();
11229   DebugLoc dl = MI.getDebugLoc();
11230 
11231   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11232   MachineBasicBlock *loop2MBB =
11233     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11234   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11235   F->insert(It, loopMBB);
11236   if (CmpOpcode)
11237     F->insert(It, loop2MBB);
11238   F->insert(It, exitMBB);
11239   exitMBB->splice(exitMBB->begin(), BB,
11240                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11241   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11242 
11243   MachineRegisterInfo &RegInfo = F->getRegInfo();
11244   Register TmpReg = (!BinOpcode) ? incr :
11245     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11246                                            : &PPC::GPRCRegClass);
11247 
11248   //  thisMBB:
11249   //   ...
11250   //   fallthrough --> loopMBB
11251   BB->addSuccessor(loopMBB);
11252 
11253   //  loopMBB:
11254   //   l[wd]arx dest, ptr
11255   //   add r0, dest, incr
11256   //   st[wd]cx. r0, ptr
11257   //   bne- loopMBB
11258   //   fallthrough --> exitMBB
11259 
11260   // For max/min...
11261   //  loopMBB:
11262   //   l[wd]arx dest, ptr
11263   //   cmpl?[wd] incr, dest
11264   //   bgt exitMBB
11265   //  loop2MBB:
11266   //   st[wd]cx. dest, ptr
11267   //   bne- loopMBB
11268   //   fallthrough --> exitMBB
11269 
11270   BB = loopMBB;
11271   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11272     .addReg(ptrA).addReg(ptrB);
11273   if (BinOpcode)
11274     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11275   if (CmpOpcode) {
11276     // Signed comparisons of byte or halfword values must be sign-extended.
11277     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11278       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11279       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11280               ExtReg).addReg(dest);
11281       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11282         .addReg(incr).addReg(ExtReg);
11283     } else
11284       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11285         .addReg(incr).addReg(dest);
11286 
11287     BuildMI(BB, dl, TII->get(PPC::BCC))
11288       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11289     BB->addSuccessor(loop2MBB);
11290     BB->addSuccessor(exitMBB);
11291     BB = loop2MBB;
11292   }
11293   BuildMI(BB, dl, TII->get(StoreMnemonic))
11294     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11295   BuildMI(BB, dl, TII->get(PPC::BCC))
11296     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11297   BB->addSuccessor(loopMBB);
11298   BB->addSuccessor(exitMBB);
11299 
11300   //  exitMBB:
11301   //   ...
11302   BB = exitMBB;
11303   return BB;
11304 }
11305 
11306 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11307     MachineInstr &MI, MachineBasicBlock *BB,
11308     bool is8bit, // operation
11309     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11310   // If we support part-word atomic mnemonics, just use them
11311   if (Subtarget.hasPartwordAtomics())
11312     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11313                             CmpPred);
11314 
11315   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11316   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11317   // In 64 bit mode we have to use 64 bits for addresses, even though the
11318   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11319   // registers without caring whether they're 32 or 64, but here we're
11320   // doing actual arithmetic on the addresses.
11321   bool is64bit = Subtarget.isPPC64();
11322   bool isLittleEndian = Subtarget.isLittleEndian();
11323   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11324 
11325   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11326   MachineFunction *F = BB->getParent();
11327   MachineFunction::iterator It = ++BB->getIterator();
11328 
11329   Register dest = MI.getOperand(0).getReg();
11330   Register ptrA = MI.getOperand(1).getReg();
11331   Register ptrB = MI.getOperand(2).getReg();
11332   Register incr = MI.getOperand(3).getReg();
11333   DebugLoc dl = MI.getDebugLoc();
11334 
11335   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11336   MachineBasicBlock *loop2MBB =
11337       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11338   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11339   F->insert(It, loopMBB);
11340   if (CmpOpcode)
11341     F->insert(It, loop2MBB);
11342   F->insert(It, exitMBB);
11343   exitMBB->splice(exitMBB->begin(), BB,
11344                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11345   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11346 
11347   MachineRegisterInfo &RegInfo = F->getRegInfo();
11348   const TargetRegisterClass *RC =
11349       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11350   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11351 
11352   Register PtrReg = RegInfo.createVirtualRegister(RC);
11353   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11354   Register ShiftReg =
11355       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11356   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11357   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11358   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11359   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11360   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11361   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11362   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11363   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11364   Register Ptr1Reg;
11365   Register TmpReg =
11366       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11367 
11368   //  thisMBB:
11369   //   ...
11370   //   fallthrough --> loopMBB
11371   BB->addSuccessor(loopMBB);
11372 
11373   // The 4-byte load must be aligned, while a char or short may be
11374   // anywhere in the word.  Hence all this nasty bookkeeping code.
11375   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11376   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11377   //   xori shift, shift1, 24 [16]
11378   //   rlwinm ptr, ptr1, 0, 0, 29
11379   //   slw incr2, incr, shift
11380   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11381   //   slw mask, mask2, shift
11382   //  loopMBB:
11383   //   lwarx tmpDest, ptr
11384   //   add tmp, tmpDest, incr2
11385   //   andc tmp2, tmpDest, mask
11386   //   and tmp3, tmp, mask
11387   //   or tmp4, tmp3, tmp2
11388   //   stwcx. tmp4, ptr
11389   //   bne- loopMBB
11390   //   fallthrough --> exitMBB
11391   //   srw dest, tmpDest, shift
11392   if (ptrA != ZeroReg) {
11393     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11394     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11395         .addReg(ptrA)
11396         .addReg(ptrB);
11397   } else {
11398     Ptr1Reg = ptrB;
11399   }
11400   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11401   // mode.
11402   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11403       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11404       .addImm(3)
11405       .addImm(27)
11406       .addImm(is8bit ? 28 : 27);
11407   if (!isLittleEndian)
11408     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11409         .addReg(Shift1Reg)
11410         .addImm(is8bit ? 24 : 16);
11411   if (is64bit)
11412     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11413         .addReg(Ptr1Reg)
11414         .addImm(0)
11415         .addImm(61);
11416   else
11417     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11418         .addReg(Ptr1Reg)
11419         .addImm(0)
11420         .addImm(0)
11421         .addImm(29);
11422   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11423   if (is8bit)
11424     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11425   else {
11426     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11427     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11428         .addReg(Mask3Reg)
11429         .addImm(65535);
11430   }
11431   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11432       .addReg(Mask2Reg)
11433       .addReg(ShiftReg);
11434 
11435   BB = loopMBB;
11436   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11437       .addReg(ZeroReg)
11438       .addReg(PtrReg);
11439   if (BinOpcode)
11440     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11441         .addReg(Incr2Reg)
11442         .addReg(TmpDestReg);
11443   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11444       .addReg(TmpDestReg)
11445       .addReg(MaskReg);
11446   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11447   if (CmpOpcode) {
11448     // For unsigned comparisons, we can directly compare the shifted values.
11449     // For signed comparisons we shift and sign extend.
11450     Register SReg = RegInfo.createVirtualRegister(GPRC);
11451     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11452         .addReg(TmpDestReg)
11453         .addReg(MaskReg);
11454     unsigned ValueReg = SReg;
11455     unsigned CmpReg = Incr2Reg;
11456     if (CmpOpcode == PPC::CMPW) {
11457       ValueReg = RegInfo.createVirtualRegister(GPRC);
11458       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11459           .addReg(SReg)
11460           .addReg(ShiftReg);
11461       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11462       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11463           .addReg(ValueReg);
11464       ValueReg = ValueSReg;
11465       CmpReg = incr;
11466     }
11467     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11468         .addReg(CmpReg)
11469         .addReg(ValueReg);
11470     BuildMI(BB, dl, TII->get(PPC::BCC))
11471         .addImm(CmpPred)
11472         .addReg(PPC::CR0)
11473         .addMBB(exitMBB);
11474     BB->addSuccessor(loop2MBB);
11475     BB->addSuccessor(exitMBB);
11476     BB = loop2MBB;
11477   }
11478   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11479   BuildMI(BB, dl, TII->get(PPC::STWCX))
11480       .addReg(Tmp4Reg)
11481       .addReg(ZeroReg)
11482       .addReg(PtrReg);
11483   BuildMI(BB, dl, TII->get(PPC::BCC))
11484       .addImm(PPC::PRED_NE)
11485       .addReg(PPC::CR0)
11486       .addMBB(loopMBB);
11487   BB->addSuccessor(loopMBB);
11488   BB->addSuccessor(exitMBB);
11489 
11490   //  exitMBB:
11491   //   ...
11492   BB = exitMBB;
11493   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11494       .addReg(TmpDestReg)
11495       .addReg(ShiftReg);
11496   return BB;
11497 }
11498 
11499 llvm::MachineBasicBlock *
11500 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11501                                     MachineBasicBlock *MBB) const {
11502   DebugLoc DL = MI.getDebugLoc();
11503   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11504   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11505 
11506   MachineFunction *MF = MBB->getParent();
11507   MachineRegisterInfo &MRI = MF->getRegInfo();
11508 
11509   const BasicBlock *BB = MBB->getBasicBlock();
11510   MachineFunction::iterator I = ++MBB->getIterator();
11511 
11512   Register DstReg = MI.getOperand(0).getReg();
11513   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11514   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11515   Register mainDstReg = MRI.createVirtualRegister(RC);
11516   Register restoreDstReg = MRI.createVirtualRegister(RC);
11517 
11518   MVT PVT = getPointerTy(MF->getDataLayout());
11519   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11520          "Invalid Pointer Size!");
11521   // For v = setjmp(buf), we generate
11522   //
11523   // thisMBB:
11524   //  SjLjSetup mainMBB
11525   //  bl mainMBB
11526   //  v_restore = 1
11527   //  b sinkMBB
11528   //
11529   // mainMBB:
11530   //  buf[LabelOffset] = LR
11531   //  v_main = 0
11532   //
11533   // sinkMBB:
11534   //  v = phi(main, restore)
11535   //
11536 
11537   MachineBasicBlock *thisMBB = MBB;
11538   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11539   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11540   MF->insert(I, mainMBB);
11541   MF->insert(I, sinkMBB);
11542 
11543   MachineInstrBuilder MIB;
11544 
11545   // Transfer the remainder of BB and its successor edges to sinkMBB.
11546   sinkMBB->splice(sinkMBB->begin(), MBB,
11547                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11548   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11549 
11550   // Note that the structure of the jmp_buf used here is not compatible
11551   // with that used by libc, and is not designed to be. Specifically, it
11552   // stores only those 'reserved' registers that LLVM does not otherwise
11553   // understand how to spill. Also, by convention, by the time this
11554   // intrinsic is called, Clang has already stored the frame address in the
11555   // first slot of the buffer and stack address in the third. Following the
11556   // X86 target code, we'll store the jump address in the second slot. We also
11557   // need to save the TOC pointer (R2) to handle jumps between shared
11558   // libraries, and that will be stored in the fourth slot. The thread
11559   // identifier (R13) is not affected.
11560 
11561   // thisMBB:
11562   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11563   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11564   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11565 
11566   // Prepare IP either in reg.
11567   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11568   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11569   Register BufReg = MI.getOperand(1).getReg();
11570 
11571   if (Subtarget.is64BitELFABI()) {
11572     setUsesTOCBasePtr(*MBB->getParent());
11573     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11574               .addReg(PPC::X2)
11575               .addImm(TOCOffset)
11576               .addReg(BufReg)
11577               .cloneMemRefs(MI);
11578   }
11579 
11580   // Naked functions never have a base pointer, and so we use r1. For all
11581   // other functions, this decision must be delayed until during PEI.
11582   unsigned BaseReg;
11583   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11584     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11585   else
11586     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11587 
11588   MIB = BuildMI(*thisMBB, MI, DL,
11589                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11590             .addReg(BaseReg)
11591             .addImm(BPOffset)
11592             .addReg(BufReg)
11593             .cloneMemRefs(MI);
11594 
11595   // Setup
11596   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11597   MIB.addRegMask(TRI->getNoPreservedMask());
11598 
11599   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11600 
11601   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11602           .addMBB(mainMBB);
11603   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11604 
11605   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11606   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11607 
11608   // mainMBB:
11609   //  mainDstReg = 0
11610   MIB =
11611       BuildMI(mainMBB, DL,
11612               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11613 
11614   // Store IP
11615   if (Subtarget.isPPC64()) {
11616     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11617             .addReg(LabelReg)
11618             .addImm(LabelOffset)
11619             .addReg(BufReg);
11620   } else {
11621     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11622             .addReg(LabelReg)
11623             .addImm(LabelOffset)
11624             .addReg(BufReg);
11625   }
11626   MIB.cloneMemRefs(MI);
11627 
11628   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11629   mainMBB->addSuccessor(sinkMBB);
11630 
11631   // sinkMBB:
11632   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11633           TII->get(PPC::PHI), DstReg)
11634     .addReg(mainDstReg).addMBB(mainMBB)
11635     .addReg(restoreDstReg).addMBB(thisMBB);
11636 
11637   MI.eraseFromParent();
11638   return sinkMBB;
11639 }
11640 
11641 MachineBasicBlock *
11642 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11643                                      MachineBasicBlock *MBB) const {
11644   DebugLoc DL = MI.getDebugLoc();
11645   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11646 
11647   MachineFunction *MF = MBB->getParent();
11648   MachineRegisterInfo &MRI = MF->getRegInfo();
11649 
11650   MVT PVT = getPointerTy(MF->getDataLayout());
11651   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11652          "Invalid Pointer Size!");
11653 
11654   const TargetRegisterClass *RC =
11655     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11656   Register Tmp = MRI.createVirtualRegister(RC);
11657   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11658   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11659   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11660   unsigned BP =
11661       (PVT == MVT::i64)
11662           ? PPC::X30
11663           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11664                                                               : PPC::R30);
11665 
11666   MachineInstrBuilder MIB;
11667 
11668   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11669   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11670   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11671   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11672 
11673   Register BufReg = MI.getOperand(0).getReg();
11674 
11675   // Reload FP (the jumped-to function may not have had a
11676   // frame pointer, and if so, then its r31 will be restored
11677   // as necessary).
11678   if (PVT == MVT::i64) {
11679     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11680             .addImm(0)
11681             .addReg(BufReg);
11682   } else {
11683     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11684             .addImm(0)
11685             .addReg(BufReg);
11686   }
11687   MIB.cloneMemRefs(MI);
11688 
11689   // Reload IP
11690   if (PVT == MVT::i64) {
11691     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11692             .addImm(LabelOffset)
11693             .addReg(BufReg);
11694   } else {
11695     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11696             .addImm(LabelOffset)
11697             .addReg(BufReg);
11698   }
11699   MIB.cloneMemRefs(MI);
11700 
11701   // Reload SP
11702   if (PVT == MVT::i64) {
11703     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11704             .addImm(SPOffset)
11705             .addReg(BufReg);
11706   } else {
11707     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11708             .addImm(SPOffset)
11709             .addReg(BufReg);
11710   }
11711   MIB.cloneMemRefs(MI);
11712 
11713   // Reload BP
11714   if (PVT == MVT::i64) {
11715     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11716             .addImm(BPOffset)
11717             .addReg(BufReg);
11718   } else {
11719     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11720             .addImm(BPOffset)
11721             .addReg(BufReg);
11722   }
11723   MIB.cloneMemRefs(MI);
11724 
11725   // Reload TOC
11726   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11727     setUsesTOCBasePtr(*MBB->getParent());
11728     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11729               .addImm(TOCOffset)
11730               .addReg(BufReg)
11731               .cloneMemRefs(MI);
11732   }
11733 
11734   // Jump
11735   BuildMI(*MBB, MI, DL,
11736           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11737   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11738 
11739   MI.eraseFromParent();
11740   return MBB;
11741 }
11742 
11743 MachineBasicBlock *
11744 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11745                                                MachineBasicBlock *BB) const {
11746   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11747       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11748     if (Subtarget.is64BitELFABI() &&
11749         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11750         !Subtarget.isUsingPCRelativeCalls()) {
11751       // Call lowering should have added an r2 operand to indicate a dependence
11752       // on the TOC base pointer value. It can't however, because there is no
11753       // way to mark the dependence as implicit there, and so the stackmap code
11754       // will confuse it with a regular operand. Instead, add the dependence
11755       // here.
11756       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11757     }
11758 
11759     return emitPatchPoint(MI, BB);
11760   }
11761 
11762   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11763       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11764     return emitEHSjLjSetJmp(MI, BB);
11765   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11766              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11767     return emitEHSjLjLongJmp(MI, BB);
11768   }
11769 
11770   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11771 
11772   // To "insert" these instructions we actually have to insert their
11773   // control-flow patterns.
11774   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11775   MachineFunction::iterator It = ++BB->getIterator();
11776 
11777   MachineFunction *F = BB->getParent();
11778 
11779   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11780       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11781       MI.getOpcode() == PPC::SELECT_I8) {
11782     SmallVector<MachineOperand, 2> Cond;
11783     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11784         MI.getOpcode() == PPC::SELECT_CC_I8)
11785       Cond.push_back(MI.getOperand(4));
11786     else
11787       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11788     Cond.push_back(MI.getOperand(1));
11789 
11790     DebugLoc dl = MI.getDebugLoc();
11791     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11792                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11793   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11794              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11795              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11796              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11797              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11798              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11799              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11800              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11801              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11802              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11803              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11804              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11805              MI.getOpcode() == PPC::SELECT_F4 ||
11806              MI.getOpcode() == PPC::SELECT_F8 ||
11807              MI.getOpcode() == PPC::SELECT_F16 ||
11808              MI.getOpcode() == PPC::SELECT_QFRC ||
11809              MI.getOpcode() == PPC::SELECT_QSRC ||
11810              MI.getOpcode() == PPC::SELECT_QBRC ||
11811              MI.getOpcode() == PPC::SELECT_SPE ||
11812              MI.getOpcode() == PPC::SELECT_SPE4 ||
11813              MI.getOpcode() == PPC::SELECT_VRRC ||
11814              MI.getOpcode() == PPC::SELECT_VSFRC ||
11815              MI.getOpcode() == PPC::SELECT_VSSRC ||
11816              MI.getOpcode() == PPC::SELECT_VSRC) {
11817     // The incoming instruction knows the destination vreg to set, the
11818     // condition code register to branch on, the true/false values to
11819     // select between, and a branch opcode to use.
11820 
11821     //  thisMBB:
11822     //  ...
11823     //   TrueVal = ...
11824     //   cmpTY ccX, r1, r2
11825     //   bCC copy1MBB
11826     //   fallthrough --> copy0MBB
11827     MachineBasicBlock *thisMBB = BB;
11828     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11829     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11830     DebugLoc dl = MI.getDebugLoc();
11831     F->insert(It, copy0MBB);
11832     F->insert(It, sinkMBB);
11833 
11834     // Transfer the remainder of BB and its successor edges to sinkMBB.
11835     sinkMBB->splice(sinkMBB->begin(), BB,
11836                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11837     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11838 
11839     // Next, add the true and fallthrough blocks as its successors.
11840     BB->addSuccessor(copy0MBB);
11841     BB->addSuccessor(sinkMBB);
11842 
11843     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11844         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11845         MI.getOpcode() == PPC::SELECT_F16 ||
11846         MI.getOpcode() == PPC::SELECT_SPE4 ||
11847         MI.getOpcode() == PPC::SELECT_SPE ||
11848         MI.getOpcode() == PPC::SELECT_QFRC ||
11849         MI.getOpcode() == PPC::SELECT_QSRC ||
11850         MI.getOpcode() == PPC::SELECT_QBRC ||
11851         MI.getOpcode() == PPC::SELECT_VRRC ||
11852         MI.getOpcode() == PPC::SELECT_VSFRC ||
11853         MI.getOpcode() == PPC::SELECT_VSSRC ||
11854         MI.getOpcode() == PPC::SELECT_VSRC) {
11855       BuildMI(BB, dl, TII->get(PPC::BC))
11856           .addReg(MI.getOperand(1).getReg())
11857           .addMBB(sinkMBB);
11858     } else {
11859       unsigned SelectPred = MI.getOperand(4).getImm();
11860       BuildMI(BB, dl, TII->get(PPC::BCC))
11861           .addImm(SelectPred)
11862           .addReg(MI.getOperand(1).getReg())
11863           .addMBB(sinkMBB);
11864     }
11865 
11866     //  copy0MBB:
11867     //   %FalseValue = ...
11868     //   # fallthrough to sinkMBB
11869     BB = copy0MBB;
11870 
11871     // Update machine-CFG edges
11872     BB->addSuccessor(sinkMBB);
11873 
11874     //  sinkMBB:
11875     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11876     //  ...
11877     BB = sinkMBB;
11878     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11879         .addReg(MI.getOperand(3).getReg())
11880         .addMBB(copy0MBB)
11881         .addReg(MI.getOperand(2).getReg())
11882         .addMBB(thisMBB);
11883   } else if (MI.getOpcode() == PPC::ReadTB) {
11884     // To read the 64-bit time-base register on a 32-bit target, we read the
11885     // two halves. Should the counter have wrapped while it was being read, we
11886     // need to try again.
11887     // ...
11888     // readLoop:
11889     // mfspr Rx,TBU # load from TBU
11890     // mfspr Ry,TB  # load from TB
11891     // mfspr Rz,TBU # load from TBU
11892     // cmpw crX,Rx,Rz # check if 'old'='new'
11893     // bne readLoop   # branch if they're not equal
11894     // ...
11895 
11896     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11897     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11898     DebugLoc dl = MI.getDebugLoc();
11899     F->insert(It, readMBB);
11900     F->insert(It, sinkMBB);
11901 
11902     // Transfer the remainder of BB and its successor edges to sinkMBB.
11903     sinkMBB->splice(sinkMBB->begin(), BB,
11904                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11905     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11906 
11907     BB->addSuccessor(readMBB);
11908     BB = readMBB;
11909 
11910     MachineRegisterInfo &RegInfo = F->getRegInfo();
11911     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11912     Register LoReg = MI.getOperand(0).getReg();
11913     Register HiReg = MI.getOperand(1).getReg();
11914 
11915     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11916     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11917     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11918 
11919     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11920 
11921     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11922         .addReg(HiReg)
11923         .addReg(ReadAgainReg);
11924     BuildMI(BB, dl, TII->get(PPC::BCC))
11925         .addImm(PPC::PRED_NE)
11926         .addReg(CmpReg)
11927         .addMBB(readMBB);
11928 
11929     BB->addSuccessor(readMBB);
11930     BB->addSuccessor(sinkMBB);
11931   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11932     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11933   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11934     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11935   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11936     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11937   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11938     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11939 
11940   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11941     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11942   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11943     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11944   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11945     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11946   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11947     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11948 
11949   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11950     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11951   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11952     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11953   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11954     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11955   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11956     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11957 
11958   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11959     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11960   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11961     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11962   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11963     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11964   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11965     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11966 
11967   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11968     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11969   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11970     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11971   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11972     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11973   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11974     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11975 
11976   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11977     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11978   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11979     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11980   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11981     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11982   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11983     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11984 
11985   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11986     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11987   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11988     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11989   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11990     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11991   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11992     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11993 
11994   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11995     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11996   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11997     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11998   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11999     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12000   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12001     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12002 
12003   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12004     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12005   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12006     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12007   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12008     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12009   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12010     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12011 
12012   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12013     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12014   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12015     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12016   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12017     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12018   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12019     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12020 
12021   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12022     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12023   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12024     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12025   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12026     BB = EmitAtomicBinary(MI, BB, 4, 0);
12027   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12028     BB = EmitAtomicBinary(MI, BB, 8, 0);
12029   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12030            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12031            (Subtarget.hasPartwordAtomics() &&
12032             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12033            (Subtarget.hasPartwordAtomics() &&
12034             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12035     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12036 
12037     auto LoadMnemonic = PPC::LDARX;
12038     auto StoreMnemonic = PPC::STDCX;
12039     switch (MI.getOpcode()) {
12040     default:
12041       llvm_unreachable("Compare and swap of unknown size");
12042     case PPC::ATOMIC_CMP_SWAP_I8:
12043       LoadMnemonic = PPC::LBARX;
12044       StoreMnemonic = PPC::STBCX;
12045       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12046       break;
12047     case PPC::ATOMIC_CMP_SWAP_I16:
12048       LoadMnemonic = PPC::LHARX;
12049       StoreMnemonic = PPC::STHCX;
12050       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12051       break;
12052     case PPC::ATOMIC_CMP_SWAP_I32:
12053       LoadMnemonic = PPC::LWARX;
12054       StoreMnemonic = PPC::STWCX;
12055       break;
12056     case PPC::ATOMIC_CMP_SWAP_I64:
12057       LoadMnemonic = PPC::LDARX;
12058       StoreMnemonic = PPC::STDCX;
12059       break;
12060     }
12061     Register dest = MI.getOperand(0).getReg();
12062     Register ptrA = MI.getOperand(1).getReg();
12063     Register ptrB = MI.getOperand(2).getReg();
12064     Register oldval = MI.getOperand(3).getReg();
12065     Register newval = MI.getOperand(4).getReg();
12066     DebugLoc dl = MI.getDebugLoc();
12067 
12068     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12069     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12070     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12071     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12072     F->insert(It, loop1MBB);
12073     F->insert(It, loop2MBB);
12074     F->insert(It, midMBB);
12075     F->insert(It, exitMBB);
12076     exitMBB->splice(exitMBB->begin(), BB,
12077                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12078     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12079 
12080     //  thisMBB:
12081     //   ...
12082     //   fallthrough --> loopMBB
12083     BB->addSuccessor(loop1MBB);
12084 
12085     // loop1MBB:
12086     //   l[bhwd]arx dest, ptr
12087     //   cmp[wd] dest, oldval
12088     //   bne- midMBB
12089     // loop2MBB:
12090     //   st[bhwd]cx. newval, ptr
12091     //   bne- loopMBB
12092     //   b exitBB
12093     // midMBB:
12094     //   st[bhwd]cx. dest, ptr
12095     // exitBB:
12096     BB = loop1MBB;
12097     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12098     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12099         .addReg(oldval)
12100         .addReg(dest);
12101     BuildMI(BB, dl, TII->get(PPC::BCC))
12102         .addImm(PPC::PRED_NE)
12103         .addReg(PPC::CR0)
12104         .addMBB(midMBB);
12105     BB->addSuccessor(loop2MBB);
12106     BB->addSuccessor(midMBB);
12107 
12108     BB = loop2MBB;
12109     BuildMI(BB, dl, TII->get(StoreMnemonic))
12110         .addReg(newval)
12111         .addReg(ptrA)
12112         .addReg(ptrB);
12113     BuildMI(BB, dl, TII->get(PPC::BCC))
12114         .addImm(PPC::PRED_NE)
12115         .addReg(PPC::CR0)
12116         .addMBB(loop1MBB);
12117     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12118     BB->addSuccessor(loop1MBB);
12119     BB->addSuccessor(exitMBB);
12120 
12121     BB = midMBB;
12122     BuildMI(BB, dl, TII->get(StoreMnemonic))
12123         .addReg(dest)
12124         .addReg(ptrA)
12125         .addReg(ptrB);
12126     BB->addSuccessor(exitMBB);
12127 
12128     //  exitMBB:
12129     //   ...
12130     BB = exitMBB;
12131   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12132              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12133     // We must use 64-bit registers for addresses when targeting 64-bit,
12134     // since we're actually doing arithmetic on them.  Other registers
12135     // can be 32-bit.
12136     bool is64bit = Subtarget.isPPC64();
12137     bool isLittleEndian = Subtarget.isLittleEndian();
12138     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12139 
12140     Register dest = MI.getOperand(0).getReg();
12141     Register ptrA = MI.getOperand(1).getReg();
12142     Register ptrB = MI.getOperand(2).getReg();
12143     Register oldval = MI.getOperand(3).getReg();
12144     Register newval = MI.getOperand(4).getReg();
12145     DebugLoc dl = MI.getDebugLoc();
12146 
12147     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12148     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12149     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12150     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12151     F->insert(It, loop1MBB);
12152     F->insert(It, loop2MBB);
12153     F->insert(It, midMBB);
12154     F->insert(It, exitMBB);
12155     exitMBB->splice(exitMBB->begin(), BB,
12156                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12157     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12158 
12159     MachineRegisterInfo &RegInfo = F->getRegInfo();
12160     const TargetRegisterClass *RC =
12161         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12162     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12163 
12164     Register PtrReg = RegInfo.createVirtualRegister(RC);
12165     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12166     Register ShiftReg =
12167         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12168     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12169     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12170     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12171     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12172     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12173     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12174     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12175     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12176     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12177     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12178     Register Ptr1Reg;
12179     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12180     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12181     //  thisMBB:
12182     //   ...
12183     //   fallthrough --> loopMBB
12184     BB->addSuccessor(loop1MBB);
12185 
12186     // The 4-byte load must be aligned, while a char or short may be
12187     // anywhere in the word.  Hence all this nasty bookkeeping code.
12188     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12189     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12190     //   xori shift, shift1, 24 [16]
12191     //   rlwinm ptr, ptr1, 0, 0, 29
12192     //   slw newval2, newval, shift
12193     //   slw oldval2, oldval,shift
12194     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12195     //   slw mask, mask2, shift
12196     //   and newval3, newval2, mask
12197     //   and oldval3, oldval2, mask
12198     // loop1MBB:
12199     //   lwarx tmpDest, ptr
12200     //   and tmp, tmpDest, mask
12201     //   cmpw tmp, oldval3
12202     //   bne- midMBB
12203     // loop2MBB:
12204     //   andc tmp2, tmpDest, mask
12205     //   or tmp4, tmp2, newval3
12206     //   stwcx. tmp4, ptr
12207     //   bne- loop1MBB
12208     //   b exitBB
12209     // midMBB:
12210     //   stwcx. tmpDest, ptr
12211     // exitBB:
12212     //   srw dest, tmpDest, shift
12213     if (ptrA != ZeroReg) {
12214       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12215       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12216           .addReg(ptrA)
12217           .addReg(ptrB);
12218     } else {
12219       Ptr1Reg = ptrB;
12220     }
12221 
12222     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12223     // mode.
12224     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12225         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12226         .addImm(3)
12227         .addImm(27)
12228         .addImm(is8bit ? 28 : 27);
12229     if (!isLittleEndian)
12230       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12231           .addReg(Shift1Reg)
12232           .addImm(is8bit ? 24 : 16);
12233     if (is64bit)
12234       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12235           .addReg(Ptr1Reg)
12236           .addImm(0)
12237           .addImm(61);
12238     else
12239       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12240           .addReg(Ptr1Reg)
12241           .addImm(0)
12242           .addImm(0)
12243           .addImm(29);
12244     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12245         .addReg(newval)
12246         .addReg(ShiftReg);
12247     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12248         .addReg(oldval)
12249         .addReg(ShiftReg);
12250     if (is8bit)
12251       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12252     else {
12253       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12254       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12255           .addReg(Mask3Reg)
12256           .addImm(65535);
12257     }
12258     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12259         .addReg(Mask2Reg)
12260         .addReg(ShiftReg);
12261     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12262         .addReg(NewVal2Reg)
12263         .addReg(MaskReg);
12264     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12265         .addReg(OldVal2Reg)
12266         .addReg(MaskReg);
12267 
12268     BB = loop1MBB;
12269     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12270         .addReg(ZeroReg)
12271         .addReg(PtrReg);
12272     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12273         .addReg(TmpDestReg)
12274         .addReg(MaskReg);
12275     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12276         .addReg(TmpReg)
12277         .addReg(OldVal3Reg);
12278     BuildMI(BB, dl, TII->get(PPC::BCC))
12279         .addImm(PPC::PRED_NE)
12280         .addReg(PPC::CR0)
12281         .addMBB(midMBB);
12282     BB->addSuccessor(loop2MBB);
12283     BB->addSuccessor(midMBB);
12284 
12285     BB = loop2MBB;
12286     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12287         .addReg(TmpDestReg)
12288         .addReg(MaskReg);
12289     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12290         .addReg(Tmp2Reg)
12291         .addReg(NewVal3Reg);
12292     BuildMI(BB, dl, TII->get(PPC::STWCX))
12293         .addReg(Tmp4Reg)
12294         .addReg(ZeroReg)
12295         .addReg(PtrReg);
12296     BuildMI(BB, dl, TII->get(PPC::BCC))
12297         .addImm(PPC::PRED_NE)
12298         .addReg(PPC::CR0)
12299         .addMBB(loop1MBB);
12300     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12301     BB->addSuccessor(loop1MBB);
12302     BB->addSuccessor(exitMBB);
12303 
12304     BB = midMBB;
12305     BuildMI(BB, dl, TII->get(PPC::STWCX))
12306         .addReg(TmpDestReg)
12307         .addReg(ZeroReg)
12308         .addReg(PtrReg);
12309     BB->addSuccessor(exitMBB);
12310 
12311     //  exitMBB:
12312     //   ...
12313     BB = exitMBB;
12314     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12315         .addReg(TmpReg)
12316         .addReg(ShiftReg);
12317   } else if (MI.getOpcode() == PPC::FADDrtz) {
12318     // This pseudo performs an FADD with rounding mode temporarily forced
12319     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12320     // is not modeled at the SelectionDAG level.
12321     Register Dest = MI.getOperand(0).getReg();
12322     Register Src1 = MI.getOperand(1).getReg();
12323     Register Src2 = MI.getOperand(2).getReg();
12324     DebugLoc dl = MI.getDebugLoc();
12325 
12326     MachineRegisterInfo &RegInfo = F->getRegInfo();
12327     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12328 
12329     // Save FPSCR value.
12330     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12331 
12332     // Set rounding mode to round-to-zero.
12333     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
12334     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
12335 
12336     // Perform addition.
12337     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12338 
12339     // Restore FPSCR value.
12340     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12341   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12342              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12343              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12344              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12345     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12346                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12347                           ? PPC::ANDI8_rec
12348                           : PPC::ANDI_rec;
12349     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12350                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12351 
12352     MachineRegisterInfo &RegInfo = F->getRegInfo();
12353     Register Dest = RegInfo.createVirtualRegister(
12354         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12355 
12356     DebugLoc Dl = MI.getDebugLoc();
12357     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12358         .addReg(MI.getOperand(1).getReg())
12359         .addImm(1);
12360     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12361             MI.getOperand(0).getReg())
12362         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12363   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12364     DebugLoc Dl = MI.getDebugLoc();
12365     MachineRegisterInfo &RegInfo = F->getRegInfo();
12366     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12367     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12368     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12369             MI.getOperand(0).getReg())
12370         .addReg(CRReg);
12371   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12372     DebugLoc Dl = MI.getDebugLoc();
12373     unsigned Imm = MI.getOperand(1).getImm();
12374     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12375     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12376             MI.getOperand(0).getReg())
12377         .addReg(PPC::CR0EQ);
12378   } else if (MI.getOpcode() == PPC::SETRNDi) {
12379     DebugLoc dl = MI.getDebugLoc();
12380     Register OldFPSCRReg = MI.getOperand(0).getReg();
12381 
12382     // Save FPSCR value.
12383     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12384 
12385     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12386     // the following settings:
12387     //   00 Round to nearest
12388     //   01 Round to 0
12389     //   10 Round to +inf
12390     //   11 Round to -inf
12391 
12392     // When the operand is immediate, using the two least significant bits of
12393     // the immediate to set the bits 62:63 of FPSCR.
12394     unsigned Mode = MI.getOperand(1).getImm();
12395     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12396       .addImm(31);
12397 
12398     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12399       .addImm(30);
12400   } else if (MI.getOpcode() == PPC::SETRND) {
12401     DebugLoc dl = MI.getDebugLoc();
12402 
12403     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12404     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12405     // If the target doesn't have DirectMove, we should use stack to do the
12406     // conversion, because the target doesn't have the instructions like mtvsrd
12407     // or mfvsrd to do this conversion directly.
12408     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12409       if (Subtarget.hasDirectMove()) {
12410         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12411           .addReg(SrcReg);
12412       } else {
12413         // Use stack to do the register copy.
12414         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12415         MachineRegisterInfo &RegInfo = F->getRegInfo();
12416         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12417         if (RC == &PPC::F8RCRegClass) {
12418           // Copy register from F8RCRegClass to G8RCRegclass.
12419           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12420                  "Unsupported RegClass.");
12421 
12422           StoreOp = PPC::STFD;
12423           LoadOp = PPC::LD;
12424         } else {
12425           // Copy register from G8RCRegClass to F8RCRegclass.
12426           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12427                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12428                  "Unsupported RegClass.");
12429         }
12430 
12431         MachineFrameInfo &MFI = F->getFrameInfo();
12432         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12433 
12434         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12435             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12436             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12437             MFI.getObjectAlign(FrameIdx));
12438 
12439         // Store the SrcReg into the stack.
12440         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12441           .addReg(SrcReg)
12442           .addImm(0)
12443           .addFrameIndex(FrameIdx)
12444           .addMemOperand(MMOStore);
12445 
12446         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12447             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12448             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12449             MFI.getObjectAlign(FrameIdx));
12450 
12451         // Load from the stack where SrcReg is stored, and save to DestReg,
12452         // so we have done the RegClass conversion from RegClass::SrcReg to
12453         // RegClass::DestReg.
12454         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12455           .addImm(0)
12456           .addFrameIndex(FrameIdx)
12457           .addMemOperand(MMOLoad);
12458       }
12459     };
12460 
12461     Register OldFPSCRReg = MI.getOperand(0).getReg();
12462 
12463     // Save FPSCR value.
12464     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12465 
12466     // When the operand is gprc register, use two least significant bits of the
12467     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12468     //
12469     // copy OldFPSCRTmpReg, OldFPSCRReg
12470     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12471     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12472     // copy NewFPSCRReg, NewFPSCRTmpReg
12473     // mtfsf 255, NewFPSCRReg
12474     MachineOperand SrcOp = MI.getOperand(1);
12475     MachineRegisterInfo &RegInfo = F->getRegInfo();
12476     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12477 
12478     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12479 
12480     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12481     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12482 
12483     // The first operand of INSERT_SUBREG should be a register which has
12484     // subregisters, we only care about its RegClass, so we should use an
12485     // IMPLICIT_DEF register.
12486     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12487     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12488       .addReg(ImDefReg)
12489       .add(SrcOp)
12490       .addImm(1);
12491 
12492     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12493     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12494       .addReg(OldFPSCRTmpReg)
12495       .addReg(ExtSrcReg)
12496       .addImm(0)
12497       .addImm(62);
12498 
12499     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12500     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12501 
12502     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12503     // bits of FPSCR.
12504     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12505       .addImm(255)
12506       .addReg(NewFPSCRReg)
12507       .addImm(0)
12508       .addImm(0);
12509   } else {
12510     llvm_unreachable("Unexpected instr type to insert");
12511   }
12512 
12513   MI.eraseFromParent(); // The pseudo instruction is gone now.
12514   return BB;
12515 }
12516 
12517 //===----------------------------------------------------------------------===//
12518 // Target Optimization Hooks
12519 //===----------------------------------------------------------------------===//
12520 
12521 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12522   // For the estimates, convergence is quadratic, so we essentially double the
12523   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12524   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12525   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12526   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12527   if (VT.getScalarType() == MVT::f64)
12528     RefinementSteps++;
12529   return RefinementSteps;
12530 }
12531 
12532 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12533                                            int Enabled, int &RefinementSteps,
12534                                            bool &UseOneConstNR,
12535                                            bool Reciprocal) const {
12536   EVT VT = Operand.getValueType();
12537   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12538       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12539       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12540       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12541       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12542       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12543     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12544       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12545 
12546     // The Newton-Raphson computation with a single constant does not provide
12547     // enough accuracy on some CPUs.
12548     UseOneConstNR = !Subtarget.needsTwoConstNR();
12549     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12550   }
12551   return SDValue();
12552 }
12553 
12554 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12555                                             int Enabled,
12556                                             int &RefinementSteps) const {
12557   EVT VT = Operand.getValueType();
12558   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12559       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12560       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12561       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12562       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12563       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12564     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12565       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12566     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12567   }
12568   return SDValue();
12569 }
12570 
12571 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12572   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12573   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12574   // enabled for division), this functionality is redundant with the default
12575   // combiner logic (once the division -> reciprocal/multiply transformation
12576   // has taken place). As a result, this matters more for older cores than for
12577   // newer ones.
12578 
12579   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12580   // reciprocal if there are two or more FDIVs (for embedded cores with only
12581   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12582   switch (Subtarget.getCPUDirective()) {
12583   default:
12584     return 3;
12585   case PPC::DIR_440:
12586   case PPC::DIR_A2:
12587   case PPC::DIR_E500:
12588   case PPC::DIR_E500mc:
12589   case PPC::DIR_E5500:
12590     return 2;
12591   }
12592 }
12593 
12594 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12595 // collapsed, and so we need to look through chains of them.
12596 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12597                                      int64_t& Offset, SelectionDAG &DAG) {
12598   if (DAG.isBaseWithConstantOffset(Loc)) {
12599     Base = Loc.getOperand(0);
12600     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12601 
12602     // The base might itself be a base plus an offset, and if so, accumulate
12603     // that as well.
12604     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12605   }
12606 }
12607 
12608 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12609                             unsigned Bytes, int Dist,
12610                             SelectionDAG &DAG) {
12611   if (VT.getSizeInBits() / 8 != Bytes)
12612     return false;
12613 
12614   SDValue BaseLoc = Base->getBasePtr();
12615   if (Loc.getOpcode() == ISD::FrameIndex) {
12616     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12617       return false;
12618     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12619     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12620     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12621     int FS  = MFI.getObjectSize(FI);
12622     int BFS = MFI.getObjectSize(BFI);
12623     if (FS != BFS || FS != (int)Bytes) return false;
12624     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12625   }
12626 
12627   SDValue Base1 = Loc, Base2 = BaseLoc;
12628   int64_t Offset1 = 0, Offset2 = 0;
12629   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12630   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12631   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12632     return true;
12633 
12634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12635   const GlobalValue *GV1 = nullptr;
12636   const GlobalValue *GV2 = nullptr;
12637   Offset1 = 0;
12638   Offset2 = 0;
12639   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12640   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12641   if (isGA1 && isGA2 && GV1 == GV2)
12642     return Offset1 == (Offset2 + Dist*Bytes);
12643   return false;
12644 }
12645 
12646 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12647 // not enforce equality of the chain operands.
12648 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12649                             unsigned Bytes, int Dist,
12650                             SelectionDAG &DAG) {
12651   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12652     EVT VT = LS->getMemoryVT();
12653     SDValue Loc = LS->getBasePtr();
12654     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12655   }
12656 
12657   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12658     EVT VT;
12659     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12660     default: return false;
12661     case Intrinsic::ppc_qpx_qvlfd:
12662     case Intrinsic::ppc_qpx_qvlfda:
12663       VT = MVT::v4f64;
12664       break;
12665     case Intrinsic::ppc_qpx_qvlfs:
12666     case Intrinsic::ppc_qpx_qvlfsa:
12667       VT = MVT::v4f32;
12668       break;
12669     case Intrinsic::ppc_qpx_qvlfcd:
12670     case Intrinsic::ppc_qpx_qvlfcda:
12671       VT = MVT::v2f64;
12672       break;
12673     case Intrinsic::ppc_qpx_qvlfcs:
12674     case Intrinsic::ppc_qpx_qvlfcsa:
12675       VT = MVT::v2f32;
12676       break;
12677     case Intrinsic::ppc_qpx_qvlfiwa:
12678     case Intrinsic::ppc_qpx_qvlfiwz:
12679     case Intrinsic::ppc_altivec_lvx:
12680     case Intrinsic::ppc_altivec_lvxl:
12681     case Intrinsic::ppc_vsx_lxvw4x:
12682     case Intrinsic::ppc_vsx_lxvw4x_be:
12683       VT = MVT::v4i32;
12684       break;
12685     case Intrinsic::ppc_vsx_lxvd2x:
12686     case Intrinsic::ppc_vsx_lxvd2x_be:
12687       VT = MVT::v2f64;
12688       break;
12689     case Intrinsic::ppc_altivec_lvebx:
12690       VT = MVT::i8;
12691       break;
12692     case Intrinsic::ppc_altivec_lvehx:
12693       VT = MVT::i16;
12694       break;
12695     case Intrinsic::ppc_altivec_lvewx:
12696       VT = MVT::i32;
12697       break;
12698     }
12699 
12700     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12701   }
12702 
12703   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12704     EVT VT;
12705     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12706     default: return false;
12707     case Intrinsic::ppc_qpx_qvstfd:
12708     case Intrinsic::ppc_qpx_qvstfda:
12709       VT = MVT::v4f64;
12710       break;
12711     case Intrinsic::ppc_qpx_qvstfs:
12712     case Intrinsic::ppc_qpx_qvstfsa:
12713       VT = MVT::v4f32;
12714       break;
12715     case Intrinsic::ppc_qpx_qvstfcd:
12716     case Intrinsic::ppc_qpx_qvstfcda:
12717       VT = MVT::v2f64;
12718       break;
12719     case Intrinsic::ppc_qpx_qvstfcs:
12720     case Intrinsic::ppc_qpx_qvstfcsa:
12721       VT = MVT::v2f32;
12722       break;
12723     case Intrinsic::ppc_qpx_qvstfiw:
12724     case Intrinsic::ppc_qpx_qvstfiwa:
12725     case Intrinsic::ppc_altivec_stvx:
12726     case Intrinsic::ppc_altivec_stvxl:
12727     case Intrinsic::ppc_vsx_stxvw4x:
12728       VT = MVT::v4i32;
12729       break;
12730     case Intrinsic::ppc_vsx_stxvd2x:
12731       VT = MVT::v2f64;
12732       break;
12733     case Intrinsic::ppc_vsx_stxvw4x_be:
12734       VT = MVT::v4i32;
12735       break;
12736     case Intrinsic::ppc_vsx_stxvd2x_be:
12737       VT = MVT::v2f64;
12738       break;
12739     case Intrinsic::ppc_altivec_stvebx:
12740       VT = MVT::i8;
12741       break;
12742     case Intrinsic::ppc_altivec_stvehx:
12743       VT = MVT::i16;
12744       break;
12745     case Intrinsic::ppc_altivec_stvewx:
12746       VT = MVT::i32;
12747       break;
12748     }
12749 
12750     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12751   }
12752 
12753   return false;
12754 }
12755 
12756 // Return true is there is a nearyby consecutive load to the one provided
12757 // (regardless of alignment). We search up and down the chain, looking though
12758 // token factors and other loads (but nothing else). As a result, a true result
12759 // indicates that it is safe to create a new consecutive load adjacent to the
12760 // load provided.
12761 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12762   SDValue Chain = LD->getChain();
12763   EVT VT = LD->getMemoryVT();
12764 
12765   SmallSet<SDNode *, 16> LoadRoots;
12766   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12767   SmallSet<SDNode *, 16> Visited;
12768 
12769   // First, search up the chain, branching to follow all token-factor operands.
12770   // If we find a consecutive load, then we're done, otherwise, record all
12771   // nodes just above the top-level loads and token factors.
12772   while (!Queue.empty()) {
12773     SDNode *ChainNext = Queue.pop_back_val();
12774     if (!Visited.insert(ChainNext).second)
12775       continue;
12776 
12777     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12778       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12779         return true;
12780 
12781       if (!Visited.count(ChainLD->getChain().getNode()))
12782         Queue.push_back(ChainLD->getChain().getNode());
12783     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12784       for (const SDUse &O : ChainNext->ops())
12785         if (!Visited.count(O.getNode()))
12786           Queue.push_back(O.getNode());
12787     } else
12788       LoadRoots.insert(ChainNext);
12789   }
12790 
12791   // Second, search down the chain, starting from the top-level nodes recorded
12792   // in the first phase. These top-level nodes are the nodes just above all
12793   // loads and token factors. Starting with their uses, recursively look though
12794   // all loads (just the chain uses) and token factors to find a consecutive
12795   // load.
12796   Visited.clear();
12797   Queue.clear();
12798 
12799   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12800        IE = LoadRoots.end(); I != IE; ++I) {
12801     Queue.push_back(*I);
12802 
12803     while (!Queue.empty()) {
12804       SDNode *LoadRoot = Queue.pop_back_val();
12805       if (!Visited.insert(LoadRoot).second)
12806         continue;
12807 
12808       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12809         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12810           return true;
12811 
12812       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12813            UE = LoadRoot->use_end(); UI != UE; ++UI)
12814         if (((isa<MemSDNode>(*UI) &&
12815             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12816             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12817           Queue.push_back(*UI);
12818     }
12819   }
12820 
12821   return false;
12822 }
12823 
12824 /// This function is called when we have proved that a SETCC node can be replaced
12825 /// by subtraction (and other supporting instructions) so that the result of
12826 /// comparison is kept in a GPR instead of CR. This function is purely for
12827 /// codegen purposes and has some flags to guide the codegen process.
12828 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12829                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12830   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12831 
12832   // Zero extend the operands to the largest legal integer. Originally, they
12833   // must be of a strictly smaller size.
12834   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12835                          DAG.getConstant(Size, DL, MVT::i32));
12836   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12837                          DAG.getConstant(Size, DL, MVT::i32));
12838 
12839   // Swap if needed. Depends on the condition code.
12840   if (Swap)
12841     std::swap(Op0, Op1);
12842 
12843   // Subtract extended integers.
12844   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12845 
12846   // Move the sign bit to the least significant position and zero out the rest.
12847   // Now the least significant bit carries the result of original comparison.
12848   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12849                              DAG.getConstant(Size - 1, DL, MVT::i32));
12850   auto Final = Shifted;
12851 
12852   // Complement the result if needed. Based on the condition code.
12853   if (Complement)
12854     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12855                         DAG.getConstant(1, DL, MVT::i64));
12856 
12857   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12858 }
12859 
12860 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12861                                                   DAGCombinerInfo &DCI) const {
12862   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12863 
12864   SelectionDAG &DAG = DCI.DAG;
12865   SDLoc DL(N);
12866 
12867   // Size of integers being compared has a critical role in the following
12868   // analysis, so we prefer to do this when all types are legal.
12869   if (!DCI.isAfterLegalizeDAG())
12870     return SDValue();
12871 
12872   // If all users of SETCC extend its value to a legal integer type
12873   // then we replace SETCC with a subtraction
12874   for (SDNode::use_iterator UI = N->use_begin(),
12875        UE = N->use_end(); UI != UE; ++UI) {
12876     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12877       return SDValue();
12878   }
12879 
12880   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12881   auto OpSize = N->getOperand(0).getValueSizeInBits();
12882 
12883   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12884 
12885   if (OpSize < Size) {
12886     switch (CC) {
12887     default: break;
12888     case ISD::SETULT:
12889       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12890     case ISD::SETULE:
12891       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12892     case ISD::SETUGT:
12893       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12894     case ISD::SETUGE:
12895       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12896     }
12897   }
12898 
12899   return SDValue();
12900 }
12901 
12902 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12903                                                   DAGCombinerInfo &DCI) const {
12904   SelectionDAG &DAG = DCI.DAG;
12905   SDLoc dl(N);
12906 
12907   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12908   // If we're tracking CR bits, we need to be careful that we don't have:
12909   //   trunc(binary-ops(zext(x), zext(y)))
12910   // or
12911   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12912   // such that we're unnecessarily moving things into GPRs when it would be
12913   // better to keep them in CR bits.
12914 
12915   // Note that trunc here can be an actual i1 trunc, or can be the effective
12916   // truncation that comes from a setcc or select_cc.
12917   if (N->getOpcode() == ISD::TRUNCATE &&
12918       N->getValueType(0) != MVT::i1)
12919     return SDValue();
12920 
12921   if (N->getOperand(0).getValueType() != MVT::i32 &&
12922       N->getOperand(0).getValueType() != MVT::i64)
12923     return SDValue();
12924 
12925   if (N->getOpcode() == ISD::SETCC ||
12926       N->getOpcode() == ISD::SELECT_CC) {
12927     // If we're looking at a comparison, then we need to make sure that the
12928     // high bits (all except for the first) don't matter the result.
12929     ISD::CondCode CC =
12930       cast<CondCodeSDNode>(N->getOperand(
12931         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12932     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12933 
12934     if (ISD::isSignedIntSetCC(CC)) {
12935       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12936           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12937         return SDValue();
12938     } else if (ISD::isUnsignedIntSetCC(CC)) {
12939       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12940                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12941           !DAG.MaskedValueIsZero(N->getOperand(1),
12942                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12943         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12944                                              : SDValue());
12945     } else {
12946       // This is neither a signed nor an unsigned comparison, just make sure
12947       // that the high bits are equal.
12948       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12949       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12950 
12951       // We don't really care about what is known about the first bit (if
12952       // anything), so clear it in all masks prior to comparing them.
12953       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12954       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12955 
12956       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12957         return SDValue();
12958     }
12959   }
12960 
12961   // We now know that the higher-order bits are irrelevant, we just need to
12962   // make sure that all of the intermediate operations are bit operations, and
12963   // all inputs are extensions.
12964   if (N->getOperand(0).getOpcode() != ISD::AND &&
12965       N->getOperand(0).getOpcode() != ISD::OR  &&
12966       N->getOperand(0).getOpcode() != ISD::XOR &&
12967       N->getOperand(0).getOpcode() != ISD::SELECT &&
12968       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12969       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12970       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12971       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12972       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12973     return SDValue();
12974 
12975   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12976       N->getOperand(1).getOpcode() != ISD::AND &&
12977       N->getOperand(1).getOpcode() != ISD::OR  &&
12978       N->getOperand(1).getOpcode() != ISD::XOR &&
12979       N->getOperand(1).getOpcode() != ISD::SELECT &&
12980       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12981       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12982       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12983       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12984       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12985     return SDValue();
12986 
12987   SmallVector<SDValue, 4> Inputs;
12988   SmallVector<SDValue, 8> BinOps, PromOps;
12989   SmallPtrSet<SDNode *, 16> Visited;
12990 
12991   for (unsigned i = 0; i < 2; ++i) {
12992     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12993           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12994           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12995           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12996         isa<ConstantSDNode>(N->getOperand(i)))
12997       Inputs.push_back(N->getOperand(i));
12998     else
12999       BinOps.push_back(N->getOperand(i));
13000 
13001     if (N->getOpcode() == ISD::TRUNCATE)
13002       break;
13003   }
13004 
13005   // Visit all inputs, collect all binary operations (and, or, xor and
13006   // select) that are all fed by extensions.
13007   while (!BinOps.empty()) {
13008     SDValue BinOp = BinOps.back();
13009     BinOps.pop_back();
13010 
13011     if (!Visited.insert(BinOp.getNode()).second)
13012       continue;
13013 
13014     PromOps.push_back(BinOp);
13015 
13016     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13017       // The condition of the select is not promoted.
13018       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13019         continue;
13020       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13021         continue;
13022 
13023       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13024             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13025             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13026            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13027           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13028         Inputs.push_back(BinOp.getOperand(i));
13029       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13030                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13031                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13032                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13033                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13034                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13035                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13036                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13037                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13038         BinOps.push_back(BinOp.getOperand(i));
13039       } else {
13040         // We have an input that is not an extension or another binary
13041         // operation; we'll abort this transformation.
13042         return SDValue();
13043       }
13044     }
13045   }
13046 
13047   // Make sure that this is a self-contained cluster of operations (which
13048   // is not quite the same thing as saying that everything has only one
13049   // use).
13050   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13051     if (isa<ConstantSDNode>(Inputs[i]))
13052       continue;
13053 
13054     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13055                               UE = Inputs[i].getNode()->use_end();
13056          UI != UE; ++UI) {
13057       SDNode *User = *UI;
13058       if (User != N && !Visited.count(User))
13059         return SDValue();
13060 
13061       // Make sure that we're not going to promote the non-output-value
13062       // operand(s) or SELECT or SELECT_CC.
13063       // FIXME: Although we could sometimes handle this, and it does occur in
13064       // practice that one of the condition inputs to the select is also one of
13065       // the outputs, we currently can't deal with this.
13066       if (User->getOpcode() == ISD::SELECT) {
13067         if (User->getOperand(0) == Inputs[i])
13068           return SDValue();
13069       } else if (User->getOpcode() == ISD::SELECT_CC) {
13070         if (User->getOperand(0) == Inputs[i] ||
13071             User->getOperand(1) == Inputs[i])
13072           return SDValue();
13073       }
13074     }
13075   }
13076 
13077   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13078     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13079                               UE = PromOps[i].getNode()->use_end();
13080          UI != UE; ++UI) {
13081       SDNode *User = *UI;
13082       if (User != N && !Visited.count(User))
13083         return SDValue();
13084 
13085       // Make sure that we're not going to promote the non-output-value
13086       // operand(s) or SELECT or SELECT_CC.
13087       // FIXME: Although we could sometimes handle this, and it does occur in
13088       // practice that one of the condition inputs to the select is also one of
13089       // the outputs, we currently can't deal with this.
13090       if (User->getOpcode() == ISD::SELECT) {
13091         if (User->getOperand(0) == PromOps[i])
13092           return SDValue();
13093       } else if (User->getOpcode() == ISD::SELECT_CC) {
13094         if (User->getOperand(0) == PromOps[i] ||
13095             User->getOperand(1) == PromOps[i])
13096           return SDValue();
13097       }
13098     }
13099   }
13100 
13101   // Replace all inputs with the extension operand.
13102   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13103     // Constants may have users outside the cluster of to-be-promoted nodes,
13104     // and so we need to replace those as we do the promotions.
13105     if (isa<ConstantSDNode>(Inputs[i]))
13106       continue;
13107     else
13108       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13109   }
13110 
13111   std::list<HandleSDNode> PromOpHandles;
13112   for (auto &PromOp : PromOps)
13113     PromOpHandles.emplace_back(PromOp);
13114 
13115   // Replace all operations (these are all the same, but have a different
13116   // (i1) return type). DAG.getNode will validate that the types of
13117   // a binary operator match, so go through the list in reverse so that
13118   // we've likely promoted both operands first. Any intermediate truncations or
13119   // extensions disappear.
13120   while (!PromOpHandles.empty()) {
13121     SDValue PromOp = PromOpHandles.back().getValue();
13122     PromOpHandles.pop_back();
13123 
13124     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13125         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13126         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13127         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13128       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13129           PromOp.getOperand(0).getValueType() != MVT::i1) {
13130         // The operand is not yet ready (see comment below).
13131         PromOpHandles.emplace_front(PromOp);
13132         continue;
13133       }
13134 
13135       SDValue RepValue = PromOp.getOperand(0);
13136       if (isa<ConstantSDNode>(RepValue))
13137         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13138 
13139       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13140       continue;
13141     }
13142 
13143     unsigned C;
13144     switch (PromOp.getOpcode()) {
13145     default:             C = 0; break;
13146     case ISD::SELECT:    C = 1; break;
13147     case ISD::SELECT_CC: C = 2; break;
13148     }
13149 
13150     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13151          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13152         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13153          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13154       // The to-be-promoted operands of this node have not yet been
13155       // promoted (this should be rare because we're going through the
13156       // list backward, but if one of the operands has several users in
13157       // this cluster of to-be-promoted nodes, it is possible).
13158       PromOpHandles.emplace_front(PromOp);
13159       continue;
13160     }
13161 
13162     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13163                                 PromOp.getNode()->op_end());
13164 
13165     // If there are any constant inputs, make sure they're replaced now.
13166     for (unsigned i = 0; i < 2; ++i)
13167       if (isa<ConstantSDNode>(Ops[C+i]))
13168         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13169 
13170     DAG.ReplaceAllUsesOfValueWith(PromOp,
13171       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13172   }
13173 
13174   // Now we're left with the initial truncation itself.
13175   if (N->getOpcode() == ISD::TRUNCATE)
13176     return N->getOperand(0);
13177 
13178   // Otherwise, this is a comparison. The operands to be compared have just
13179   // changed type (to i1), but everything else is the same.
13180   return SDValue(N, 0);
13181 }
13182 
13183 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13184                                                   DAGCombinerInfo &DCI) const {
13185   SelectionDAG &DAG = DCI.DAG;
13186   SDLoc dl(N);
13187 
13188   // If we're tracking CR bits, we need to be careful that we don't have:
13189   //   zext(binary-ops(trunc(x), trunc(y)))
13190   // or
13191   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13192   // such that we're unnecessarily moving things into CR bits that can more
13193   // efficiently stay in GPRs. Note that if we're not certain that the high
13194   // bits are set as required by the final extension, we still may need to do
13195   // some masking to get the proper behavior.
13196 
13197   // This same functionality is important on PPC64 when dealing with
13198   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13199   // the return values of functions. Because it is so similar, it is handled
13200   // here as well.
13201 
13202   if (N->getValueType(0) != MVT::i32 &&
13203       N->getValueType(0) != MVT::i64)
13204     return SDValue();
13205 
13206   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13207         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13208     return SDValue();
13209 
13210   if (N->getOperand(0).getOpcode() != ISD::AND &&
13211       N->getOperand(0).getOpcode() != ISD::OR  &&
13212       N->getOperand(0).getOpcode() != ISD::XOR &&
13213       N->getOperand(0).getOpcode() != ISD::SELECT &&
13214       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13215     return SDValue();
13216 
13217   SmallVector<SDValue, 4> Inputs;
13218   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13219   SmallPtrSet<SDNode *, 16> Visited;
13220 
13221   // Visit all inputs, collect all binary operations (and, or, xor and
13222   // select) that are all fed by truncations.
13223   while (!BinOps.empty()) {
13224     SDValue BinOp = BinOps.back();
13225     BinOps.pop_back();
13226 
13227     if (!Visited.insert(BinOp.getNode()).second)
13228       continue;
13229 
13230     PromOps.push_back(BinOp);
13231 
13232     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13233       // The condition of the select is not promoted.
13234       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13235         continue;
13236       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13237         continue;
13238 
13239       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13240           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13241         Inputs.push_back(BinOp.getOperand(i));
13242       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13243                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13244                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13245                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13246                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13247         BinOps.push_back(BinOp.getOperand(i));
13248       } else {
13249         // We have an input that is not a truncation or another binary
13250         // operation; we'll abort this transformation.
13251         return SDValue();
13252       }
13253     }
13254   }
13255 
13256   // The operands of a select that must be truncated when the select is
13257   // promoted because the operand is actually part of the to-be-promoted set.
13258   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13259 
13260   // Make sure that this is a self-contained cluster of operations (which
13261   // is not quite the same thing as saying that everything has only one
13262   // use).
13263   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13264     if (isa<ConstantSDNode>(Inputs[i]))
13265       continue;
13266 
13267     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13268                               UE = Inputs[i].getNode()->use_end();
13269          UI != UE; ++UI) {
13270       SDNode *User = *UI;
13271       if (User != N && !Visited.count(User))
13272         return SDValue();
13273 
13274       // If we're going to promote the non-output-value operand(s) or SELECT or
13275       // SELECT_CC, record them for truncation.
13276       if (User->getOpcode() == ISD::SELECT) {
13277         if (User->getOperand(0) == Inputs[i])
13278           SelectTruncOp[0].insert(std::make_pair(User,
13279                                     User->getOperand(0).getValueType()));
13280       } else if (User->getOpcode() == ISD::SELECT_CC) {
13281         if (User->getOperand(0) == Inputs[i])
13282           SelectTruncOp[0].insert(std::make_pair(User,
13283                                     User->getOperand(0).getValueType()));
13284         if (User->getOperand(1) == Inputs[i])
13285           SelectTruncOp[1].insert(std::make_pair(User,
13286                                     User->getOperand(1).getValueType()));
13287       }
13288     }
13289   }
13290 
13291   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13292     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13293                               UE = PromOps[i].getNode()->use_end();
13294          UI != UE; ++UI) {
13295       SDNode *User = *UI;
13296       if (User != N && !Visited.count(User))
13297         return SDValue();
13298 
13299       // If we're going to promote the non-output-value operand(s) or SELECT or
13300       // SELECT_CC, record them for truncation.
13301       if (User->getOpcode() == ISD::SELECT) {
13302         if (User->getOperand(0) == PromOps[i])
13303           SelectTruncOp[0].insert(std::make_pair(User,
13304                                     User->getOperand(0).getValueType()));
13305       } else if (User->getOpcode() == ISD::SELECT_CC) {
13306         if (User->getOperand(0) == PromOps[i])
13307           SelectTruncOp[0].insert(std::make_pair(User,
13308                                     User->getOperand(0).getValueType()));
13309         if (User->getOperand(1) == PromOps[i])
13310           SelectTruncOp[1].insert(std::make_pair(User,
13311                                     User->getOperand(1).getValueType()));
13312       }
13313     }
13314   }
13315 
13316   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13317   bool ReallyNeedsExt = false;
13318   if (N->getOpcode() != ISD::ANY_EXTEND) {
13319     // If all of the inputs are not already sign/zero extended, then
13320     // we'll still need to do that at the end.
13321     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13322       if (isa<ConstantSDNode>(Inputs[i]))
13323         continue;
13324 
13325       unsigned OpBits =
13326         Inputs[i].getOperand(0).getValueSizeInBits();
13327       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13328 
13329       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13330            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13331                                   APInt::getHighBitsSet(OpBits,
13332                                                         OpBits-PromBits))) ||
13333           (N->getOpcode() == ISD::SIGN_EXTEND &&
13334            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13335              (OpBits-(PromBits-1)))) {
13336         ReallyNeedsExt = true;
13337         break;
13338       }
13339     }
13340   }
13341 
13342   // Replace all inputs, either with the truncation operand, or a
13343   // truncation or extension to the final output type.
13344   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13345     // Constant inputs need to be replaced with the to-be-promoted nodes that
13346     // use them because they might have users outside of the cluster of
13347     // promoted nodes.
13348     if (isa<ConstantSDNode>(Inputs[i]))
13349       continue;
13350 
13351     SDValue InSrc = Inputs[i].getOperand(0);
13352     if (Inputs[i].getValueType() == N->getValueType(0))
13353       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13354     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13355       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13356         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13357     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13358       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13359         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13360     else
13361       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13362         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13363   }
13364 
13365   std::list<HandleSDNode> PromOpHandles;
13366   for (auto &PromOp : PromOps)
13367     PromOpHandles.emplace_back(PromOp);
13368 
13369   // Replace all operations (these are all the same, but have a different
13370   // (promoted) return type). DAG.getNode will validate that the types of
13371   // a binary operator match, so go through the list in reverse so that
13372   // we've likely promoted both operands first.
13373   while (!PromOpHandles.empty()) {
13374     SDValue PromOp = PromOpHandles.back().getValue();
13375     PromOpHandles.pop_back();
13376 
13377     unsigned C;
13378     switch (PromOp.getOpcode()) {
13379     default:             C = 0; break;
13380     case ISD::SELECT:    C = 1; break;
13381     case ISD::SELECT_CC: C = 2; break;
13382     }
13383 
13384     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13385          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13386         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13387          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13388       // The to-be-promoted operands of this node have not yet been
13389       // promoted (this should be rare because we're going through the
13390       // list backward, but if one of the operands has several users in
13391       // this cluster of to-be-promoted nodes, it is possible).
13392       PromOpHandles.emplace_front(PromOp);
13393       continue;
13394     }
13395 
13396     // For SELECT and SELECT_CC nodes, we do a similar check for any
13397     // to-be-promoted comparison inputs.
13398     if (PromOp.getOpcode() == ISD::SELECT ||
13399         PromOp.getOpcode() == ISD::SELECT_CC) {
13400       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13401            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13402           (SelectTruncOp[1].count(PromOp.getNode()) &&
13403            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13404         PromOpHandles.emplace_front(PromOp);
13405         continue;
13406       }
13407     }
13408 
13409     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13410                                 PromOp.getNode()->op_end());
13411 
13412     // If this node has constant inputs, then they'll need to be promoted here.
13413     for (unsigned i = 0; i < 2; ++i) {
13414       if (!isa<ConstantSDNode>(Ops[C+i]))
13415         continue;
13416       if (Ops[C+i].getValueType() == N->getValueType(0))
13417         continue;
13418 
13419       if (N->getOpcode() == ISD::SIGN_EXTEND)
13420         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13421       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13422         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13423       else
13424         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13425     }
13426 
13427     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13428     // truncate them again to the original value type.
13429     if (PromOp.getOpcode() == ISD::SELECT ||
13430         PromOp.getOpcode() == ISD::SELECT_CC) {
13431       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13432       if (SI0 != SelectTruncOp[0].end())
13433         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13434       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13435       if (SI1 != SelectTruncOp[1].end())
13436         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13437     }
13438 
13439     DAG.ReplaceAllUsesOfValueWith(PromOp,
13440       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13441   }
13442 
13443   // Now we're left with the initial extension itself.
13444   if (!ReallyNeedsExt)
13445     return N->getOperand(0);
13446 
13447   // To zero extend, just mask off everything except for the first bit (in the
13448   // i1 case).
13449   if (N->getOpcode() == ISD::ZERO_EXTEND)
13450     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13451                        DAG.getConstant(APInt::getLowBitsSet(
13452                                          N->getValueSizeInBits(0), PromBits),
13453                                        dl, N->getValueType(0)));
13454 
13455   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13456          "Invalid extension type");
13457   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13458   SDValue ShiftCst =
13459       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13460   return DAG.getNode(
13461       ISD::SRA, dl, N->getValueType(0),
13462       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13463       ShiftCst);
13464 }
13465 
13466 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13467                                         DAGCombinerInfo &DCI) const {
13468   assert(N->getOpcode() == ISD::SETCC &&
13469          "Should be called with a SETCC node");
13470 
13471   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13472   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13473     SDValue LHS = N->getOperand(0);
13474     SDValue RHS = N->getOperand(1);
13475 
13476     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13477     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13478         LHS.hasOneUse())
13479       std::swap(LHS, RHS);
13480 
13481     // x == 0-y --> x+y == 0
13482     // x != 0-y --> x+y != 0
13483     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13484         RHS.hasOneUse()) {
13485       SDLoc DL(N);
13486       SelectionDAG &DAG = DCI.DAG;
13487       EVT VT = N->getValueType(0);
13488       EVT OpVT = LHS.getValueType();
13489       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13490       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13491     }
13492   }
13493 
13494   return DAGCombineTruncBoolExt(N, DCI);
13495 }
13496 
13497 // Is this an extending load from an f32 to an f64?
13498 static bool isFPExtLoad(SDValue Op) {
13499   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13500     return LD->getExtensionType() == ISD::EXTLOAD &&
13501       Op.getValueType() == MVT::f64;
13502   return false;
13503 }
13504 
13505 /// Reduces the number of fp-to-int conversion when building a vector.
13506 ///
13507 /// If this vector is built out of floating to integer conversions,
13508 /// transform it to a vector built out of floating point values followed by a
13509 /// single floating to integer conversion of the vector.
13510 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13511 /// becomes (fptosi (build_vector ($A, $B, ...)))
13512 SDValue PPCTargetLowering::
13513 combineElementTruncationToVectorTruncation(SDNode *N,
13514                                            DAGCombinerInfo &DCI) const {
13515   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13516          "Should be called with a BUILD_VECTOR node");
13517 
13518   SelectionDAG &DAG = DCI.DAG;
13519   SDLoc dl(N);
13520 
13521   SDValue FirstInput = N->getOperand(0);
13522   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13523          "The input operand must be an fp-to-int conversion.");
13524 
13525   // This combine happens after legalization so the fp_to_[su]i nodes are
13526   // already converted to PPCSISD nodes.
13527   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13528   if (FirstConversion == PPCISD::FCTIDZ ||
13529       FirstConversion == PPCISD::FCTIDUZ ||
13530       FirstConversion == PPCISD::FCTIWZ ||
13531       FirstConversion == PPCISD::FCTIWUZ) {
13532     bool IsSplat = true;
13533     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13534       FirstConversion == PPCISD::FCTIWUZ;
13535     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13536     SmallVector<SDValue, 4> Ops;
13537     EVT TargetVT = N->getValueType(0);
13538     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13539       SDValue NextOp = N->getOperand(i);
13540       if (NextOp.getOpcode() != PPCISD::MFVSR)
13541         return SDValue();
13542       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13543       if (NextConversion != FirstConversion)
13544         return SDValue();
13545       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13546       // This is not valid if the input was originally double precision. It is
13547       // also not profitable to do unless this is an extending load in which
13548       // case doing this combine will allow us to combine consecutive loads.
13549       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13550         return SDValue();
13551       if (N->getOperand(i) != FirstInput)
13552         IsSplat = false;
13553     }
13554 
13555     // If this is a splat, we leave it as-is since there will be only a single
13556     // fp-to-int conversion followed by a splat of the integer. This is better
13557     // for 32-bit and smaller ints and neutral for 64-bit ints.
13558     if (IsSplat)
13559       return SDValue();
13560 
13561     // Now that we know we have the right type of node, get its operands
13562     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13563       SDValue In = N->getOperand(i).getOperand(0);
13564       if (Is32Bit) {
13565         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13566         // here, we know that all inputs are extending loads so this is safe).
13567         if (In.isUndef())
13568           Ops.push_back(DAG.getUNDEF(SrcVT));
13569         else {
13570           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13571                                       MVT::f32, In.getOperand(0),
13572                                       DAG.getIntPtrConstant(1, dl));
13573           Ops.push_back(Trunc);
13574         }
13575       } else
13576         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13577     }
13578 
13579     unsigned Opcode;
13580     if (FirstConversion == PPCISD::FCTIDZ ||
13581         FirstConversion == PPCISD::FCTIWZ)
13582       Opcode = ISD::FP_TO_SINT;
13583     else
13584       Opcode = ISD::FP_TO_UINT;
13585 
13586     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13587     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13588     return DAG.getNode(Opcode, dl, TargetVT, BV);
13589   }
13590   return SDValue();
13591 }
13592 
13593 /// Reduce the number of loads when building a vector.
13594 ///
13595 /// Building a vector out of multiple loads can be converted to a load
13596 /// of the vector type if the loads are consecutive. If the loads are
13597 /// consecutive but in descending order, a shuffle is added at the end
13598 /// to reorder the vector.
13599 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13600   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13601          "Should be called with a BUILD_VECTOR node");
13602 
13603   SDLoc dl(N);
13604 
13605   // Return early for non byte-sized type, as they can't be consecutive.
13606   if (!N->getValueType(0).getVectorElementType().isByteSized())
13607     return SDValue();
13608 
13609   bool InputsAreConsecutiveLoads = true;
13610   bool InputsAreReverseConsecutive = true;
13611   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13612   SDValue FirstInput = N->getOperand(0);
13613   bool IsRoundOfExtLoad = false;
13614 
13615   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13616       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13617     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13618     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13619   }
13620   // Not a build vector of (possibly fp_rounded) loads.
13621   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13622       N->getNumOperands() == 1)
13623     return SDValue();
13624 
13625   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13626     // If any inputs are fp_round(extload), they all must be.
13627     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13628       return SDValue();
13629 
13630     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13631       N->getOperand(i);
13632     if (NextInput.getOpcode() != ISD::LOAD)
13633       return SDValue();
13634 
13635     SDValue PreviousInput =
13636       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13637     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13638     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13639 
13640     // If any inputs are fp_round(extload), they all must be.
13641     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13642       return SDValue();
13643 
13644     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13645       InputsAreConsecutiveLoads = false;
13646     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13647       InputsAreReverseConsecutive = false;
13648 
13649     // Exit early if the loads are neither consecutive nor reverse consecutive.
13650     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13651       return SDValue();
13652   }
13653 
13654   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13655          "The loads cannot be both consecutive and reverse consecutive.");
13656 
13657   SDValue FirstLoadOp =
13658     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13659   SDValue LastLoadOp =
13660     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13661                        N->getOperand(N->getNumOperands()-1);
13662 
13663   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13664   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13665   if (InputsAreConsecutiveLoads) {
13666     assert(LD1 && "Input needs to be a LoadSDNode.");
13667     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13668                        LD1->getBasePtr(), LD1->getPointerInfo(),
13669                        LD1->getAlignment());
13670   }
13671   if (InputsAreReverseConsecutive) {
13672     assert(LDL && "Input needs to be a LoadSDNode.");
13673     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13674                                LDL->getBasePtr(), LDL->getPointerInfo(),
13675                                LDL->getAlignment());
13676     SmallVector<int, 16> Ops;
13677     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13678       Ops.push_back(i);
13679 
13680     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13681                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13682   }
13683   return SDValue();
13684 }
13685 
13686 // This function adds the required vector_shuffle needed to get
13687 // the elements of the vector extract in the correct position
13688 // as specified by the CorrectElems encoding.
13689 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13690                                       SDValue Input, uint64_t Elems,
13691                                       uint64_t CorrectElems) {
13692   SDLoc dl(N);
13693 
13694   unsigned NumElems = Input.getValueType().getVectorNumElements();
13695   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13696 
13697   // Knowing the element indices being extracted from the original
13698   // vector and the order in which they're being inserted, just put
13699   // them at element indices required for the instruction.
13700   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13701     if (DAG.getDataLayout().isLittleEndian())
13702       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13703     else
13704       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13705     CorrectElems = CorrectElems >> 8;
13706     Elems = Elems >> 8;
13707   }
13708 
13709   SDValue Shuffle =
13710       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13711                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13712 
13713   EVT VT = N->getValueType(0);
13714   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13715 
13716   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13717                                Input.getValueType().getVectorElementType(),
13718                                VT.getVectorNumElements());
13719   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13720                      DAG.getValueType(ExtVT));
13721 }
13722 
13723 // Look for build vector patterns where input operands come from sign
13724 // extended vector_extract elements of specific indices. If the correct indices
13725 // aren't used, add a vector shuffle to fix up the indices and create
13726 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13727 // during instruction selection.
13728 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13729   // This array encodes the indices that the vector sign extend instructions
13730   // extract from when extending from one type to another for both BE and LE.
13731   // The right nibble of each byte corresponds to the LE incides.
13732   // and the left nibble of each byte corresponds to the BE incides.
13733   // For example: 0x3074B8FC  byte->word
13734   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13735   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13736   // For example: 0x000070F8  byte->double word
13737   // For LE: the allowed indices are: 0x0,0x8
13738   // For BE: the allowed indices are: 0x7,0xF
13739   uint64_t TargetElems[] = {
13740       0x3074B8FC, // b->w
13741       0x000070F8, // b->d
13742       0x10325476, // h->w
13743       0x00003074, // h->d
13744       0x00001032, // w->d
13745   };
13746 
13747   uint64_t Elems = 0;
13748   int Index;
13749   SDValue Input;
13750 
13751   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13752     if (!Op)
13753       return false;
13754     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13755         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13756       return false;
13757 
13758     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13759     // of the right width.
13760     SDValue Extract = Op.getOperand(0);
13761     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13762       Extract = Extract.getOperand(0);
13763     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13764       return false;
13765 
13766     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13767     if (!ExtOp)
13768       return false;
13769 
13770     Index = ExtOp->getZExtValue();
13771     if (Input && Input != Extract.getOperand(0))
13772       return false;
13773 
13774     if (!Input)
13775       Input = Extract.getOperand(0);
13776 
13777     Elems = Elems << 8;
13778     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13779     Elems |= Index;
13780 
13781     return true;
13782   };
13783 
13784   // If the build vector operands aren't sign extended vector extracts,
13785   // of the same input vector, then return.
13786   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13787     if (!isSExtOfVecExtract(N->getOperand(i))) {
13788       return SDValue();
13789     }
13790   }
13791 
13792   // If the vector extract indicies are not correct, add the appropriate
13793   // vector_shuffle.
13794   int TgtElemArrayIdx;
13795   int InputSize = Input.getValueType().getScalarSizeInBits();
13796   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13797   if (InputSize + OutputSize == 40)
13798     TgtElemArrayIdx = 0;
13799   else if (InputSize + OutputSize == 72)
13800     TgtElemArrayIdx = 1;
13801   else if (InputSize + OutputSize == 48)
13802     TgtElemArrayIdx = 2;
13803   else if (InputSize + OutputSize == 80)
13804     TgtElemArrayIdx = 3;
13805   else if (InputSize + OutputSize == 96)
13806     TgtElemArrayIdx = 4;
13807   else
13808     return SDValue();
13809 
13810   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13811   CorrectElems = DAG.getDataLayout().isLittleEndian()
13812                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13813                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13814   if (Elems != CorrectElems) {
13815     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13816   }
13817 
13818   // Regular lowering will catch cases where a shuffle is not needed.
13819   return SDValue();
13820 }
13821 
13822 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13823                                                  DAGCombinerInfo &DCI) const {
13824   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13825          "Should be called with a BUILD_VECTOR node");
13826 
13827   SelectionDAG &DAG = DCI.DAG;
13828   SDLoc dl(N);
13829 
13830   if (!Subtarget.hasVSX())
13831     return SDValue();
13832 
13833   // The target independent DAG combiner will leave a build_vector of
13834   // float-to-int conversions intact. We can generate MUCH better code for
13835   // a float-to-int conversion of a vector of floats.
13836   SDValue FirstInput = N->getOperand(0);
13837   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13838     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13839     if (Reduced)
13840       return Reduced;
13841   }
13842 
13843   // If we're building a vector out of consecutive loads, just load that
13844   // vector type.
13845   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13846   if (Reduced)
13847     return Reduced;
13848 
13849   // If we're building a vector out of extended elements from another vector
13850   // we have P9 vector integer extend instructions. The code assumes legal
13851   // input types (i.e. it can't handle things like v4i16) so do not run before
13852   // legalization.
13853   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13854     Reduced = combineBVOfVecSExt(N, DAG);
13855     if (Reduced)
13856       return Reduced;
13857   }
13858 
13859 
13860   if (N->getValueType(0) != MVT::v2f64)
13861     return SDValue();
13862 
13863   // Looking for:
13864   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13865   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13866       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13867     return SDValue();
13868   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13869       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13870     return SDValue();
13871   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13872     return SDValue();
13873 
13874   SDValue Ext1 = FirstInput.getOperand(0);
13875   SDValue Ext2 = N->getOperand(1).getOperand(0);
13876   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13877      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13878     return SDValue();
13879 
13880   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13881   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13882   if (!Ext1Op || !Ext2Op)
13883     return SDValue();
13884   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13885       Ext1.getOperand(0) != Ext2.getOperand(0))
13886     return SDValue();
13887 
13888   int FirstElem = Ext1Op->getZExtValue();
13889   int SecondElem = Ext2Op->getZExtValue();
13890   int SubvecIdx;
13891   if (FirstElem == 0 && SecondElem == 1)
13892     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13893   else if (FirstElem == 2 && SecondElem == 3)
13894     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13895   else
13896     return SDValue();
13897 
13898   SDValue SrcVec = Ext1.getOperand(0);
13899   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13900     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13901   return DAG.getNode(NodeType, dl, MVT::v2f64,
13902                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13903 }
13904 
13905 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13906                                               DAGCombinerInfo &DCI) const {
13907   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13908           N->getOpcode() == ISD::UINT_TO_FP) &&
13909          "Need an int -> FP conversion node here");
13910 
13911   if (useSoftFloat() || !Subtarget.has64BitSupport())
13912     return SDValue();
13913 
13914   SelectionDAG &DAG = DCI.DAG;
13915   SDLoc dl(N);
13916   SDValue Op(N, 0);
13917 
13918   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13919   // from the hardware.
13920   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13921     return SDValue();
13922   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13923       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13924     return SDValue();
13925 
13926   SDValue FirstOperand(Op.getOperand(0));
13927   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13928     (FirstOperand.getValueType() == MVT::i8 ||
13929      FirstOperand.getValueType() == MVT::i16);
13930   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13931     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13932     bool DstDouble = Op.getValueType() == MVT::f64;
13933     unsigned ConvOp = Signed ?
13934       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13935       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13936     SDValue WidthConst =
13937       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13938                             dl, false);
13939     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13940     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13941     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13942                                          DAG.getVTList(MVT::f64, MVT::Other),
13943                                          Ops, MVT::i8, LDN->getMemOperand());
13944 
13945     // For signed conversion, we need to sign-extend the value in the VSR
13946     if (Signed) {
13947       SDValue ExtOps[] = { Ld, WidthConst };
13948       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13949       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13950     } else
13951       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13952   }
13953 
13954 
13955   // For i32 intermediate values, unfortunately, the conversion functions
13956   // leave the upper 32 bits of the value are undefined. Within the set of
13957   // scalar instructions, we have no method for zero- or sign-extending the
13958   // value. Thus, we cannot handle i32 intermediate values here.
13959   if (Op.getOperand(0).getValueType() == MVT::i32)
13960     return SDValue();
13961 
13962   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13963          "UINT_TO_FP is supported only with FPCVT");
13964 
13965   // If we have FCFIDS, then use it when converting to single-precision.
13966   // Otherwise, convert to double-precision and then round.
13967   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13968                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13969                                                             : PPCISD::FCFIDS)
13970                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13971                                                             : PPCISD::FCFID);
13972   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13973                   ? MVT::f32
13974                   : MVT::f64;
13975 
13976   // If we're converting from a float, to an int, and back to a float again,
13977   // then we don't need the store/load pair at all.
13978   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13979        Subtarget.hasFPCVT()) ||
13980       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13981     SDValue Src = Op.getOperand(0).getOperand(0);
13982     if (Src.getValueType() == MVT::f32) {
13983       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13984       DCI.AddToWorklist(Src.getNode());
13985     } else if (Src.getValueType() != MVT::f64) {
13986       // Make sure that we don't pick up a ppc_fp128 source value.
13987       return SDValue();
13988     }
13989 
13990     unsigned FCTOp =
13991       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13992                                                         PPCISD::FCTIDUZ;
13993 
13994     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13995     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13996 
13997     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13998       FP = DAG.getNode(ISD::FP_ROUND, dl,
13999                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14000       DCI.AddToWorklist(FP.getNode());
14001     }
14002 
14003     return FP;
14004   }
14005 
14006   return SDValue();
14007 }
14008 
14009 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14010 // builtins) into loads with swaps.
14011 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14012                                               DAGCombinerInfo &DCI) const {
14013   SelectionDAG &DAG = DCI.DAG;
14014   SDLoc dl(N);
14015   SDValue Chain;
14016   SDValue Base;
14017   MachineMemOperand *MMO;
14018 
14019   switch (N->getOpcode()) {
14020   default:
14021     llvm_unreachable("Unexpected opcode for little endian VSX load");
14022   case ISD::LOAD: {
14023     LoadSDNode *LD = cast<LoadSDNode>(N);
14024     Chain = LD->getChain();
14025     Base = LD->getBasePtr();
14026     MMO = LD->getMemOperand();
14027     // If the MMO suggests this isn't a load of a full vector, leave
14028     // things alone.  For a built-in, we have to make the change for
14029     // correctness, so if there is a size problem that will be a bug.
14030     if (MMO->getSize() < 16)
14031       return SDValue();
14032     break;
14033   }
14034   case ISD::INTRINSIC_W_CHAIN: {
14035     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14036     Chain = Intrin->getChain();
14037     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14038     // us what we want. Get operand 2 instead.
14039     Base = Intrin->getOperand(2);
14040     MMO = Intrin->getMemOperand();
14041     break;
14042   }
14043   }
14044 
14045   MVT VecTy = N->getValueType(0).getSimpleVT();
14046 
14047   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14048   // aligned and the type is a vector with elements up to 4 bytes
14049   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14050       VecTy.getScalarSizeInBits() <= 32) {
14051     return SDValue();
14052   }
14053 
14054   SDValue LoadOps[] = { Chain, Base };
14055   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14056                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14057                                          LoadOps, MVT::v2f64, MMO);
14058 
14059   DCI.AddToWorklist(Load.getNode());
14060   Chain = Load.getValue(1);
14061   SDValue Swap = DAG.getNode(
14062       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14063   DCI.AddToWorklist(Swap.getNode());
14064 
14065   // Add a bitcast if the resulting load type doesn't match v2f64.
14066   if (VecTy != MVT::v2f64) {
14067     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14068     DCI.AddToWorklist(N.getNode());
14069     // Package {bitcast value, swap's chain} to match Load's shape.
14070     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14071                        N, Swap.getValue(1));
14072   }
14073 
14074   return Swap;
14075 }
14076 
14077 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14078 // builtins) into stores with swaps.
14079 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14080                                                DAGCombinerInfo &DCI) const {
14081   SelectionDAG &DAG = DCI.DAG;
14082   SDLoc dl(N);
14083   SDValue Chain;
14084   SDValue Base;
14085   unsigned SrcOpnd;
14086   MachineMemOperand *MMO;
14087 
14088   switch (N->getOpcode()) {
14089   default:
14090     llvm_unreachable("Unexpected opcode for little endian VSX store");
14091   case ISD::STORE: {
14092     StoreSDNode *ST = cast<StoreSDNode>(N);
14093     Chain = ST->getChain();
14094     Base = ST->getBasePtr();
14095     MMO = ST->getMemOperand();
14096     SrcOpnd = 1;
14097     // If the MMO suggests this isn't a store of a full vector, leave
14098     // things alone.  For a built-in, we have to make the change for
14099     // correctness, so if there is a size problem that will be a bug.
14100     if (MMO->getSize() < 16)
14101       return SDValue();
14102     break;
14103   }
14104   case ISD::INTRINSIC_VOID: {
14105     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14106     Chain = Intrin->getChain();
14107     // Intrin->getBasePtr() oddly does not get what we want.
14108     Base = Intrin->getOperand(3);
14109     MMO = Intrin->getMemOperand();
14110     SrcOpnd = 2;
14111     break;
14112   }
14113   }
14114 
14115   SDValue Src = N->getOperand(SrcOpnd);
14116   MVT VecTy = Src.getValueType().getSimpleVT();
14117 
14118   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14119   // aligned and the type is a vector with elements up to 4 bytes
14120   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14121       VecTy.getScalarSizeInBits() <= 32) {
14122     return SDValue();
14123   }
14124 
14125   // All stores are done as v2f64 and possible bit cast.
14126   if (VecTy != MVT::v2f64) {
14127     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14128     DCI.AddToWorklist(Src.getNode());
14129   }
14130 
14131   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14132                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14133   DCI.AddToWorklist(Swap.getNode());
14134   Chain = Swap.getValue(1);
14135   SDValue StoreOps[] = { Chain, Swap, Base };
14136   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14137                                           DAG.getVTList(MVT::Other),
14138                                           StoreOps, VecTy, MMO);
14139   DCI.AddToWorklist(Store.getNode());
14140   return Store;
14141 }
14142 
14143 // Handle DAG combine for STORE (FP_TO_INT F).
14144 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14145                                                DAGCombinerInfo &DCI) const {
14146 
14147   SelectionDAG &DAG = DCI.DAG;
14148   SDLoc dl(N);
14149   unsigned Opcode = N->getOperand(1).getOpcode();
14150 
14151   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14152          && "Not a FP_TO_INT Instruction!");
14153 
14154   SDValue Val = N->getOperand(1).getOperand(0);
14155   EVT Op1VT = N->getOperand(1).getValueType();
14156   EVT ResVT = Val.getValueType();
14157 
14158   // Floating point types smaller than 32 bits are not legal on Power.
14159   if (ResVT.getScalarSizeInBits() < 32)
14160     return SDValue();
14161 
14162   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14163   bool ValidTypeForStoreFltAsInt =
14164         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14165          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14166 
14167   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14168       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14169     return SDValue();
14170 
14171   // Extend f32 values to f64
14172   if (ResVT.getScalarSizeInBits() == 32) {
14173     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14174     DCI.AddToWorklist(Val.getNode());
14175   }
14176 
14177   // Set signed or unsigned conversion opcode.
14178   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14179                           PPCISD::FP_TO_SINT_IN_VSR :
14180                           PPCISD::FP_TO_UINT_IN_VSR;
14181 
14182   Val = DAG.getNode(ConvOpcode,
14183                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14184   DCI.AddToWorklist(Val.getNode());
14185 
14186   // Set number of bytes being converted.
14187   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14188   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14189                     DAG.getIntPtrConstant(ByteSize, dl, false),
14190                     DAG.getValueType(Op1VT) };
14191 
14192   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14193           DAG.getVTList(MVT::Other), Ops,
14194           cast<StoreSDNode>(N)->getMemoryVT(),
14195           cast<StoreSDNode>(N)->getMemOperand());
14196 
14197   DCI.AddToWorklist(Val.getNode());
14198   return Val;
14199 }
14200 
14201 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14202   // Check that the source of the element keeps flipping
14203   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14204   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14205   for (int i = 1, e = Mask.size(); i < e; i++) {
14206     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14207       return false;
14208     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14209       return false;
14210     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14211   }
14212   return true;
14213 }
14214 
14215 static bool isSplatBV(SDValue Op) {
14216   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14217     return false;
14218   SDValue FirstOp;
14219 
14220   // Find first non-undef input.
14221   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14222     FirstOp = Op.getOperand(i);
14223     if (!FirstOp.isUndef())
14224       break;
14225   }
14226 
14227   // All inputs are undef or the same as the first non-undef input.
14228   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14229     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14230       return false;
14231   return true;
14232 }
14233 
14234 static SDValue isScalarToVec(SDValue Op) {
14235   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14236     return Op;
14237   if (Op.getOpcode() != ISD::BITCAST)
14238     return SDValue();
14239   Op = Op.getOperand(0);
14240   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14241     return Op;
14242   return SDValue();
14243 }
14244 
14245 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14246                                             int LHSMaxIdx, int RHSMinIdx,
14247                                             int RHSMaxIdx, int HalfVec) {
14248   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14249     int Idx = ShuffV[i];
14250     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14251       ShuffV[i] += HalfVec;
14252   }
14253   return;
14254 }
14255 
14256 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14257 // the original is:
14258 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14259 // In such a case, just change the shuffle mask to extract the element
14260 // from the permuted index.
14261 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14262   SDLoc dl(OrigSToV);
14263   EVT VT = OrigSToV.getValueType();
14264   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14265          "Expecting a SCALAR_TO_VECTOR here");
14266   SDValue Input = OrigSToV.getOperand(0);
14267 
14268   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14269     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14270     SDValue OrigVector = Input.getOperand(0);
14271 
14272     // Can't handle non-const element indices or different vector types
14273     // for the input to the extract and the output of the scalar_to_vector.
14274     if (Idx && VT == OrigVector.getValueType()) {
14275       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14276       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14277       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14278     }
14279   }
14280   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14281                      OrigSToV.getOperand(0));
14282 }
14283 
14284 // On little endian subtargets, combine shuffles such as:
14285 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14286 // into:
14287 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14288 // because the latter can be matched to a single instruction merge.
14289 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14290 // to put the value into element zero. Adjust the shuffle mask so that the
14291 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14292 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14293                                                 SelectionDAG &DAG) const {
14294   SDValue LHS = SVN->getOperand(0);
14295   SDValue RHS = SVN->getOperand(1);
14296   auto Mask = SVN->getMask();
14297   int NumElts = LHS.getValueType().getVectorNumElements();
14298   SDValue Res(SVN, 0);
14299   SDLoc dl(SVN);
14300 
14301   // None of these combines are useful on big endian systems since the ISA
14302   // already has a big endian bias.
14303   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14304     return Res;
14305 
14306   // If this is not a shuffle of a shuffle and the first element comes from
14307   // the second vector, canonicalize to the commuted form. This will make it
14308   // more likely to match one of the single instruction patterns.
14309   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14310       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14311     std::swap(LHS, RHS);
14312     Res = DAG.getCommutedVectorShuffle(*SVN);
14313     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14314   }
14315 
14316   // Adjust the shuffle mask if either input vector comes from a
14317   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14318   // form (to prevent the need for a swap).
14319   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14320   SDValue SToVLHS = isScalarToVec(LHS);
14321   SDValue SToVRHS = isScalarToVec(RHS);
14322   if (SToVLHS || SToVRHS) {
14323     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14324                             : SToVRHS.getValueType().getVectorNumElements();
14325     int NumEltsOut = ShuffV.size();
14326 
14327     // Initially assume that neither input is permuted. These will be adjusted
14328     // accordingly if either input is.
14329     int LHSMaxIdx = -1;
14330     int RHSMinIdx = -1;
14331     int RHSMaxIdx = -1;
14332     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14333 
14334     // Get the permuted scalar to vector nodes for the source(s) that come from
14335     // ISD::SCALAR_TO_VECTOR.
14336     if (SToVLHS) {
14337       // Set up the values for the shuffle vector fixup.
14338       LHSMaxIdx = NumEltsOut / NumEltsIn;
14339       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14340       if (SToVLHS.getValueType() != LHS.getValueType())
14341         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14342       LHS = SToVLHS;
14343     }
14344     if (SToVRHS) {
14345       RHSMinIdx = NumEltsOut;
14346       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14347       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14348       if (SToVRHS.getValueType() != RHS.getValueType())
14349         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14350       RHS = SToVRHS;
14351     }
14352 
14353     // Fix up the shuffle mask to reflect where the desired element actually is.
14354     // The minimum and maximum indices that correspond to element zero for both
14355     // the LHS and RHS are computed and will control which shuffle mask entries
14356     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14357     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14358     // HalfVec to refer to the corresponding element in the permuted vector.
14359     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14360                                     HalfVec);
14361     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14362 
14363     // We may have simplified away the shuffle. We won't be able to do anything
14364     // further with it here.
14365     if (!isa<ShuffleVectorSDNode>(Res))
14366       return Res;
14367     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14368   }
14369 
14370   // The common case after we commuted the shuffle is that the RHS is a splat
14371   // and we have elements coming in from the splat at indices that are not
14372   // conducive to using a merge.
14373   // Example:
14374   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14375   if (!isSplatBV(RHS))
14376     return Res;
14377 
14378   // We are looking for a mask such that all even elements are from
14379   // one vector and all odd elements from the other.
14380   if (!isAlternatingShuffMask(Mask, NumElts))
14381     return Res;
14382 
14383   // Adjust the mask so we are pulling in the same index from the splat
14384   // as the index from the interesting vector in consecutive elements.
14385   // Example (even elements from first vector):
14386   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14387   if (Mask[0] < NumElts)
14388     for (int i = 1, e = Mask.size(); i < e; i += 2)
14389       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14390   // Example (odd elements from first vector):
14391   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14392   else
14393     for (int i = 0, e = Mask.size(); i < e; i += 2)
14394       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14395 
14396   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14397   return Res;
14398 }
14399 
14400 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14401                                                 LSBaseSDNode *LSBase,
14402                                                 DAGCombinerInfo &DCI) const {
14403   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14404         "Not a reverse memop pattern!");
14405 
14406   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14407     auto Mask = SVN->getMask();
14408     int i = 0;
14409     auto I = Mask.rbegin();
14410     auto E = Mask.rend();
14411 
14412     for (; I != E; ++I) {
14413       if (*I != i)
14414         return false;
14415       i++;
14416     }
14417     return true;
14418   };
14419 
14420   SelectionDAG &DAG = DCI.DAG;
14421   EVT VT = SVN->getValueType(0);
14422 
14423   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14424     return SDValue();
14425 
14426   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14427   // See comment in PPCVSXSwapRemoval.cpp.
14428   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14429   if (!Subtarget.hasP9Vector())
14430     return SDValue();
14431 
14432   if(!IsElementReverse(SVN))
14433     return SDValue();
14434 
14435   if (LSBase->getOpcode() == ISD::LOAD) {
14436     SDLoc dl(SVN);
14437     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14438     return DAG.getMemIntrinsicNode(
14439         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14440         LSBase->getMemoryVT(), LSBase->getMemOperand());
14441   }
14442 
14443   if (LSBase->getOpcode() == ISD::STORE) {
14444     SDLoc dl(LSBase);
14445     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14446                           LSBase->getBasePtr()};
14447     return DAG.getMemIntrinsicNode(
14448         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14449         LSBase->getMemoryVT(), LSBase->getMemOperand());
14450   }
14451 
14452   llvm_unreachable("Expected a load or store node here");
14453 }
14454 
14455 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14456                                              DAGCombinerInfo &DCI) const {
14457   SelectionDAG &DAG = DCI.DAG;
14458   SDLoc dl(N);
14459   switch (N->getOpcode()) {
14460   default: break;
14461   case ISD::ADD:
14462     return combineADD(N, DCI);
14463   case ISD::SHL:
14464     return combineSHL(N, DCI);
14465   case ISD::SRA:
14466     return combineSRA(N, DCI);
14467   case ISD::SRL:
14468     return combineSRL(N, DCI);
14469   case ISD::MUL:
14470     return combineMUL(N, DCI);
14471   case ISD::FMA:
14472   case PPCISD::FNMSUB:
14473     return combineFMALike(N, DCI);
14474   case PPCISD::SHL:
14475     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14476         return N->getOperand(0);
14477     break;
14478   case PPCISD::SRL:
14479     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14480         return N->getOperand(0);
14481     break;
14482   case PPCISD::SRA:
14483     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14484       if (C->isNullValue() ||   //  0 >>s V -> 0.
14485           C->isAllOnesValue())    // -1 >>s V -> -1.
14486         return N->getOperand(0);
14487     }
14488     break;
14489   case ISD::SIGN_EXTEND:
14490   case ISD::ZERO_EXTEND:
14491   case ISD::ANY_EXTEND:
14492     return DAGCombineExtBoolTrunc(N, DCI);
14493   case ISD::TRUNCATE:
14494     return combineTRUNCATE(N, DCI);
14495   case ISD::SETCC:
14496     if (SDValue CSCC = combineSetCC(N, DCI))
14497       return CSCC;
14498     LLVM_FALLTHROUGH;
14499   case ISD::SELECT_CC:
14500     return DAGCombineTruncBoolExt(N, DCI);
14501   case ISD::SINT_TO_FP:
14502   case ISD::UINT_TO_FP:
14503     return combineFPToIntToFP(N, DCI);
14504   case ISD::VECTOR_SHUFFLE:
14505     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14506       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14507       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14508     }
14509     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14510   case ISD::STORE: {
14511 
14512     EVT Op1VT = N->getOperand(1).getValueType();
14513     unsigned Opcode = N->getOperand(1).getOpcode();
14514 
14515     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14516       SDValue Val= combineStoreFPToInt(N, DCI);
14517       if (Val)
14518         return Val;
14519     }
14520 
14521     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14522       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14523       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14524       if (Val)
14525         return Val;
14526     }
14527 
14528     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14529     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14530         N->getOperand(1).getNode()->hasOneUse() &&
14531         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14532          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14533 
14534       // STBRX can only handle simple types and it makes no sense to store less
14535       // two bytes in byte-reversed order.
14536       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14537       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14538         break;
14539 
14540       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14541       // Do an any-extend to 32-bits if this is a half-word input.
14542       if (BSwapOp.getValueType() == MVT::i16)
14543         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14544 
14545       // If the type of BSWAP operand is wider than stored memory width
14546       // it need to be shifted to the right side before STBRX.
14547       if (Op1VT.bitsGT(mVT)) {
14548         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14549         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14550                               DAG.getConstant(Shift, dl, MVT::i32));
14551         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14552         if (Op1VT == MVT::i64)
14553           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14554       }
14555 
14556       SDValue Ops[] = {
14557         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14558       };
14559       return
14560         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14561                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14562                                 cast<StoreSDNode>(N)->getMemOperand());
14563     }
14564 
14565     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14566     // So it can increase the chance of CSE constant construction.
14567     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14568         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14569       // Need to sign-extended to 64-bits to handle negative values.
14570       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14571       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14572                                     MemVT.getSizeInBits());
14573       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14574 
14575       // DAG.getTruncStore() can't be used here because it doesn't accept
14576       // the general (base + offset) addressing mode.
14577       // So we use UpdateNodeOperands and setTruncatingStore instead.
14578       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14579                              N->getOperand(3));
14580       cast<StoreSDNode>(N)->setTruncatingStore(true);
14581       return SDValue(N, 0);
14582     }
14583 
14584     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14585     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14586     if (Op1VT.isSimple()) {
14587       MVT StoreVT = Op1VT.getSimpleVT();
14588       if (Subtarget.needsSwapsForVSXMemOps() &&
14589           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14590            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14591         return expandVSXStoreForLE(N, DCI);
14592     }
14593     break;
14594   }
14595   case ISD::LOAD: {
14596     LoadSDNode *LD = cast<LoadSDNode>(N);
14597     EVT VT = LD->getValueType(0);
14598 
14599     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14600     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14601     if (VT.isSimple()) {
14602       MVT LoadVT = VT.getSimpleVT();
14603       if (Subtarget.needsSwapsForVSXMemOps() &&
14604           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14605            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14606         return expandVSXLoadForLE(N, DCI);
14607     }
14608 
14609     // We sometimes end up with a 64-bit integer load, from which we extract
14610     // two single-precision floating-point numbers. This happens with
14611     // std::complex<float>, and other similar structures, because of the way we
14612     // canonicalize structure copies. However, if we lack direct moves,
14613     // then the final bitcasts from the extracted integer values to the
14614     // floating-point numbers turn into store/load pairs. Even with direct moves,
14615     // just loading the two floating-point numbers is likely better.
14616     auto ReplaceTwoFloatLoad = [&]() {
14617       if (VT != MVT::i64)
14618         return false;
14619 
14620       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14621           LD->isVolatile())
14622         return false;
14623 
14624       //  We're looking for a sequence like this:
14625       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14626       //      t16: i64 = srl t13, Constant:i32<32>
14627       //    t17: i32 = truncate t16
14628       //  t18: f32 = bitcast t17
14629       //    t19: i32 = truncate t13
14630       //  t20: f32 = bitcast t19
14631 
14632       if (!LD->hasNUsesOfValue(2, 0))
14633         return false;
14634 
14635       auto UI = LD->use_begin();
14636       while (UI.getUse().getResNo() != 0) ++UI;
14637       SDNode *Trunc = *UI++;
14638       while (UI.getUse().getResNo() != 0) ++UI;
14639       SDNode *RightShift = *UI;
14640       if (Trunc->getOpcode() != ISD::TRUNCATE)
14641         std::swap(Trunc, RightShift);
14642 
14643       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14644           Trunc->getValueType(0) != MVT::i32 ||
14645           !Trunc->hasOneUse())
14646         return false;
14647       if (RightShift->getOpcode() != ISD::SRL ||
14648           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14649           RightShift->getConstantOperandVal(1) != 32 ||
14650           !RightShift->hasOneUse())
14651         return false;
14652 
14653       SDNode *Trunc2 = *RightShift->use_begin();
14654       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14655           Trunc2->getValueType(0) != MVT::i32 ||
14656           !Trunc2->hasOneUse())
14657         return false;
14658 
14659       SDNode *Bitcast = *Trunc->use_begin();
14660       SDNode *Bitcast2 = *Trunc2->use_begin();
14661 
14662       if (Bitcast->getOpcode() != ISD::BITCAST ||
14663           Bitcast->getValueType(0) != MVT::f32)
14664         return false;
14665       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14666           Bitcast2->getValueType(0) != MVT::f32)
14667         return false;
14668 
14669       if (Subtarget.isLittleEndian())
14670         std::swap(Bitcast, Bitcast2);
14671 
14672       // Bitcast has the second float (in memory-layout order) and Bitcast2
14673       // has the first one.
14674 
14675       SDValue BasePtr = LD->getBasePtr();
14676       if (LD->isIndexed()) {
14677         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14678                "Non-pre-inc AM on PPC?");
14679         BasePtr =
14680           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14681                       LD->getOffset());
14682       }
14683 
14684       auto MMOFlags =
14685           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14686       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14687                                       LD->getPointerInfo(), LD->getAlignment(),
14688                                       MMOFlags, LD->getAAInfo());
14689       SDValue AddPtr =
14690         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14691                     BasePtr, DAG.getIntPtrConstant(4, dl));
14692       SDValue FloatLoad2 = DAG.getLoad(
14693           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14694           LD->getPointerInfo().getWithOffset(4),
14695           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14696 
14697       if (LD->isIndexed()) {
14698         // Note that DAGCombine should re-form any pre-increment load(s) from
14699         // what is produced here if that makes sense.
14700         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14701       }
14702 
14703       DCI.CombineTo(Bitcast2, FloatLoad);
14704       DCI.CombineTo(Bitcast, FloatLoad2);
14705 
14706       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14707                                     SDValue(FloatLoad2.getNode(), 1));
14708       return true;
14709     };
14710 
14711     if (ReplaceTwoFloatLoad())
14712       return SDValue(N, 0);
14713 
14714     EVT MemVT = LD->getMemoryVT();
14715     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14716     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14717     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14718     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14719     if (LD->isUnindexed() && VT.isVector() &&
14720         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14721           // P8 and later hardware should just use LOAD.
14722           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14723                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14724          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14725           LD->getAlignment() >= ScalarABIAlignment)) &&
14726         LD->getAlignment() < ABIAlignment) {
14727       // This is a type-legal unaligned Altivec or QPX load.
14728       SDValue Chain = LD->getChain();
14729       SDValue Ptr = LD->getBasePtr();
14730       bool isLittleEndian = Subtarget.isLittleEndian();
14731 
14732       // This implements the loading of unaligned vectors as described in
14733       // the venerable Apple Velocity Engine overview. Specifically:
14734       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14735       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14736       //
14737       // The general idea is to expand a sequence of one or more unaligned
14738       // loads into an alignment-based permutation-control instruction (lvsl
14739       // or lvsr), a series of regular vector loads (which always truncate
14740       // their input address to an aligned address), and a series of
14741       // permutations.  The results of these permutations are the requested
14742       // loaded values.  The trick is that the last "extra" load is not taken
14743       // from the address you might suspect (sizeof(vector) bytes after the
14744       // last requested load), but rather sizeof(vector) - 1 bytes after the
14745       // last requested vector. The point of this is to avoid a page fault if
14746       // the base address happened to be aligned. This works because if the
14747       // base address is aligned, then adding less than a full vector length
14748       // will cause the last vector in the sequence to be (re)loaded.
14749       // Otherwise, the next vector will be fetched as you might suspect was
14750       // necessary.
14751 
14752       // We might be able to reuse the permutation generation from
14753       // a different base address offset from this one by an aligned amount.
14754       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14755       // optimization later.
14756       Intrinsic::ID Intr, IntrLD, IntrPerm;
14757       MVT PermCntlTy, PermTy, LDTy;
14758       if (Subtarget.hasAltivec()) {
14759         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14760                                  Intrinsic::ppc_altivec_lvsl;
14761         IntrLD = Intrinsic::ppc_altivec_lvx;
14762         IntrPerm = Intrinsic::ppc_altivec_vperm;
14763         PermCntlTy = MVT::v16i8;
14764         PermTy = MVT::v4i32;
14765         LDTy = MVT::v4i32;
14766       } else {
14767         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14768                                        Intrinsic::ppc_qpx_qvlpcls;
14769         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14770                                        Intrinsic::ppc_qpx_qvlfs;
14771         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14772         PermCntlTy = MVT::v4f64;
14773         PermTy = MVT::v4f64;
14774         LDTy = MemVT.getSimpleVT();
14775       }
14776 
14777       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14778 
14779       // Create the new MMO for the new base load. It is like the original MMO,
14780       // but represents an area in memory almost twice the vector size centered
14781       // on the original address. If the address is unaligned, we might start
14782       // reading up to (sizeof(vector)-1) bytes below the address of the
14783       // original unaligned load.
14784       MachineFunction &MF = DAG.getMachineFunction();
14785       MachineMemOperand *BaseMMO =
14786         MF.getMachineMemOperand(LD->getMemOperand(),
14787                                 -(long)MemVT.getStoreSize()+1,
14788                                 2*MemVT.getStoreSize()-1);
14789 
14790       // Create the new base load.
14791       SDValue LDXIntID =
14792           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14793       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14794       SDValue BaseLoad =
14795         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14796                                 DAG.getVTList(PermTy, MVT::Other),
14797                                 BaseLoadOps, LDTy, BaseMMO);
14798 
14799       // Note that the value of IncOffset (which is provided to the next
14800       // load's pointer info offset value, and thus used to calculate the
14801       // alignment), and the value of IncValue (which is actually used to
14802       // increment the pointer value) are different! This is because we
14803       // require the next load to appear to be aligned, even though it
14804       // is actually offset from the base pointer by a lesser amount.
14805       int IncOffset = VT.getSizeInBits() / 8;
14806       int IncValue = IncOffset;
14807 
14808       // Walk (both up and down) the chain looking for another load at the real
14809       // (aligned) offset (the alignment of the other load does not matter in
14810       // this case). If found, then do not use the offset reduction trick, as
14811       // that will prevent the loads from being later combined (as they would
14812       // otherwise be duplicates).
14813       if (!findConsecutiveLoad(LD, DAG))
14814         --IncValue;
14815 
14816       SDValue Increment =
14817           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14818       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14819 
14820       MachineMemOperand *ExtraMMO =
14821         MF.getMachineMemOperand(LD->getMemOperand(),
14822                                 1, 2*MemVT.getStoreSize()-1);
14823       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14824       SDValue ExtraLoad =
14825         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14826                                 DAG.getVTList(PermTy, MVT::Other),
14827                                 ExtraLoadOps, LDTy, ExtraMMO);
14828 
14829       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14830         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14831 
14832       // Because vperm has a big-endian bias, we must reverse the order
14833       // of the input vectors and complement the permute control vector
14834       // when generating little endian code.  We have already handled the
14835       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14836       // and ExtraLoad here.
14837       SDValue Perm;
14838       if (isLittleEndian)
14839         Perm = BuildIntrinsicOp(IntrPerm,
14840                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14841       else
14842         Perm = BuildIntrinsicOp(IntrPerm,
14843                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14844 
14845       if (VT != PermTy)
14846         Perm = Subtarget.hasAltivec() ?
14847                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14848                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14849                                DAG.getTargetConstant(1, dl, MVT::i64));
14850                                // second argument is 1 because this rounding
14851                                // is always exact.
14852 
14853       // The output of the permutation is our loaded result, the TokenFactor is
14854       // our new chain.
14855       DCI.CombineTo(N, Perm, TF);
14856       return SDValue(N, 0);
14857     }
14858     }
14859     break;
14860     case ISD::INTRINSIC_WO_CHAIN: {
14861       bool isLittleEndian = Subtarget.isLittleEndian();
14862       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14863       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14864                                            : Intrinsic::ppc_altivec_lvsl);
14865       if ((IID == Intr ||
14866            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14867            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14868         N->getOperand(1)->getOpcode() == ISD::ADD) {
14869         SDValue Add = N->getOperand(1);
14870 
14871         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14872                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14873 
14874         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14875                                   APInt::getAllOnesValue(Bits /* alignment */)
14876                                       .zext(Add.getScalarValueSizeInBits()))) {
14877           SDNode *BasePtr = Add->getOperand(0).getNode();
14878           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14879                                     UE = BasePtr->use_end();
14880                UI != UE; ++UI) {
14881             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14882                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14883               // We've found another LVSL/LVSR, and this address is an aligned
14884               // multiple of that one. The results will be the same, so use the
14885               // one we've just found instead.
14886 
14887               return SDValue(*UI, 0);
14888             }
14889           }
14890         }
14891 
14892         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14893           SDNode *BasePtr = Add->getOperand(0).getNode();
14894           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14895                UE = BasePtr->use_end(); UI != UE; ++UI) {
14896             if (UI->getOpcode() == ISD::ADD &&
14897                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14898                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14899                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14900                 (1ULL << Bits) == 0) {
14901               SDNode *OtherAdd = *UI;
14902               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14903                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14904                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14905                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14906                   return SDValue(*VI, 0);
14907                 }
14908               }
14909             }
14910           }
14911         }
14912       }
14913 
14914       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14915       // Expose the vabsduw/h/b opportunity for down stream
14916       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14917           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14918            IID == Intrinsic::ppc_altivec_vmaxsh ||
14919            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14920         SDValue V1 = N->getOperand(1);
14921         SDValue V2 = N->getOperand(2);
14922         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14923              V1.getSimpleValueType() == MVT::v8i16 ||
14924              V1.getSimpleValueType() == MVT::v16i8) &&
14925             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14926           // (0-a, a)
14927           if (V1.getOpcode() == ISD::SUB &&
14928               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14929               V1.getOperand(1) == V2) {
14930             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14931           }
14932           // (a, 0-a)
14933           if (V2.getOpcode() == ISD::SUB &&
14934               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14935               V2.getOperand(1) == V1) {
14936             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14937           }
14938           // (x-y, y-x)
14939           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14940               V1.getOperand(0) == V2.getOperand(1) &&
14941               V1.getOperand(1) == V2.getOperand(0)) {
14942             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14943           }
14944         }
14945       }
14946     }
14947 
14948     break;
14949   case ISD::INTRINSIC_W_CHAIN:
14950     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14951     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14952     if (Subtarget.needsSwapsForVSXMemOps()) {
14953       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14954       default:
14955         break;
14956       case Intrinsic::ppc_vsx_lxvw4x:
14957       case Intrinsic::ppc_vsx_lxvd2x:
14958         return expandVSXLoadForLE(N, DCI);
14959       }
14960     }
14961     break;
14962   case ISD::INTRINSIC_VOID:
14963     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14964     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14965     if (Subtarget.needsSwapsForVSXMemOps()) {
14966       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14967       default:
14968         break;
14969       case Intrinsic::ppc_vsx_stxvw4x:
14970       case Intrinsic::ppc_vsx_stxvd2x:
14971         return expandVSXStoreForLE(N, DCI);
14972       }
14973     }
14974     break;
14975   case ISD::BSWAP:
14976     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14977     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14978         N->getOperand(0).hasOneUse() &&
14979         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14980          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14981           N->getValueType(0) == MVT::i64))) {
14982       SDValue Load = N->getOperand(0);
14983       LoadSDNode *LD = cast<LoadSDNode>(Load);
14984       // Create the byte-swapping load.
14985       SDValue Ops[] = {
14986         LD->getChain(),    // Chain
14987         LD->getBasePtr(),  // Ptr
14988         DAG.getValueType(N->getValueType(0)) // VT
14989       };
14990       SDValue BSLoad =
14991         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14992                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14993                                               MVT::i64 : MVT::i32, MVT::Other),
14994                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14995 
14996       // If this is an i16 load, insert the truncate.
14997       SDValue ResVal = BSLoad;
14998       if (N->getValueType(0) == MVT::i16)
14999         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15000 
15001       // First, combine the bswap away.  This makes the value produced by the
15002       // load dead.
15003       DCI.CombineTo(N, ResVal);
15004 
15005       // Next, combine the load away, we give it a bogus result value but a real
15006       // chain result.  The result value is dead because the bswap is dead.
15007       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15008 
15009       // Return N so it doesn't get rechecked!
15010       return SDValue(N, 0);
15011     }
15012     break;
15013   case PPCISD::VCMP:
15014     // If a VCMPo node already exists with exactly the same operands as this
15015     // node, use its result instead of this node (VCMPo computes both a CR6 and
15016     // a normal output).
15017     //
15018     if (!N->getOperand(0).hasOneUse() &&
15019         !N->getOperand(1).hasOneUse() &&
15020         !N->getOperand(2).hasOneUse()) {
15021 
15022       // Scan all of the users of the LHS, looking for VCMPo's that match.
15023       SDNode *VCMPoNode = nullptr;
15024 
15025       SDNode *LHSN = N->getOperand(0).getNode();
15026       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15027            UI != E; ++UI)
15028         if (UI->getOpcode() == PPCISD::VCMPo &&
15029             UI->getOperand(1) == N->getOperand(1) &&
15030             UI->getOperand(2) == N->getOperand(2) &&
15031             UI->getOperand(0) == N->getOperand(0)) {
15032           VCMPoNode = *UI;
15033           break;
15034         }
15035 
15036       // If there is no VCMPo node, or if the flag value has a single use, don't
15037       // transform this.
15038       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
15039         break;
15040 
15041       // Look at the (necessarily single) use of the flag value.  If it has a
15042       // chain, this transformation is more complex.  Note that multiple things
15043       // could use the value result, which we should ignore.
15044       SDNode *FlagUser = nullptr;
15045       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
15046            FlagUser == nullptr; ++UI) {
15047         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
15048         SDNode *User = *UI;
15049         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15050           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
15051             FlagUser = User;
15052             break;
15053           }
15054         }
15055       }
15056 
15057       // If the user is a MFOCRF instruction, we know this is safe.
15058       // Otherwise we give up for right now.
15059       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15060         return SDValue(VCMPoNode, 0);
15061     }
15062     break;
15063   case ISD::BRCOND: {
15064     SDValue Cond = N->getOperand(1);
15065     SDValue Target = N->getOperand(2);
15066 
15067     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15068         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15069           Intrinsic::loop_decrement) {
15070 
15071       // We now need to make the intrinsic dead (it cannot be instruction
15072       // selected).
15073       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15074       assert(Cond.getNode()->hasOneUse() &&
15075              "Counter decrement has more than one use");
15076 
15077       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15078                          N->getOperand(0), Target);
15079     }
15080   }
15081   break;
15082   case ISD::BR_CC: {
15083     // If this is a branch on an altivec predicate comparison, lower this so
15084     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15085     // lowering is done pre-legalize, because the legalizer lowers the predicate
15086     // compare down to code that is difficult to reassemble.
15087     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15088     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15089 
15090     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15091     // value. If so, pass-through the AND to get to the intrinsic.
15092     if (LHS.getOpcode() == ISD::AND &&
15093         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15094         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15095           Intrinsic::loop_decrement &&
15096         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15097         !isNullConstant(LHS.getOperand(1)))
15098       LHS = LHS.getOperand(0);
15099 
15100     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15101         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15102           Intrinsic::loop_decrement &&
15103         isa<ConstantSDNode>(RHS)) {
15104       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15105              "Counter decrement comparison is not EQ or NE");
15106 
15107       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15108       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15109                     (CC == ISD::SETNE && !Val);
15110 
15111       // We now need to make the intrinsic dead (it cannot be instruction
15112       // selected).
15113       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15114       assert(LHS.getNode()->hasOneUse() &&
15115              "Counter decrement has more than one use");
15116 
15117       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15118                          N->getOperand(0), N->getOperand(4));
15119     }
15120 
15121     int CompareOpc;
15122     bool isDot;
15123 
15124     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15125         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15126         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15127       assert(isDot && "Can't compare against a vector result!");
15128 
15129       // If this is a comparison against something other than 0/1, then we know
15130       // that the condition is never/always true.
15131       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15132       if (Val != 0 && Val != 1) {
15133         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15134           return N->getOperand(0);
15135         // Always !=, turn it into an unconditional branch.
15136         return DAG.getNode(ISD::BR, dl, MVT::Other,
15137                            N->getOperand(0), N->getOperand(4));
15138       }
15139 
15140       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15141 
15142       // Create the PPCISD altivec 'dot' comparison node.
15143       SDValue Ops[] = {
15144         LHS.getOperand(2),  // LHS of compare
15145         LHS.getOperand(3),  // RHS of compare
15146         DAG.getConstant(CompareOpc, dl, MVT::i32)
15147       };
15148       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15149       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
15150 
15151       // Unpack the result based on how the target uses it.
15152       PPC::Predicate CompOpc;
15153       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15154       default:  // Can't happen, don't crash on invalid number though.
15155       case 0:   // Branch on the value of the EQ bit of CR6.
15156         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15157         break;
15158       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15159         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15160         break;
15161       case 2:   // Branch on the value of the LT bit of CR6.
15162         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15163         break;
15164       case 3:   // Branch on the inverted value of the LT bit of CR6.
15165         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15166         break;
15167       }
15168 
15169       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15170                          DAG.getConstant(CompOpc, dl, MVT::i32),
15171                          DAG.getRegister(PPC::CR6, MVT::i32),
15172                          N->getOperand(4), CompNode.getValue(1));
15173     }
15174     break;
15175   }
15176   case ISD::BUILD_VECTOR:
15177     return DAGCombineBuildVector(N, DCI);
15178   case ISD::ABS:
15179     return combineABS(N, DCI);
15180   case ISD::VSELECT:
15181     return combineVSelect(N, DCI);
15182   }
15183 
15184   return SDValue();
15185 }
15186 
15187 SDValue
15188 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15189                                  SelectionDAG &DAG,
15190                                  SmallVectorImpl<SDNode *> &Created) const {
15191   // fold (sdiv X, pow2)
15192   EVT VT = N->getValueType(0);
15193   if (VT == MVT::i64 && !Subtarget.isPPC64())
15194     return SDValue();
15195   if ((VT != MVT::i32 && VT != MVT::i64) ||
15196       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15197     return SDValue();
15198 
15199   SDLoc DL(N);
15200   SDValue N0 = N->getOperand(0);
15201 
15202   bool IsNegPow2 = (-Divisor).isPowerOf2();
15203   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15204   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15205 
15206   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15207   Created.push_back(Op.getNode());
15208 
15209   if (IsNegPow2) {
15210     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15211     Created.push_back(Op.getNode());
15212   }
15213 
15214   return Op;
15215 }
15216 
15217 //===----------------------------------------------------------------------===//
15218 // Inline Assembly Support
15219 //===----------------------------------------------------------------------===//
15220 
15221 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15222                                                       KnownBits &Known,
15223                                                       const APInt &DemandedElts,
15224                                                       const SelectionDAG &DAG,
15225                                                       unsigned Depth) const {
15226   Known.resetAll();
15227   switch (Op.getOpcode()) {
15228   default: break;
15229   case PPCISD::LBRX: {
15230     // lhbrx is known to have the top bits cleared out.
15231     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15232       Known.Zero = 0xFFFF0000;
15233     break;
15234   }
15235   case ISD::INTRINSIC_WO_CHAIN: {
15236     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15237     default: break;
15238     case Intrinsic::ppc_altivec_vcmpbfp_p:
15239     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15240     case Intrinsic::ppc_altivec_vcmpequb_p:
15241     case Intrinsic::ppc_altivec_vcmpequh_p:
15242     case Intrinsic::ppc_altivec_vcmpequw_p:
15243     case Intrinsic::ppc_altivec_vcmpequd_p:
15244     case Intrinsic::ppc_altivec_vcmpgefp_p:
15245     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15246     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15247     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15248     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15249     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15250     case Intrinsic::ppc_altivec_vcmpgtub_p:
15251     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15252     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15253     case Intrinsic::ppc_altivec_vcmpgtud_p:
15254       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15255       break;
15256     }
15257   }
15258   }
15259 }
15260 
15261 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15262   switch (Subtarget.getCPUDirective()) {
15263   default: break;
15264   case PPC::DIR_970:
15265   case PPC::DIR_PWR4:
15266   case PPC::DIR_PWR5:
15267   case PPC::DIR_PWR5X:
15268   case PPC::DIR_PWR6:
15269   case PPC::DIR_PWR6X:
15270   case PPC::DIR_PWR7:
15271   case PPC::DIR_PWR8:
15272   case PPC::DIR_PWR9:
15273   case PPC::DIR_PWR10:
15274   case PPC::DIR_PWR_FUTURE: {
15275     if (!ML)
15276       break;
15277 
15278     if (!DisableInnermostLoopAlign32) {
15279       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15280       // so that we can decrease cache misses and branch-prediction misses.
15281       // Actual alignment of the loop will depend on the hotness check and other
15282       // logic in alignBlocks.
15283       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15284         return Align(32);
15285     }
15286 
15287     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15288 
15289     // For small loops (between 5 and 8 instructions), align to a 32-byte
15290     // boundary so that the entire loop fits in one instruction-cache line.
15291     uint64_t LoopSize = 0;
15292     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15293       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15294         LoopSize += TII->getInstSizeInBytes(*J);
15295         if (LoopSize > 32)
15296           break;
15297       }
15298 
15299     if (LoopSize > 16 && LoopSize <= 32)
15300       return Align(32);
15301 
15302     break;
15303   }
15304   }
15305 
15306   return TargetLowering::getPrefLoopAlignment(ML);
15307 }
15308 
15309 /// getConstraintType - Given a constraint, return the type of
15310 /// constraint it is for this target.
15311 PPCTargetLowering::ConstraintType
15312 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15313   if (Constraint.size() == 1) {
15314     switch (Constraint[0]) {
15315     default: break;
15316     case 'b':
15317     case 'r':
15318     case 'f':
15319     case 'd':
15320     case 'v':
15321     case 'y':
15322       return C_RegisterClass;
15323     case 'Z':
15324       // FIXME: While Z does indicate a memory constraint, it specifically
15325       // indicates an r+r address (used in conjunction with the 'y' modifier
15326       // in the replacement string). Currently, we're forcing the base
15327       // register to be r0 in the asm printer (which is interpreted as zero)
15328       // and forming the complete address in the second register. This is
15329       // suboptimal.
15330       return C_Memory;
15331     }
15332   } else if (Constraint == "wc") { // individual CR bits.
15333     return C_RegisterClass;
15334   } else if (Constraint == "wa" || Constraint == "wd" ||
15335              Constraint == "wf" || Constraint == "ws" ||
15336              Constraint == "wi" || Constraint == "ww") {
15337     return C_RegisterClass; // VSX registers.
15338   }
15339   return TargetLowering::getConstraintType(Constraint);
15340 }
15341 
15342 /// Examine constraint type and operand type and determine a weight value.
15343 /// This object must already have been set up with the operand type
15344 /// and the current alternative constraint selected.
15345 TargetLowering::ConstraintWeight
15346 PPCTargetLowering::getSingleConstraintMatchWeight(
15347     AsmOperandInfo &info, const char *constraint) const {
15348   ConstraintWeight weight = CW_Invalid;
15349   Value *CallOperandVal = info.CallOperandVal;
15350     // If we don't have a value, we can't do a match,
15351     // but allow it at the lowest weight.
15352   if (!CallOperandVal)
15353     return CW_Default;
15354   Type *type = CallOperandVal->getType();
15355 
15356   // Look at the constraint type.
15357   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15358     return CW_Register; // an individual CR bit.
15359   else if ((StringRef(constraint) == "wa" ||
15360             StringRef(constraint) == "wd" ||
15361             StringRef(constraint) == "wf") &&
15362            type->isVectorTy())
15363     return CW_Register;
15364   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15365     return CW_Register; // just hold 64-bit integers data.
15366   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15367     return CW_Register;
15368   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15369     return CW_Register;
15370 
15371   switch (*constraint) {
15372   default:
15373     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15374     break;
15375   case 'b':
15376     if (type->isIntegerTy())
15377       weight = CW_Register;
15378     break;
15379   case 'f':
15380     if (type->isFloatTy())
15381       weight = CW_Register;
15382     break;
15383   case 'd':
15384     if (type->isDoubleTy())
15385       weight = CW_Register;
15386     break;
15387   case 'v':
15388     if (type->isVectorTy())
15389       weight = CW_Register;
15390     break;
15391   case 'y':
15392     weight = CW_Register;
15393     break;
15394   case 'Z':
15395     weight = CW_Memory;
15396     break;
15397   }
15398   return weight;
15399 }
15400 
15401 std::pair<unsigned, const TargetRegisterClass *>
15402 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15403                                                 StringRef Constraint,
15404                                                 MVT VT) const {
15405   if (Constraint.size() == 1) {
15406     // GCC RS6000 Constraint Letters
15407     switch (Constraint[0]) {
15408     case 'b':   // R1-R31
15409       if (VT == MVT::i64 && Subtarget.isPPC64())
15410         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15411       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15412     case 'r':   // R0-R31
15413       if (VT == MVT::i64 && Subtarget.isPPC64())
15414         return std::make_pair(0U, &PPC::G8RCRegClass);
15415       return std::make_pair(0U, &PPC::GPRCRegClass);
15416     // 'd' and 'f' constraints are both defined to be "the floating point
15417     // registers", where one is for 32-bit and the other for 64-bit. We don't
15418     // really care overly much here so just give them all the same reg classes.
15419     case 'd':
15420     case 'f':
15421       if (Subtarget.hasSPE()) {
15422         if (VT == MVT::f32 || VT == MVT::i32)
15423           return std::make_pair(0U, &PPC::GPRCRegClass);
15424         if (VT == MVT::f64 || VT == MVT::i64)
15425           return std::make_pair(0U, &PPC::SPERCRegClass);
15426       } else {
15427         if (VT == MVT::f32 || VT == MVT::i32)
15428           return std::make_pair(0U, &PPC::F4RCRegClass);
15429         if (VT == MVT::f64 || VT == MVT::i64)
15430           return std::make_pair(0U, &PPC::F8RCRegClass);
15431         if (VT == MVT::v4f64 && Subtarget.hasQPX())
15432           return std::make_pair(0U, &PPC::QFRCRegClass);
15433         if (VT == MVT::v4f32 && Subtarget.hasQPX())
15434           return std::make_pair(0U, &PPC::QSRCRegClass);
15435       }
15436       break;
15437     case 'v':
15438       if (VT == MVT::v4f64 && Subtarget.hasQPX())
15439         return std::make_pair(0U, &PPC::QFRCRegClass);
15440       if (VT == MVT::v4f32 && Subtarget.hasQPX())
15441         return std::make_pair(0U, &PPC::QSRCRegClass);
15442       if (Subtarget.hasAltivec())
15443         return std::make_pair(0U, &PPC::VRRCRegClass);
15444       break;
15445     case 'y':   // crrc
15446       return std::make_pair(0U, &PPC::CRRCRegClass);
15447     }
15448   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15449     // An individual CR bit.
15450     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15451   } else if ((Constraint == "wa" || Constraint == "wd" ||
15452              Constraint == "wf" || Constraint == "wi") &&
15453              Subtarget.hasVSX()) {
15454     return std::make_pair(0U, &PPC::VSRCRegClass);
15455   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15456     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15457       return std::make_pair(0U, &PPC::VSSRCRegClass);
15458     else
15459       return std::make_pair(0U, &PPC::VSFRCRegClass);
15460   }
15461 
15462   // If we name a VSX register, we can't defer to the base class because it
15463   // will not recognize the correct register (their names will be VSL{0-31}
15464   // and V{0-31} so they won't match). So we match them here.
15465   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15466     int VSNum = atoi(Constraint.data() + 3);
15467     assert(VSNum >= 0 && VSNum <= 63 &&
15468            "Attempted to access a vsr out of range");
15469     if (VSNum < 32)
15470       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15471     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15472   }
15473   std::pair<unsigned, const TargetRegisterClass *> R =
15474       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15475 
15476   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15477   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15478   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15479   // register.
15480   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15481   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15482   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15483       PPC::GPRCRegClass.contains(R.first))
15484     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15485                             PPC::sub_32, &PPC::G8RCRegClass),
15486                           &PPC::G8RCRegClass);
15487 
15488   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15489   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15490     R.first = PPC::CR0;
15491     R.second = &PPC::CRRCRegClass;
15492   }
15493 
15494   return R;
15495 }
15496 
15497 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15498 /// vector.  If it is invalid, don't add anything to Ops.
15499 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15500                                                      std::string &Constraint,
15501                                                      std::vector<SDValue>&Ops,
15502                                                      SelectionDAG &DAG) const {
15503   SDValue Result;
15504 
15505   // Only support length 1 constraints.
15506   if (Constraint.length() > 1) return;
15507 
15508   char Letter = Constraint[0];
15509   switch (Letter) {
15510   default: break;
15511   case 'I':
15512   case 'J':
15513   case 'K':
15514   case 'L':
15515   case 'M':
15516   case 'N':
15517   case 'O':
15518   case 'P': {
15519     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15520     if (!CST) return; // Must be an immediate to match.
15521     SDLoc dl(Op);
15522     int64_t Value = CST->getSExtValue();
15523     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15524                          // numbers are printed as such.
15525     switch (Letter) {
15526     default: llvm_unreachable("Unknown constraint letter!");
15527     case 'I':  // "I" is a signed 16-bit constant.
15528       if (isInt<16>(Value))
15529         Result = DAG.getTargetConstant(Value, dl, TCVT);
15530       break;
15531     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15532       if (isShiftedUInt<16, 16>(Value))
15533         Result = DAG.getTargetConstant(Value, dl, TCVT);
15534       break;
15535     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15536       if (isShiftedInt<16, 16>(Value))
15537         Result = DAG.getTargetConstant(Value, dl, TCVT);
15538       break;
15539     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15540       if (isUInt<16>(Value))
15541         Result = DAG.getTargetConstant(Value, dl, TCVT);
15542       break;
15543     case 'M':  // "M" is a constant that is greater than 31.
15544       if (Value > 31)
15545         Result = DAG.getTargetConstant(Value, dl, TCVT);
15546       break;
15547     case 'N':  // "N" is a positive constant that is an exact power of two.
15548       if (Value > 0 && isPowerOf2_64(Value))
15549         Result = DAG.getTargetConstant(Value, dl, TCVT);
15550       break;
15551     case 'O':  // "O" is the constant zero.
15552       if (Value == 0)
15553         Result = DAG.getTargetConstant(Value, dl, TCVT);
15554       break;
15555     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15556       if (isInt<16>(-Value))
15557         Result = DAG.getTargetConstant(Value, dl, TCVT);
15558       break;
15559     }
15560     break;
15561   }
15562   }
15563 
15564   if (Result.getNode()) {
15565     Ops.push_back(Result);
15566     return;
15567   }
15568 
15569   // Handle standard constraint letters.
15570   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15571 }
15572 
15573 // isLegalAddressingMode - Return true if the addressing mode represented
15574 // by AM is legal for this target, for a load/store of the specified type.
15575 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15576                                               const AddrMode &AM, Type *Ty,
15577                                               unsigned AS, Instruction *I) const {
15578   // PPC does not allow r+i addressing modes for vectors!
15579   if (Ty->isVectorTy() && AM.BaseOffs != 0)
15580     return false;
15581 
15582   // PPC allows a sign-extended 16-bit immediate field.
15583   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15584     return false;
15585 
15586   // No global is ever allowed as a base.
15587   if (AM.BaseGV)
15588     return false;
15589 
15590   // PPC only support r+r,
15591   switch (AM.Scale) {
15592   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15593     break;
15594   case 1:
15595     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15596       return false;
15597     // Otherwise we have r+r or r+i.
15598     break;
15599   case 2:
15600     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15601       return false;
15602     // Allow 2*r as r+r.
15603     break;
15604   default:
15605     // No other scales are supported.
15606     return false;
15607   }
15608 
15609   return true;
15610 }
15611 
15612 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15613                                            SelectionDAG &DAG) const {
15614   MachineFunction &MF = DAG.getMachineFunction();
15615   MachineFrameInfo &MFI = MF.getFrameInfo();
15616   MFI.setReturnAddressIsTaken(true);
15617 
15618   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15619     return SDValue();
15620 
15621   SDLoc dl(Op);
15622   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15623 
15624   // Make sure the function does not optimize away the store of the RA to
15625   // the stack.
15626   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15627   FuncInfo->setLRStoreRequired();
15628   bool isPPC64 = Subtarget.isPPC64();
15629   auto PtrVT = getPointerTy(MF.getDataLayout());
15630 
15631   if (Depth > 0) {
15632     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15633     SDValue Offset =
15634         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15635                         isPPC64 ? MVT::i64 : MVT::i32);
15636     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15637                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15638                        MachinePointerInfo());
15639   }
15640 
15641   // Just load the return address off the stack.
15642   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15643   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15644                      MachinePointerInfo());
15645 }
15646 
15647 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15648                                           SelectionDAG &DAG) const {
15649   SDLoc dl(Op);
15650   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15651 
15652   MachineFunction &MF = DAG.getMachineFunction();
15653   MachineFrameInfo &MFI = MF.getFrameInfo();
15654   MFI.setFrameAddressIsTaken(true);
15655 
15656   EVT PtrVT = getPointerTy(MF.getDataLayout());
15657   bool isPPC64 = PtrVT == MVT::i64;
15658 
15659   // Naked functions never have a frame pointer, and so we use r1. For all
15660   // other functions, this decision must be delayed until during PEI.
15661   unsigned FrameReg;
15662   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15663     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15664   else
15665     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15666 
15667   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15668                                          PtrVT);
15669   while (Depth--)
15670     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15671                             FrameAddr, MachinePointerInfo());
15672   return FrameAddr;
15673 }
15674 
15675 // FIXME? Maybe this could be a TableGen attribute on some registers and
15676 // this table could be generated automatically from RegInfo.
15677 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15678                                               const MachineFunction &MF) const {
15679   bool isPPC64 = Subtarget.isPPC64();
15680 
15681   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15682   if (!is64Bit && VT != LLT::scalar(32))
15683     report_fatal_error("Invalid register global variable type");
15684 
15685   Register Reg = StringSwitch<Register>(RegName)
15686                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15687                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15688                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15689                      .Default(Register());
15690 
15691   if (Reg)
15692     return Reg;
15693   report_fatal_error("Invalid register name global variable");
15694 }
15695 
15696 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15697   // 32-bit SVR4 ABI access everything as got-indirect.
15698   if (Subtarget.is32BitELFABI())
15699     return true;
15700 
15701   // AIX accesses everything indirectly through the TOC, which is similar to
15702   // the GOT.
15703   if (Subtarget.isAIXABI())
15704     return true;
15705 
15706   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15707   // If it is small or large code model, module locals are accessed
15708   // indirectly by loading their address from .toc/.got.
15709   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15710     return true;
15711 
15712   // JumpTable and BlockAddress are accessed as got-indirect.
15713   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15714     return true;
15715 
15716   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15717     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15718 
15719   return false;
15720 }
15721 
15722 bool
15723 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15724   // The PowerPC target isn't yet aware of offsets.
15725   return false;
15726 }
15727 
15728 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15729                                            const CallInst &I,
15730                                            MachineFunction &MF,
15731                                            unsigned Intrinsic) const {
15732   switch (Intrinsic) {
15733   case Intrinsic::ppc_qpx_qvlfd:
15734   case Intrinsic::ppc_qpx_qvlfs:
15735   case Intrinsic::ppc_qpx_qvlfcd:
15736   case Intrinsic::ppc_qpx_qvlfcs:
15737   case Intrinsic::ppc_qpx_qvlfiwa:
15738   case Intrinsic::ppc_qpx_qvlfiwz:
15739   case Intrinsic::ppc_altivec_lvx:
15740   case Intrinsic::ppc_altivec_lvxl:
15741   case Intrinsic::ppc_altivec_lvebx:
15742   case Intrinsic::ppc_altivec_lvehx:
15743   case Intrinsic::ppc_altivec_lvewx:
15744   case Intrinsic::ppc_vsx_lxvd2x:
15745   case Intrinsic::ppc_vsx_lxvw4x: {
15746     EVT VT;
15747     switch (Intrinsic) {
15748     case Intrinsic::ppc_altivec_lvebx:
15749       VT = MVT::i8;
15750       break;
15751     case Intrinsic::ppc_altivec_lvehx:
15752       VT = MVT::i16;
15753       break;
15754     case Intrinsic::ppc_altivec_lvewx:
15755       VT = MVT::i32;
15756       break;
15757     case Intrinsic::ppc_vsx_lxvd2x:
15758       VT = MVT::v2f64;
15759       break;
15760     case Intrinsic::ppc_qpx_qvlfd:
15761       VT = MVT::v4f64;
15762       break;
15763     case Intrinsic::ppc_qpx_qvlfs:
15764       VT = MVT::v4f32;
15765       break;
15766     case Intrinsic::ppc_qpx_qvlfcd:
15767       VT = MVT::v2f64;
15768       break;
15769     case Intrinsic::ppc_qpx_qvlfcs:
15770       VT = MVT::v2f32;
15771       break;
15772     default:
15773       VT = MVT::v4i32;
15774       break;
15775     }
15776 
15777     Info.opc = ISD::INTRINSIC_W_CHAIN;
15778     Info.memVT = VT;
15779     Info.ptrVal = I.getArgOperand(0);
15780     Info.offset = -VT.getStoreSize()+1;
15781     Info.size = 2*VT.getStoreSize()-1;
15782     Info.align = Align(1);
15783     Info.flags = MachineMemOperand::MOLoad;
15784     return true;
15785   }
15786   case Intrinsic::ppc_qpx_qvlfda:
15787   case Intrinsic::ppc_qpx_qvlfsa:
15788   case Intrinsic::ppc_qpx_qvlfcda:
15789   case Intrinsic::ppc_qpx_qvlfcsa:
15790   case Intrinsic::ppc_qpx_qvlfiwaa:
15791   case Intrinsic::ppc_qpx_qvlfiwza: {
15792     EVT VT;
15793     switch (Intrinsic) {
15794     case Intrinsic::ppc_qpx_qvlfda:
15795       VT = MVT::v4f64;
15796       break;
15797     case Intrinsic::ppc_qpx_qvlfsa:
15798       VT = MVT::v4f32;
15799       break;
15800     case Intrinsic::ppc_qpx_qvlfcda:
15801       VT = MVT::v2f64;
15802       break;
15803     case Intrinsic::ppc_qpx_qvlfcsa:
15804       VT = MVT::v2f32;
15805       break;
15806     default:
15807       VT = MVT::v4i32;
15808       break;
15809     }
15810 
15811     Info.opc = ISD::INTRINSIC_W_CHAIN;
15812     Info.memVT = VT;
15813     Info.ptrVal = I.getArgOperand(0);
15814     Info.offset = 0;
15815     Info.size = VT.getStoreSize();
15816     Info.align = Align(1);
15817     Info.flags = MachineMemOperand::MOLoad;
15818     return true;
15819   }
15820   case Intrinsic::ppc_qpx_qvstfd:
15821   case Intrinsic::ppc_qpx_qvstfs:
15822   case Intrinsic::ppc_qpx_qvstfcd:
15823   case Intrinsic::ppc_qpx_qvstfcs:
15824   case Intrinsic::ppc_qpx_qvstfiw:
15825   case Intrinsic::ppc_altivec_stvx:
15826   case Intrinsic::ppc_altivec_stvxl:
15827   case Intrinsic::ppc_altivec_stvebx:
15828   case Intrinsic::ppc_altivec_stvehx:
15829   case Intrinsic::ppc_altivec_stvewx:
15830   case Intrinsic::ppc_vsx_stxvd2x:
15831   case Intrinsic::ppc_vsx_stxvw4x: {
15832     EVT VT;
15833     switch (Intrinsic) {
15834     case Intrinsic::ppc_altivec_stvebx:
15835       VT = MVT::i8;
15836       break;
15837     case Intrinsic::ppc_altivec_stvehx:
15838       VT = MVT::i16;
15839       break;
15840     case Intrinsic::ppc_altivec_stvewx:
15841       VT = MVT::i32;
15842       break;
15843     case Intrinsic::ppc_vsx_stxvd2x:
15844       VT = MVT::v2f64;
15845       break;
15846     case Intrinsic::ppc_qpx_qvstfd:
15847       VT = MVT::v4f64;
15848       break;
15849     case Intrinsic::ppc_qpx_qvstfs:
15850       VT = MVT::v4f32;
15851       break;
15852     case Intrinsic::ppc_qpx_qvstfcd:
15853       VT = MVT::v2f64;
15854       break;
15855     case Intrinsic::ppc_qpx_qvstfcs:
15856       VT = MVT::v2f32;
15857       break;
15858     default:
15859       VT = MVT::v4i32;
15860       break;
15861     }
15862 
15863     Info.opc = ISD::INTRINSIC_VOID;
15864     Info.memVT = VT;
15865     Info.ptrVal = I.getArgOperand(1);
15866     Info.offset = -VT.getStoreSize()+1;
15867     Info.size = 2*VT.getStoreSize()-1;
15868     Info.align = Align(1);
15869     Info.flags = MachineMemOperand::MOStore;
15870     return true;
15871   }
15872   case Intrinsic::ppc_qpx_qvstfda:
15873   case Intrinsic::ppc_qpx_qvstfsa:
15874   case Intrinsic::ppc_qpx_qvstfcda:
15875   case Intrinsic::ppc_qpx_qvstfcsa:
15876   case Intrinsic::ppc_qpx_qvstfiwa: {
15877     EVT VT;
15878     switch (Intrinsic) {
15879     case Intrinsic::ppc_qpx_qvstfda:
15880       VT = MVT::v4f64;
15881       break;
15882     case Intrinsic::ppc_qpx_qvstfsa:
15883       VT = MVT::v4f32;
15884       break;
15885     case Intrinsic::ppc_qpx_qvstfcda:
15886       VT = MVT::v2f64;
15887       break;
15888     case Intrinsic::ppc_qpx_qvstfcsa:
15889       VT = MVT::v2f32;
15890       break;
15891     default:
15892       VT = MVT::v4i32;
15893       break;
15894     }
15895 
15896     Info.opc = ISD::INTRINSIC_VOID;
15897     Info.memVT = VT;
15898     Info.ptrVal = I.getArgOperand(1);
15899     Info.offset = 0;
15900     Info.size = VT.getStoreSize();
15901     Info.align = Align(1);
15902     Info.flags = MachineMemOperand::MOStore;
15903     return true;
15904   }
15905   default:
15906     break;
15907   }
15908 
15909   return false;
15910 }
15911 
15912 /// It returns EVT::Other if the type should be determined using generic
15913 /// target-independent logic.
15914 EVT PPCTargetLowering::getOptimalMemOpType(
15915     const MemOp &Op, const AttributeList &FuncAttributes) const {
15916   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15917     // When expanding a memset, require at least two QPX instructions to cover
15918     // the cost of loading the value to be stored from the constant pool.
15919     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15920         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15921         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15922       return MVT::v4f64;
15923     }
15924 
15925     // We should use Altivec/VSX loads and stores when available. For unaligned
15926     // addresses, unaligned VSX loads are only fast starting with the P8.
15927     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15928         (Op.isAligned(Align(16)) ||
15929          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15930       return MVT::v4i32;
15931   }
15932 
15933   if (Subtarget.isPPC64()) {
15934     return MVT::i64;
15935   }
15936 
15937   return MVT::i32;
15938 }
15939 
15940 /// Returns true if it is beneficial to convert a load of a constant
15941 /// to just the constant itself.
15942 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15943                                                           Type *Ty) const {
15944   assert(Ty->isIntegerTy());
15945 
15946   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15947   return !(BitSize == 0 || BitSize > 64);
15948 }
15949 
15950 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15951   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15952     return false;
15953   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15954   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15955   return NumBits1 == 64 && NumBits2 == 32;
15956 }
15957 
15958 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15959   if (!VT1.isInteger() || !VT2.isInteger())
15960     return false;
15961   unsigned NumBits1 = VT1.getSizeInBits();
15962   unsigned NumBits2 = VT2.getSizeInBits();
15963   return NumBits1 == 64 && NumBits2 == 32;
15964 }
15965 
15966 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15967   // Generally speaking, zexts are not free, but they are free when they can be
15968   // folded with other operations.
15969   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15970     EVT MemVT = LD->getMemoryVT();
15971     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15972          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15973         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15974          LD->getExtensionType() == ISD::ZEXTLOAD))
15975       return true;
15976   }
15977 
15978   // FIXME: Add other cases...
15979   //  - 32-bit shifts with a zext to i64
15980   //  - zext after ctlz, bswap, etc.
15981   //  - zext after and by a constant mask
15982 
15983   return TargetLowering::isZExtFree(Val, VT2);
15984 }
15985 
15986 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15987   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15988          "invalid fpext types");
15989   // Extending to float128 is not free.
15990   if (DestVT == MVT::f128)
15991     return false;
15992   return true;
15993 }
15994 
15995 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15996   return isInt<16>(Imm) || isUInt<16>(Imm);
15997 }
15998 
15999 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16000   return isInt<16>(Imm) || isUInt<16>(Imm);
16001 }
16002 
16003 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
16004                                                        unsigned,
16005                                                        unsigned,
16006                                                        MachineMemOperand::Flags,
16007                                                        bool *Fast) const {
16008   if (DisablePPCUnaligned)
16009     return false;
16010 
16011   // PowerPC supports unaligned memory access for simple non-vector types.
16012   // Although accessing unaligned addresses is not as efficient as accessing
16013   // aligned addresses, it is generally more efficient than manual expansion,
16014   // and generally only traps for software emulation when crossing page
16015   // boundaries.
16016 
16017   if (!VT.isSimple())
16018     return false;
16019 
16020   if (VT.isFloatingPoint() && !VT.isVector() &&
16021       !Subtarget.allowsUnalignedFPAccess())
16022     return false;
16023 
16024   if (VT.getSimpleVT().isVector()) {
16025     if (Subtarget.hasVSX()) {
16026       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16027           VT != MVT::v4f32 && VT != MVT::v4i32)
16028         return false;
16029     } else {
16030       return false;
16031     }
16032   }
16033 
16034   if (VT == MVT::ppcf128)
16035     return false;
16036 
16037   if (Fast)
16038     *Fast = true;
16039 
16040   return true;
16041 }
16042 
16043 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16044                                                    EVT VT) const {
16045   return isFMAFasterThanFMulAndFAdd(
16046       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16047 }
16048 
16049 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16050                                                    Type *Ty) const {
16051   switch (Ty->getScalarType()->getTypeID()) {
16052   case Type::FloatTyID:
16053   case Type::DoubleTyID:
16054     return true;
16055   case Type::FP128TyID:
16056     return EnableQuadPrecision && Subtarget.hasP9Vector();
16057   default:
16058     return false;
16059   }
16060 }
16061 
16062 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
16063 // FIXME: add more patterns which are profitable to hoist.
16064 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16065   if (I->getOpcode() != Instruction::FMul)
16066     return true;
16067 
16068   if (!I->hasOneUse())
16069     return true;
16070 
16071   Instruction *User = I->user_back();
16072   assert(User && "A single use instruction with no uses.");
16073 
16074   if (User->getOpcode() != Instruction::FSub &&
16075       User->getOpcode() != Instruction::FAdd)
16076     return true;
16077 
16078   const TargetOptions &Options = getTargetMachine().Options;
16079   const Function *F = I->getFunction();
16080   const DataLayout &DL = F->getParent()->getDataLayout();
16081   Type *Ty = User->getOperand(0)->getType();
16082 
16083   return !(
16084       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16085       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16086       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16087 }
16088 
16089 const MCPhysReg *
16090 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16091   // LR is a callee-save register, but we must treat it as clobbered by any call
16092   // site. Hence we include LR in the scratch registers, which are in turn added
16093   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16094   // to CTR, which is used by any indirect call.
16095   static const MCPhysReg ScratchRegs[] = {
16096     PPC::X12, PPC::LR8, PPC::CTR8, 0
16097   };
16098 
16099   return ScratchRegs;
16100 }
16101 
16102 Register PPCTargetLowering::getExceptionPointerRegister(
16103     const Constant *PersonalityFn) const {
16104   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16105 }
16106 
16107 Register PPCTargetLowering::getExceptionSelectorRegister(
16108     const Constant *PersonalityFn) const {
16109   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16110 }
16111 
16112 bool
16113 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16114                      EVT VT , unsigned DefinedValues) const {
16115   if (VT == MVT::v2i64)
16116     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16117 
16118   if (Subtarget.hasVSX() || Subtarget.hasQPX())
16119     return true;
16120 
16121   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16122 }
16123 
16124 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16125   if (DisableILPPref || Subtarget.enableMachineScheduler())
16126     return TargetLowering::getSchedulingPreference(N);
16127 
16128   return Sched::ILP;
16129 }
16130 
16131 // Create a fast isel object.
16132 FastISel *
16133 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16134                                   const TargetLibraryInfo *LibInfo) const {
16135   return PPC::createFastISel(FuncInfo, LibInfo);
16136 }
16137 
16138 // 'Inverted' means the FMA opcode after negating one multiplicand.
16139 // For example, (fma -a b c) = (fnmsub a b c)
16140 static unsigned invertFMAOpcode(unsigned Opc) {
16141   switch (Opc) {
16142   default:
16143     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16144   case ISD::FMA:
16145     return PPCISD::FNMSUB;
16146   case PPCISD::FNMSUB:
16147     return ISD::FMA;
16148   }
16149 }
16150 
16151 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16152                                                 bool LegalOps, bool OptForSize,
16153                                                 NegatibleCost &Cost,
16154                                                 unsigned Depth) const {
16155   if (Depth > SelectionDAG::MaxRecursionDepth)
16156     return SDValue();
16157 
16158   unsigned Opc = Op.getOpcode();
16159   EVT VT = Op.getValueType();
16160   SDNodeFlags Flags = Op.getNode()->getFlags();
16161 
16162   switch (Opc) {
16163   case PPCISD::FNMSUB:
16164     // TODO: QPX subtarget is deprecated. No transformation here.
16165     if (!Op.hasOneUse() || !isTypeLegal(VT) || Subtarget.hasQPX())
16166       break;
16167 
16168     const TargetOptions &Options = getTargetMachine().Options;
16169     SDValue N0 = Op.getOperand(0);
16170     SDValue N1 = Op.getOperand(1);
16171     SDValue N2 = Op.getOperand(2);
16172     SDLoc Loc(Op);
16173 
16174     NegatibleCost N2Cost = NegatibleCost::Expensive;
16175     SDValue NegN2 =
16176         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16177 
16178     if (!NegN2)
16179       return SDValue();
16180 
16181     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16182     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16183     // These transformations may change sign of zeroes. For example,
16184     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16185     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16186       // Try and choose the cheaper one to negate.
16187       NegatibleCost N0Cost = NegatibleCost::Expensive;
16188       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16189                                            N0Cost, Depth + 1);
16190 
16191       NegatibleCost N1Cost = NegatibleCost::Expensive;
16192       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16193                                            N1Cost, Depth + 1);
16194 
16195       if (NegN0 && N0Cost <= N1Cost) {
16196         Cost = std::min(N0Cost, N2Cost);
16197         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16198       } else if (NegN1) {
16199         Cost = std::min(N1Cost, N2Cost);
16200         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16201       }
16202     }
16203 
16204     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16205     if (isOperationLegal(ISD::FMA, VT)) {
16206       Cost = N2Cost;
16207       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16208     }
16209 
16210     break;
16211   }
16212 
16213   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16214                                               Cost, Depth);
16215 }
16216 
16217 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16218 bool PPCTargetLowering::useLoadStackGuardNode() const {
16219   if (!Subtarget.isTargetLinux())
16220     return TargetLowering::useLoadStackGuardNode();
16221   return true;
16222 }
16223 
16224 // Override to disable global variable loading on Linux.
16225 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16226   if (!Subtarget.isTargetLinux())
16227     return TargetLowering::insertSSPDeclarations(M);
16228 }
16229 
16230 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16231                                      bool ForCodeSize) const {
16232   if (!VT.isSimple() || !Subtarget.hasVSX())
16233     return false;
16234 
16235   switch(VT.getSimpleVT().SimpleTy) {
16236   default:
16237     // For FP types that are currently not supported by PPC backend, return
16238     // false. Examples: f16, f80.
16239     return false;
16240   case MVT::f32:
16241   case MVT::f64:
16242   case MVT::ppcf128:
16243     return Imm.isPosZero();
16244   }
16245 }
16246 
16247 // For vector shift operation op, fold
16248 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16249 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16250                                   SelectionDAG &DAG) {
16251   SDValue N0 = N->getOperand(0);
16252   SDValue N1 = N->getOperand(1);
16253   EVT VT = N0.getValueType();
16254   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16255   unsigned Opcode = N->getOpcode();
16256   unsigned TargetOpcode;
16257 
16258   switch (Opcode) {
16259   default:
16260     llvm_unreachable("Unexpected shift operation");
16261   case ISD::SHL:
16262     TargetOpcode = PPCISD::SHL;
16263     break;
16264   case ISD::SRL:
16265     TargetOpcode = PPCISD::SRL;
16266     break;
16267   case ISD::SRA:
16268     TargetOpcode = PPCISD::SRA;
16269     break;
16270   }
16271 
16272   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16273       N1->getOpcode() == ISD::AND)
16274     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16275       if (Mask->getZExtValue() == OpSizeInBits - 1)
16276         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16277 
16278   return SDValue();
16279 }
16280 
16281 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16282   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16283     return Value;
16284 
16285   SDValue N0 = N->getOperand(0);
16286   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16287   if (!Subtarget.isISA3_0() ||
16288       N0.getOpcode() != ISD::SIGN_EXTEND ||
16289       N0.getOperand(0).getValueType() != MVT::i32 ||
16290       CN1 == nullptr || N->getValueType(0) != MVT::i64)
16291     return SDValue();
16292 
16293   // We can't save an operation here if the value is already extended, and
16294   // the existing shift is easier to combine.
16295   SDValue ExtsSrc = N0.getOperand(0);
16296   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16297       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16298     return SDValue();
16299 
16300   SDLoc DL(N0);
16301   SDValue ShiftBy = SDValue(CN1, 0);
16302   // We want the shift amount to be i32 on the extswli, but the shift could
16303   // have an i64.
16304   if (ShiftBy.getValueType() == MVT::i64)
16305     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16306 
16307   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16308                          ShiftBy);
16309 }
16310 
16311 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16312   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16313     return Value;
16314 
16315   return SDValue();
16316 }
16317 
16318 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16319   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16320     return Value;
16321 
16322   return SDValue();
16323 }
16324 
16325 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16326 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16327 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16328 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16329 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16330                                  const PPCSubtarget &Subtarget) {
16331   if (!Subtarget.isPPC64())
16332     return SDValue();
16333 
16334   SDValue LHS = N->getOperand(0);
16335   SDValue RHS = N->getOperand(1);
16336 
16337   auto isZextOfCompareWithConstant = [](SDValue Op) {
16338     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16339         Op.getValueType() != MVT::i64)
16340       return false;
16341 
16342     SDValue Cmp = Op.getOperand(0);
16343     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16344         Cmp.getOperand(0).getValueType() != MVT::i64)
16345       return false;
16346 
16347     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16348       int64_t NegConstant = 0 - Constant->getSExtValue();
16349       // Due to the limitations of the addi instruction,
16350       // -C is required to be [-32768, 32767].
16351       return isInt<16>(NegConstant);
16352     }
16353 
16354     return false;
16355   };
16356 
16357   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16358   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16359 
16360   // If there is a pattern, canonicalize a zext operand to the RHS.
16361   if (LHSHasPattern && !RHSHasPattern)
16362     std::swap(LHS, RHS);
16363   else if (!LHSHasPattern && !RHSHasPattern)
16364     return SDValue();
16365 
16366   SDLoc DL(N);
16367   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16368   SDValue Cmp = RHS.getOperand(0);
16369   SDValue Z = Cmp.getOperand(0);
16370   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16371 
16372   assert(Constant && "Constant Should not be a null pointer.");
16373   int64_t NegConstant = 0 - Constant->getSExtValue();
16374 
16375   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16376   default: break;
16377   case ISD::SETNE: {
16378     //                                 when C == 0
16379     //                             --> addze X, (addic Z, -1).carry
16380     //                            /
16381     // add X, (zext(setne Z, C))--
16382     //                            \    when -32768 <= -C <= 32767 && C != 0
16383     //                             --> addze X, (addic (addi Z, -C), -1).carry
16384     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16385                               DAG.getConstant(NegConstant, DL, MVT::i64));
16386     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16387     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16388                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16389     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16390                        SDValue(Addc.getNode(), 1));
16391     }
16392   case ISD::SETEQ: {
16393     //                                 when C == 0
16394     //                             --> addze X, (subfic Z, 0).carry
16395     //                            /
16396     // add X, (zext(sete  Z, C))--
16397     //                            \    when -32768 <= -C <= 32767 && C != 0
16398     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16399     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16400                               DAG.getConstant(NegConstant, DL, MVT::i64));
16401     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16402     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16403                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16404     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16405                        SDValue(Subc.getNode(), 1));
16406     }
16407   }
16408 
16409   return SDValue();
16410 }
16411 
16412 // Transform
16413 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16414 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16415 // In this case both C1 and C2 must be known constants.
16416 // C1+C2 must fit into a 34 bit signed integer.
16417 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16418                                           const PPCSubtarget &Subtarget) {
16419   if (!Subtarget.isUsingPCRelativeCalls())
16420     return SDValue();
16421 
16422   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16423   // If we find that node try to cast the Global Address and the Constant.
16424   SDValue LHS = N->getOperand(0);
16425   SDValue RHS = N->getOperand(1);
16426 
16427   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16428     std::swap(LHS, RHS);
16429 
16430   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16431     return SDValue();
16432 
16433   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16434   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16435   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16436 
16437   // Check that both casts succeeded.
16438   if (!GSDN || !ConstNode)
16439     return SDValue();
16440 
16441   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16442   SDLoc DL(GSDN);
16443 
16444   // The signed int offset needs to fit in 34 bits.
16445   if (!isInt<34>(NewOffset))
16446     return SDValue();
16447 
16448   // The new global address is a copy of the old global address except
16449   // that it has the updated Offset.
16450   SDValue GA =
16451       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16452                                  NewOffset, GSDN->getTargetFlags());
16453   SDValue MatPCRel =
16454       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16455   return MatPCRel;
16456 }
16457 
16458 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16459   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16460     return Value;
16461 
16462   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16463     return Value;
16464 
16465   return SDValue();
16466 }
16467 
16468 // Detect TRUNCATE operations on bitcasts of float128 values.
16469 // What we are looking for here is the situtation where we extract a subset
16470 // of bits from a 128 bit float.
16471 // This can be of two forms:
16472 // 1) BITCAST of f128 feeding TRUNCATE
16473 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16474 // The reason this is required is because we do not have a legal i128 type
16475 // and so we want to prevent having to store the f128 and then reload part
16476 // of it.
16477 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16478                                            DAGCombinerInfo &DCI) const {
16479   // If we are using CRBits then try that first.
16480   if (Subtarget.useCRBits()) {
16481     // Check if CRBits did anything and return that if it did.
16482     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16483       return CRTruncValue;
16484   }
16485 
16486   SDLoc dl(N);
16487   SDValue Op0 = N->getOperand(0);
16488 
16489   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16490   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16491     EVT VT = N->getValueType(0);
16492     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16493       return SDValue();
16494     SDValue Sub = Op0.getOperand(0);
16495     if (Sub.getOpcode() == ISD::SUB) {
16496       SDValue SubOp0 = Sub.getOperand(0);
16497       SDValue SubOp1 = Sub.getOperand(1);
16498       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16499           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16500         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16501                                SubOp1.getOperand(0),
16502                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16503       }
16504     }
16505   }
16506 
16507   // Looking for a truncate of i128 to i64.
16508   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16509     return SDValue();
16510 
16511   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16512 
16513   // SRL feeding TRUNCATE.
16514   if (Op0.getOpcode() == ISD::SRL) {
16515     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16516     // The right shift has to be by 64 bits.
16517     if (!ConstNode || ConstNode->getZExtValue() != 64)
16518       return SDValue();
16519 
16520     // Switch the element number to extract.
16521     EltToExtract = EltToExtract ? 0 : 1;
16522     // Update Op0 past the SRL.
16523     Op0 = Op0.getOperand(0);
16524   }
16525 
16526   // BITCAST feeding a TRUNCATE possibly via SRL.
16527   if (Op0.getOpcode() == ISD::BITCAST &&
16528       Op0.getValueType() == MVT::i128 &&
16529       Op0.getOperand(0).getValueType() == MVT::f128) {
16530     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16531     return DCI.DAG.getNode(
16532         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16533         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16534   }
16535   return SDValue();
16536 }
16537 
16538 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16539   SelectionDAG &DAG = DCI.DAG;
16540 
16541   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16542   if (!ConstOpOrElement)
16543     return SDValue();
16544 
16545   // An imul is usually smaller than the alternative sequence for legal type.
16546   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16547       isOperationLegal(ISD::MUL, N->getValueType(0)))
16548     return SDValue();
16549 
16550   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16551     switch (this->Subtarget.getCPUDirective()) {
16552     default:
16553       // TODO: enhance the condition for subtarget before pwr8
16554       return false;
16555     case PPC::DIR_PWR8:
16556       //  type        mul     add    shl
16557       // scalar        4       1      1
16558       // vector        7       2      2
16559       return true;
16560     case PPC::DIR_PWR9:
16561     case PPC::DIR_PWR10:
16562     case PPC::DIR_PWR_FUTURE:
16563       //  type        mul     add    shl
16564       // scalar        5       2      2
16565       // vector        7       2      2
16566 
16567       // The cycle RATIO of related operations are showed as a table above.
16568       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16569       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16570       // are 4, it is always profitable; but for 3 instrs patterns
16571       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16572       // So we should only do it for vector type.
16573       return IsAddOne && IsNeg ? VT.isVector() : true;
16574     }
16575   };
16576 
16577   EVT VT = N->getValueType(0);
16578   SDLoc DL(N);
16579 
16580   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16581   bool IsNeg = MulAmt.isNegative();
16582   APInt MulAmtAbs = MulAmt.abs();
16583 
16584   if ((MulAmtAbs - 1).isPowerOf2()) {
16585     // (mul x, 2^N + 1) => (add (shl x, N), x)
16586     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16587 
16588     if (!IsProfitable(IsNeg, true, VT))
16589       return SDValue();
16590 
16591     SDValue Op0 = N->getOperand(0);
16592     SDValue Op1 =
16593         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16594                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16595     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16596 
16597     if (!IsNeg)
16598       return Res;
16599 
16600     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16601   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16602     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16603     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16604 
16605     if (!IsProfitable(IsNeg, false, VT))
16606       return SDValue();
16607 
16608     SDValue Op0 = N->getOperand(0);
16609     SDValue Op1 =
16610         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16611                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16612 
16613     if (!IsNeg)
16614       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16615     else
16616       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16617 
16618   } else {
16619     return SDValue();
16620   }
16621 }
16622 
16623 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16624 // in combiner since we need to check SD flags and other subtarget features.
16625 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16626                                           DAGCombinerInfo &DCI) const {
16627   SDValue N0 = N->getOperand(0);
16628   SDValue N1 = N->getOperand(1);
16629   SDValue N2 = N->getOperand(2);
16630   SDNodeFlags Flags = N->getFlags();
16631   EVT VT = N->getValueType(0);
16632   SelectionDAG &DAG = DCI.DAG;
16633   const TargetOptions &Options = getTargetMachine().Options;
16634   unsigned Opc = N->getOpcode();
16635   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16636   bool LegalOps = !DCI.isBeforeLegalizeOps();
16637   SDLoc Loc(N);
16638 
16639   // TODO: QPX subtarget is deprecated. No transformation here.
16640   if (Subtarget.hasQPX() || !isOperationLegal(ISD::FMA, VT))
16641     return SDValue();
16642 
16643   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16644   // since (fnmsub a b c)=-0 while c-ab=+0.
16645   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16646     return SDValue();
16647 
16648   // (fma (fneg a) b c) => (fnmsub a b c)
16649   // (fnmsub (fneg a) b c) => (fma a b c)
16650   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16651     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16652 
16653   // (fma a (fneg b) c) => (fnmsub a b c)
16654   // (fnmsub a (fneg b) c) => (fma a b c)
16655   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16656     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16657 
16658   return SDValue();
16659 }
16660 
16661 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16662   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16663   if (!Subtarget.is64BitELFABI())
16664     return false;
16665 
16666   // If not a tail call then no need to proceed.
16667   if (!CI->isTailCall())
16668     return false;
16669 
16670   // If sibling calls have been disabled and tail-calls aren't guaranteed
16671   // there is no reason to duplicate.
16672   auto &TM = getTargetMachine();
16673   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16674     return false;
16675 
16676   // Can't tail call a function called indirectly, or if it has variadic args.
16677   const Function *Callee = CI->getCalledFunction();
16678   if (!Callee || Callee->isVarArg())
16679     return false;
16680 
16681   // Make sure the callee and caller calling conventions are eligible for tco.
16682   const Function *Caller = CI->getParent()->getParent();
16683   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16684                                            CI->getCallingConv()))
16685       return false;
16686 
16687   // If the function is local then we have a good chance at tail-calling it
16688   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16689 }
16690 
16691 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16692   if (!Subtarget.hasVSX())
16693     return false;
16694   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16695     return true;
16696   return VT == MVT::f32 || VT == MVT::f64 ||
16697     VT == MVT::v4f32 || VT == MVT::v2f64;
16698 }
16699 
16700 bool PPCTargetLowering::
16701 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16702   const Value *Mask = AndI.getOperand(1);
16703   // If the mask is suitable for andi. or andis. we should sink the and.
16704   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16705     // Can't handle constants wider than 64-bits.
16706     if (CI->getBitWidth() > 64)
16707       return false;
16708     int64_t ConstVal = CI->getZExtValue();
16709     return isUInt<16>(ConstVal) ||
16710       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16711   }
16712 
16713   // For non-constant masks, we can always use the record-form and.
16714   return true;
16715 }
16716 
16717 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16718 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16719 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16720 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16721 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16722 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16723   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16724   assert(Subtarget.hasP9Altivec() &&
16725          "Only combine this when P9 altivec supported!");
16726   EVT VT = N->getValueType(0);
16727   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16728     return SDValue();
16729 
16730   SelectionDAG &DAG = DCI.DAG;
16731   SDLoc dl(N);
16732   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16733     // Even for signed integers, if it's known to be positive (as signed
16734     // integer) due to zero-extended inputs.
16735     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16736     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16737     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16738          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16739         (SubOpcd1 == ISD::ZERO_EXTEND ||
16740          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16741       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16742                          N->getOperand(0)->getOperand(0),
16743                          N->getOperand(0)->getOperand(1),
16744                          DAG.getTargetConstant(0, dl, MVT::i32));
16745     }
16746 
16747     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16748     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16749         N->getOperand(0).hasOneUse()) {
16750       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16751                          N->getOperand(0)->getOperand(0),
16752                          N->getOperand(0)->getOperand(1),
16753                          DAG.getTargetConstant(1, dl, MVT::i32));
16754     }
16755   }
16756 
16757   return SDValue();
16758 }
16759 
16760 // For type v4i32/v8ii16/v16i8, transform
16761 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16762 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16763 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16764 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16765 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16766                                           DAGCombinerInfo &DCI) const {
16767   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16768   assert(Subtarget.hasP9Altivec() &&
16769          "Only combine this when P9 altivec supported!");
16770 
16771   SelectionDAG &DAG = DCI.DAG;
16772   SDLoc dl(N);
16773   SDValue Cond = N->getOperand(0);
16774   SDValue TrueOpnd = N->getOperand(1);
16775   SDValue FalseOpnd = N->getOperand(2);
16776   EVT VT = N->getOperand(1).getValueType();
16777 
16778   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16779       FalseOpnd.getOpcode() != ISD::SUB)
16780     return SDValue();
16781 
16782   // ABSD only available for type v4i32/v8i16/v16i8
16783   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16784     return SDValue();
16785 
16786   // At least to save one more dependent computation
16787   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16788     return SDValue();
16789 
16790   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16791 
16792   // Can only handle unsigned comparison here
16793   switch (CC) {
16794   default:
16795     return SDValue();
16796   case ISD::SETUGT:
16797   case ISD::SETUGE:
16798     break;
16799   case ISD::SETULT:
16800   case ISD::SETULE:
16801     std::swap(TrueOpnd, FalseOpnd);
16802     break;
16803   }
16804 
16805   SDValue CmpOpnd1 = Cond.getOperand(0);
16806   SDValue CmpOpnd2 = Cond.getOperand(1);
16807 
16808   // SETCC CmpOpnd1 CmpOpnd2 cond
16809   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16810   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16811   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16812       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16813       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16814       FalseOpnd.getOperand(1) == CmpOpnd1) {
16815     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16816                        CmpOpnd1, CmpOpnd2,
16817                        DAG.getTargetConstant(0, dl, MVT::i32));
16818   }
16819 
16820   return SDValue();
16821 }
16822