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/CallSite.h"
59 #include "llvm/IR/CallingConv.h"
60 #include "llvm/IR/Constant.h"
61 #include "llvm/IR/Constants.h"
62 #include "llvm/IR/DataLayout.h"
63 #include "llvm/IR/DebugLoc.h"
64 #include "llvm/IR/DerivedTypes.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/GlobalValue.h"
67 #include "llvm/IR/IRBuilder.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Intrinsics.h"
70 #include "llvm/IR/IntrinsicsPowerPC.h"
71 #include "llvm/IR/Module.h"
72 #include "llvm/IR/Type.h"
73 #include "llvm/IR/Use.h"
74 #include "llvm/IR/Value.h"
75 #include "llvm/MC/MCContext.h"
76 #include "llvm/MC/MCExpr.h"
77 #include "llvm/MC/MCRegisterInfo.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
122 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
123 
124 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
125 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
126 
127 STATISTIC(NumTailCalls, "Number of tail calls");
128 STATISTIC(NumSiblingCalls, "Number of sibling calls");
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   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
171 
172   // PowerPC has pre-inc load and store's.
173   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
174   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
175   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
176   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
177   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
178   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
179   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
180   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
181   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
182   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
183   if (!Subtarget.hasSPE()) {
184     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
185     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
186     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
187     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
188   }
189 
190   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
191   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
192   for (MVT VT : ScalarIntVTs) {
193     setOperationAction(ISD::ADDC, VT, Legal);
194     setOperationAction(ISD::ADDE, VT, Legal);
195     setOperationAction(ISD::SUBC, VT, Legal);
196     setOperationAction(ISD::SUBE, VT, Legal);
197   }
198 
199   if (Subtarget.useCRBits()) {
200     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
201 
202     if (isPPC64 || Subtarget.hasFPCVT()) {
203       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
204       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
205                          isPPC64 ? MVT::i64 : MVT::i32);
206       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
207       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
208                         isPPC64 ? MVT::i64 : MVT::i32);
209     } else {
210       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
211       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
212     }
213 
214     // PowerPC does not support direct load/store of condition registers.
215     setOperationAction(ISD::LOAD, MVT::i1, Custom);
216     setOperationAction(ISD::STORE, MVT::i1, Custom);
217 
218     // FIXME: Remove this once the ANDI glue bug is fixed:
219     if (ANDIGlueBug)
220       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
221 
222     for (MVT VT : MVT::integer_valuetypes()) {
223       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
224       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
225       setTruncStoreAction(VT, MVT::i1, Expand);
226     }
227 
228     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
229   }
230 
231   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
232   // PPC (the libcall is not available).
233   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
234   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
235 
236   // We do not currently implement these libm ops for PowerPC.
237   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
238   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
239   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
240   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
241   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
242   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
243 
244   // PowerPC has no SREM/UREM instructions unless we are on P9
245   // On P9 we may use a hardware instruction to compute the remainder.
246   // The instructions are not legalized directly because in the cases where the
247   // result of both the remainder and the division is required it is more
248   // efficient to compute the remainder from the result of the division rather
249   // than use the remainder instruction.
250   if (Subtarget.isISA3_0()) {
251     setOperationAction(ISD::SREM, MVT::i32, Custom);
252     setOperationAction(ISD::UREM, MVT::i32, Custom);
253     setOperationAction(ISD::SREM, MVT::i64, Custom);
254     setOperationAction(ISD::UREM, MVT::i64, Custom);
255   } else {
256     setOperationAction(ISD::SREM, MVT::i32, Expand);
257     setOperationAction(ISD::UREM, MVT::i32, Expand);
258     setOperationAction(ISD::SREM, MVT::i64, Expand);
259     setOperationAction(ISD::UREM, MVT::i64, Expand);
260   }
261 
262   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
263   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
264   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
265   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
266   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
267   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
268   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
269   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
270   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
271 
272   // We don't support sin/cos/sqrt/fmod/pow
273   setOperationAction(ISD::FSIN , MVT::f64, Expand);
274   setOperationAction(ISD::FCOS , MVT::f64, Expand);
275   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
276   setOperationAction(ISD::FREM , MVT::f64, Expand);
277   setOperationAction(ISD::FPOW , MVT::f64, Expand);
278   setOperationAction(ISD::FSIN , MVT::f32, Expand);
279   setOperationAction(ISD::FCOS , MVT::f32, Expand);
280   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
281   setOperationAction(ISD::FREM , MVT::f32, Expand);
282   setOperationAction(ISD::FPOW , MVT::f32, Expand);
283   if (Subtarget.hasSPE()) {
284     setOperationAction(ISD::FMA  , MVT::f64, Expand);
285     setOperationAction(ISD::FMA  , MVT::f32, Expand);
286   } else {
287     setOperationAction(ISD::FMA  , MVT::f64, Legal);
288     setOperationAction(ISD::FMA  , MVT::f32, Legal);
289   }
290 
291   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
292 
293   // If we're enabling GP optimizations, use hardware square root
294   if (!Subtarget.hasFSQRT() &&
295       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
296         Subtarget.hasFRE()))
297     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
298 
299   if (!Subtarget.hasFSQRT() &&
300       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
301         Subtarget.hasFRES()))
302     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
303 
304   if (Subtarget.hasFCPSGN()) {
305     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
306     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
307   } else {
308     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
309     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
310   }
311 
312   if (Subtarget.hasFPRND()) {
313     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
314     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
315     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
316     setOperationAction(ISD::FROUND, MVT::f64, Legal);
317 
318     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
319     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
320     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
321     setOperationAction(ISD::FROUND, MVT::f32, Legal);
322   }
323 
324   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
325   // to speed up scalar BSWAP64.
326   // CTPOP or CTTZ were introduced in P8/P9 respectively
327   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
328   if (Subtarget.hasP9Vector())
329     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
330   else
331     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
332   if (Subtarget.isISA3_0()) {
333     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
334     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
335   } else {
336     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
337     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
338   }
339 
340   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
341     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
342     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
343   } else {
344     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
345     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
346   }
347 
348   // PowerPC does not have ROTR
349   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
350   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
351 
352   if (!Subtarget.useCRBits()) {
353     // PowerPC does not have Select
354     setOperationAction(ISD::SELECT, MVT::i32, Expand);
355     setOperationAction(ISD::SELECT, MVT::i64, Expand);
356     setOperationAction(ISD::SELECT, MVT::f32, Expand);
357     setOperationAction(ISD::SELECT, MVT::f64, Expand);
358   }
359 
360   // PowerPC wants to turn select_cc of FP into fsel when possible.
361   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
362   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
363 
364   // PowerPC wants to optimize integer setcc a bit
365   if (!Subtarget.useCRBits())
366     setOperationAction(ISD::SETCC, MVT::i32, Custom);
367 
368   // PowerPC does not have BRCOND which requires SetCC
369   if (!Subtarget.useCRBits())
370     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
371 
372   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
373 
374   if (Subtarget.hasSPE()) {
375     // SPE has built-in conversions
376     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
377     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
378     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
379   } else {
380     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
381     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
382 
383     // PowerPC does not have [U|S]INT_TO_FP
384     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
385     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
386   }
387 
388   if (Subtarget.hasDirectMove() && isPPC64) {
389     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
390     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
391     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
392     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
393     if (TM.Options.UnsafeFPMath) {
394       setOperationAction(ISD::LRINT, MVT::f64, Legal);
395       setOperationAction(ISD::LRINT, MVT::f32, Legal);
396       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
397       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
398       setOperationAction(ISD::LROUND, MVT::f64, Legal);
399       setOperationAction(ISD::LROUND, MVT::f32, Legal);
400       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
401       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
402     }
403   } else {
404     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
405     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
406     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
407     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
408   }
409 
410   // We cannot sextinreg(i1).  Expand to shifts.
411   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
412 
413   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
414   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
415   // support continuation, user-level threading, and etc.. As a result, no
416   // other SjLj exception interfaces are implemented and please don't build
417   // your own exception handling based on them.
418   // LLVM/Clang supports zero-cost DWARF exception handling.
419   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
420   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
421 
422   // We want to legalize GlobalAddress and ConstantPool nodes into the
423   // appropriate instructions to materialize the address.
424   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
425   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
426   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
427   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
428   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
429   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
430   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
431   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
432   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
433   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
434 
435   // TRAP is legal.
436   setOperationAction(ISD::TRAP, MVT::Other, Legal);
437 
438   // TRAMPOLINE is custom lowered.
439   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
440   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
441 
442   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
443   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
444 
445   if (Subtarget.is64BitELFABI()) {
446     // VAARG always uses double-word chunks, so promote anything smaller.
447     setOperationAction(ISD::VAARG, MVT::i1, Promote);
448     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
449     setOperationAction(ISD::VAARG, MVT::i8, Promote);
450     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
451     setOperationAction(ISD::VAARG, MVT::i16, Promote);
452     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
453     setOperationAction(ISD::VAARG, MVT::i32, Promote);
454     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
455     setOperationAction(ISD::VAARG, MVT::Other, Expand);
456   } else if (Subtarget.is32BitELFABI()) {
457     // VAARG is custom lowered with the 32-bit SVR4 ABI.
458     setOperationAction(ISD::VAARG, MVT::Other, Custom);
459     setOperationAction(ISD::VAARG, MVT::i64, Custom);
460   } else
461     setOperationAction(ISD::VAARG, MVT::Other, Expand);
462 
463   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
464   if (Subtarget.is32BitELFABI())
465     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
466   else
467     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
468 
469   // Use the default implementation.
470   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
471   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
472   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
473   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
474   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
475   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
476   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
477   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
478   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
479 
480   // We want to custom lower some of our intrinsics.
481   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
482 
483   // To handle counter-based loop conditions.
484   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
485 
486   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
487   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
488   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
489   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
490 
491   // Comparisons that require checking two conditions.
492   if (Subtarget.hasSPE()) {
493     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
494     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
495     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
496     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
497   }
498   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
499   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
500   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
501   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
502   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
503   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
504   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
505   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
506   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
507   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
508   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
509   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
510 
511   if (Subtarget.has64BitSupport()) {
512     // They also have instructions for converting between i64 and fp.
513     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
514     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
515     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
516     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
517     // This is just the low 32 bits of a (signed) fp->i64 conversion.
518     // We cannot do this with Promote because i64 is not a legal type.
519     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
520 
521     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
522       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
523   } else {
524     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
525     if (Subtarget.hasSPE())
526       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
527     else
528       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
529   }
530 
531   // With the instructions enabled under FPCVT, we can do everything.
532   if (Subtarget.hasFPCVT()) {
533     if (Subtarget.has64BitSupport()) {
534       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
535       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
536       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
537       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
538     }
539 
540     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
542     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
543     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
544   }
545 
546   if (Subtarget.use64BitRegs()) {
547     // 64-bit PowerPC implementations can support i64 types directly
548     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
549     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
550     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
551     // 64-bit PowerPC wants to expand i128 shifts itself.
552     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
553     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
554     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
555   } else {
556     // 32-bit PowerPC wants to expand i64 shifts itself.
557     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
558     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
559     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
560   }
561 
562   if (Subtarget.hasVSX()) {
563     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
564     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
565     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
566     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
567   }
568 
569   if (Subtarget.hasAltivec()) {
570     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
571       setOperationAction(ISD::SADDSAT, VT, Legal);
572       setOperationAction(ISD::SSUBSAT, VT, Legal);
573       setOperationAction(ISD::UADDSAT, VT, Legal);
574       setOperationAction(ISD::USUBSAT, VT, Legal);
575     }
576     // First set operation action for all vector types to expand. Then we
577     // will selectively turn on ones that can be effectively codegen'd.
578     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
579       // add/sub are legal for all supported vector VT's.
580       setOperationAction(ISD::ADD, VT, Legal);
581       setOperationAction(ISD::SUB, VT, Legal);
582 
583       // For v2i64, these are only valid with P8Vector. This is corrected after
584       // the loop.
585       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
586         setOperationAction(ISD::SMAX, VT, Legal);
587         setOperationAction(ISD::SMIN, VT, Legal);
588         setOperationAction(ISD::UMAX, VT, Legal);
589         setOperationAction(ISD::UMIN, VT, Legal);
590       }
591       else {
592         setOperationAction(ISD::SMAX, VT, Expand);
593         setOperationAction(ISD::SMIN, VT, Expand);
594         setOperationAction(ISD::UMAX, VT, Expand);
595         setOperationAction(ISD::UMIN, VT, Expand);
596       }
597 
598       if (Subtarget.hasVSX()) {
599         setOperationAction(ISD::FMAXNUM, VT, Legal);
600         setOperationAction(ISD::FMINNUM, VT, Legal);
601       }
602 
603       // Vector instructions introduced in P8
604       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
605         setOperationAction(ISD::CTPOP, VT, Legal);
606         setOperationAction(ISD::CTLZ, VT, Legal);
607       }
608       else {
609         setOperationAction(ISD::CTPOP, VT, Expand);
610         setOperationAction(ISD::CTLZ, VT, Expand);
611       }
612 
613       // Vector instructions introduced in P9
614       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
615         setOperationAction(ISD::CTTZ, VT, Legal);
616       else
617         setOperationAction(ISD::CTTZ, VT, Expand);
618 
619       // We promote all shuffles to v16i8.
620       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
621       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
622 
623       // We promote all non-typed operations to v4i32.
624       setOperationAction(ISD::AND   , VT, Promote);
625       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
626       setOperationAction(ISD::OR    , VT, Promote);
627       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
628       setOperationAction(ISD::XOR   , VT, Promote);
629       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
630       setOperationAction(ISD::LOAD  , VT, Promote);
631       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
632       setOperationAction(ISD::SELECT, VT, Promote);
633       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
634       setOperationAction(ISD::VSELECT, VT, Legal);
635       setOperationAction(ISD::SELECT_CC, VT, Promote);
636       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
637       setOperationAction(ISD::STORE, VT, Promote);
638       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
639 
640       // No other operations are legal.
641       setOperationAction(ISD::MUL , VT, Expand);
642       setOperationAction(ISD::SDIV, VT, Expand);
643       setOperationAction(ISD::SREM, VT, Expand);
644       setOperationAction(ISD::UDIV, VT, Expand);
645       setOperationAction(ISD::UREM, VT, Expand);
646       setOperationAction(ISD::FDIV, VT, Expand);
647       setOperationAction(ISD::FREM, VT, Expand);
648       setOperationAction(ISD::FNEG, VT, Expand);
649       setOperationAction(ISD::FSQRT, VT, Expand);
650       setOperationAction(ISD::FLOG, VT, Expand);
651       setOperationAction(ISD::FLOG10, VT, Expand);
652       setOperationAction(ISD::FLOG2, VT, Expand);
653       setOperationAction(ISD::FEXP, VT, Expand);
654       setOperationAction(ISD::FEXP2, VT, Expand);
655       setOperationAction(ISD::FSIN, VT, Expand);
656       setOperationAction(ISD::FCOS, VT, Expand);
657       setOperationAction(ISD::FABS, VT, Expand);
658       setOperationAction(ISD::FFLOOR, VT, Expand);
659       setOperationAction(ISD::FCEIL,  VT, Expand);
660       setOperationAction(ISD::FTRUNC, VT, Expand);
661       setOperationAction(ISD::FRINT,  VT, Expand);
662       setOperationAction(ISD::FNEARBYINT, VT, Expand);
663       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
664       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
665       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
666       setOperationAction(ISD::MULHU, VT, Expand);
667       setOperationAction(ISD::MULHS, VT, Expand);
668       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
669       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
670       setOperationAction(ISD::UDIVREM, VT, Expand);
671       setOperationAction(ISD::SDIVREM, VT, Expand);
672       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
673       setOperationAction(ISD::FPOW, VT, Expand);
674       setOperationAction(ISD::BSWAP, VT, Expand);
675       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
676       setOperationAction(ISD::ROTL, VT, Expand);
677       setOperationAction(ISD::ROTR, VT, Expand);
678 
679       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
680         setTruncStoreAction(VT, InnerVT, Expand);
681         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
682         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
683         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
684       }
685     }
686     if (!Subtarget.hasP8Vector()) {
687       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
688       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
689       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
690       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
691     }
692 
693     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
694       setOperationAction(ISD::ABS, VT, Custom);
695 
696     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
697     // with merges, splats, etc.
698     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
699 
700     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
701     // are cheap, so handle them before they get expanded to scalar.
702     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
703     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
704     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
705     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
706     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
707 
708     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
709     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
710     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
711     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
712     setOperationAction(ISD::SELECT, MVT::v4i32,
713                        Subtarget.useCRBits() ? Legal : Expand);
714     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
715     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
716     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
717     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
718     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
719     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
720     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
721     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
722     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
723 
724     // Without hasP8Altivec set, v2i64 SMAX isn't available.
725     // But ABS custom lowering requires SMAX support.
726     if (!Subtarget.hasP8Altivec())
727       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
728 
729     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
730     if (Subtarget.hasAltivec())
731       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
732         setOperationAction(ISD::ROTL, VT, Legal);
733     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
734     if (Subtarget.hasP8Altivec())
735       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
736 
737     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
738     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
739     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
740     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
741 
742     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
743     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
744 
745     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
746       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
747       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
748     }
749 
750     if (Subtarget.hasP8Altivec())
751       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
752     else
753       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
754 
755     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
756     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
757 
758     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
759     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
760 
761     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
762     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
763     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
764     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
765 
766     // Altivec does not contain unordered floating-point compare instructions
767     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
768     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
769     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
770     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
771 
772     if (Subtarget.hasVSX()) {
773       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
774       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
775       if (Subtarget.hasP8Vector()) {
776         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
777         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
778       }
779       if (Subtarget.hasDirectMove() && isPPC64) {
780         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
781         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
782         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
783         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
784         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
785         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
786         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
787         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
788       }
789       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
790 
791       // The nearbyint variants are not allowed to raise the inexact exception
792       // so we can only code-gen them with unsafe math.
793       if (TM.Options.UnsafeFPMath) {
794         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
795         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
796       }
797 
798       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
799       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
800       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
801       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
802       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
803       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
804       setOperationAction(ISD::FROUND, MVT::f64, Legal);
805       setOperationAction(ISD::FRINT, MVT::f64, Legal);
806 
807       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
808       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
809       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
810       setOperationAction(ISD::FROUND, MVT::f32, Legal);
811       setOperationAction(ISD::FRINT, MVT::f32, Legal);
812 
813       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
814       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
815 
816       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
817       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
818 
819       // Share the Altivec comparison restrictions.
820       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
821       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
822       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
823       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
824 
825       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
826       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
827 
828       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
829 
830       if (Subtarget.hasP8Vector())
831         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
832 
833       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
834 
835       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
836       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
837       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
838 
839       if (Subtarget.hasP8Altivec()) {
840         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
841         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
842         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
843 
844         // 128 bit shifts can be accomplished via 3 instructions for SHL and
845         // SRL, but not for SRA because of the instructions available:
846         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
847         // doing
848         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
849         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
850         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
851 
852         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
853       }
854       else {
855         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
856         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
857         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
858 
859         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
860 
861         // VSX v2i64 only supports non-arithmetic operations.
862         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
863         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
864       }
865 
866       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
867       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
868       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
869       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
870 
871       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
872 
873       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
874       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
875       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
876       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
877 
878       // Custom handling for partial vectors of integers converted to
879       // floating point. We already have optimal handling for v2i32 through
880       // the DAG combine, so those aren't necessary.
881       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
882       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
883       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
884       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
885       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
886       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
887       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
888       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
889 
890       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
891       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
892       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
893       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
894       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
895       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
896 
897       if (Subtarget.hasDirectMove())
898         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
899       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
900 
901       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
902     }
903 
904     if (Subtarget.hasP8Altivec()) {
905       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
906       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
907     }
908 
909     if (Subtarget.hasP9Vector()) {
910       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
911       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
912 
913       // 128 bit shifts can be accomplished via 3 instructions for SHL and
914       // SRL, but not for SRA because of the instructions available:
915       // VS{RL} and VS{RL}O.
916       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
917       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
918       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
919 
920       if (EnableQuadPrecision) {
921         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
922         setOperationAction(ISD::FADD, MVT::f128, Legal);
923         setOperationAction(ISD::FSUB, MVT::f128, Legal);
924         setOperationAction(ISD::FDIV, MVT::f128, Legal);
925         setOperationAction(ISD::FMUL, MVT::f128, Legal);
926         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
927         // No extending loads to f128 on PPC.
928         for (MVT FPT : MVT::fp_valuetypes())
929           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
930         setOperationAction(ISD::FMA, MVT::f128, Legal);
931         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
932         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
933         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
934         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
935         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
936         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
937 
938         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
939         setOperationAction(ISD::FRINT, MVT::f128, Legal);
940         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
941         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
942         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
943         setOperationAction(ISD::FROUND, MVT::f128, Legal);
944 
945         setOperationAction(ISD::SELECT, MVT::f128, Expand);
946         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
947         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
948         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
949         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
950         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
951         // No implementation for these ops for PowerPC.
952         setOperationAction(ISD::FSIN , MVT::f128, Expand);
953         setOperationAction(ISD::FCOS , MVT::f128, Expand);
954         setOperationAction(ISD::FPOW, MVT::f128, Expand);
955         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
956         setOperationAction(ISD::FREM, MVT::f128, Expand);
957       }
958       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
959       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
960       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
961       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
962       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
963     }
964 
965     if (Subtarget.hasP9Altivec()) {
966       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
967       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
968 
969       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
970       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
971       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
972       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
973       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
974       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
975       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
976     }
977   }
978 
979   if (Subtarget.hasQPX()) {
980     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
981     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
982     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
983     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
984 
985     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
986     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
987 
988     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
989     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
990 
991     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
992     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
993 
994     if (!Subtarget.useCRBits())
995       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
996     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
997 
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
999     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1000     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1001     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1002     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1003     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1004     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1005 
1006     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1007     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1008 
1009     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1010     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1011 
1012     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1013     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1014     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1015     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1016     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1017     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1018     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1019     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1020     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1021     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1022 
1023     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1024     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1025 
1026     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1027     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1028 
1029     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1030 
1031     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1032     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1033     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1034     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1035 
1036     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1037     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1038 
1039     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1040     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1041 
1042     if (!Subtarget.useCRBits())
1043       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1044     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1045 
1046     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1047     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1048     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1049     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1050     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1051     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1052     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1053 
1054     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1055     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1056 
1057     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1058     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1059     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1060     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1061     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1062     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1063     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1064     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1065     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1066     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1067 
1068     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1069     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1070 
1071     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1072     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1073 
1074     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1075 
1076     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1077     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1078     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1079 
1080     if (!Subtarget.useCRBits())
1081       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1082     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1083 
1084     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1085     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1086 
1087     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1088     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1089     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1090     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1091     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1092     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1093     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1094 
1095     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1096     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1097 
1098     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1099 
1100     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1101     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1102     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1103     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1104 
1105     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1106     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1107     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1108     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1109 
1110     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1111     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1112 
1113     // These need to set FE_INEXACT, and so cannot be vectorized here.
1114     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1115     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1116 
1117     if (TM.Options.UnsafeFPMath) {
1118       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1119       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1120 
1121       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1122       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1123     } else {
1124       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1125       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1126 
1127       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1128       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1129     }
1130   }
1131 
1132   if (Subtarget.has64BitSupport())
1133     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1134 
1135   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1136 
1137   if (!isPPC64) {
1138     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1139     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1140   }
1141 
1142   setBooleanContents(ZeroOrOneBooleanContent);
1143 
1144   if (Subtarget.hasAltivec()) {
1145     // Altivec instructions set fields to all zeros or all ones.
1146     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1147   }
1148 
1149   if (!isPPC64) {
1150     // These libcalls are not available in 32-bit.
1151     setLibcallName(RTLIB::SHL_I128, nullptr);
1152     setLibcallName(RTLIB::SRL_I128, nullptr);
1153     setLibcallName(RTLIB::SRA_I128, nullptr);
1154   }
1155 
1156   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1157 
1158   // We have target-specific dag combine patterns for the following nodes:
1159   setTargetDAGCombine(ISD::ADD);
1160   setTargetDAGCombine(ISD::SHL);
1161   setTargetDAGCombine(ISD::SRA);
1162   setTargetDAGCombine(ISD::SRL);
1163   setTargetDAGCombine(ISD::MUL);
1164   setTargetDAGCombine(ISD::SINT_TO_FP);
1165   setTargetDAGCombine(ISD::BUILD_VECTOR);
1166   if (Subtarget.hasFPCVT())
1167     setTargetDAGCombine(ISD::UINT_TO_FP);
1168   setTargetDAGCombine(ISD::LOAD);
1169   setTargetDAGCombine(ISD::STORE);
1170   setTargetDAGCombine(ISD::BR_CC);
1171   if (Subtarget.useCRBits())
1172     setTargetDAGCombine(ISD::BRCOND);
1173   setTargetDAGCombine(ISD::BSWAP);
1174   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1175   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1176   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1177 
1178   setTargetDAGCombine(ISD::SIGN_EXTEND);
1179   setTargetDAGCombine(ISD::ZERO_EXTEND);
1180   setTargetDAGCombine(ISD::ANY_EXTEND);
1181 
1182   setTargetDAGCombine(ISD::TRUNCATE);
1183   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1184 
1185 
1186   if (Subtarget.useCRBits()) {
1187     setTargetDAGCombine(ISD::TRUNCATE);
1188     setTargetDAGCombine(ISD::SETCC);
1189     setTargetDAGCombine(ISD::SELECT_CC);
1190   }
1191 
1192   // Use reciprocal estimates.
1193   if (TM.Options.UnsafeFPMath) {
1194     setTargetDAGCombine(ISD::FDIV);
1195     setTargetDAGCombine(ISD::FSQRT);
1196   }
1197 
1198   if (Subtarget.hasP9Altivec()) {
1199     setTargetDAGCombine(ISD::ABS);
1200     setTargetDAGCombine(ISD::VSELECT);
1201   }
1202 
1203   if (EnableQuadPrecision) {
1204     setLibcallName(RTLIB::LOG_F128, "logf128");
1205     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1206     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1207     setLibcallName(RTLIB::EXP_F128, "expf128");
1208     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1209     setLibcallName(RTLIB::SIN_F128, "sinf128");
1210     setLibcallName(RTLIB::COS_F128, "cosf128");
1211     setLibcallName(RTLIB::POW_F128, "powf128");
1212     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1213     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1214     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1215     setLibcallName(RTLIB::REM_F128, "fmodf128");
1216   }
1217 
1218   // With 32 condition bits, we don't need to sink (and duplicate) compares
1219   // aggressively in CodeGenPrep.
1220   if (Subtarget.useCRBits()) {
1221     setHasMultipleConditionRegisters();
1222     setJumpIsExpensive();
1223   }
1224 
1225   setMinFunctionAlignment(Align(4));
1226 
1227   switch (Subtarget.getCPUDirective()) {
1228   default: break;
1229   case PPC::DIR_970:
1230   case PPC::DIR_A2:
1231   case PPC::DIR_E500:
1232   case PPC::DIR_E500mc:
1233   case PPC::DIR_E5500:
1234   case PPC::DIR_PWR4:
1235   case PPC::DIR_PWR5:
1236   case PPC::DIR_PWR5X:
1237   case PPC::DIR_PWR6:
1238   case PPC::DIR_PWR6X:
1239   case PPC::DIR_PWR7:
1240   case PPC::DIR_PWR8:
1241   case PPC::DIR_PWR9:
1242   case PPC::DIR_PWR_FUTURE:
1243     setPrefLoopAlignment(Align(16));
1244     setPrefFunctionAlignment(Align(16));
1245     break;
1246   }
1247 
1248   if (Subtarget.enableMachineScheduler())
1249     setSchedulingPreference(Sched::Source);
1250   else
1251     setSchedulingPreference(Sched::Hybrid);
1252 
1253   computeRegisterProperties(STI.getRegisterInfo());
1254 
1255   // The Freescale cores do better with aggressive inlining of memcpy and
1256   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1257   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1258       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1259     MaxStoresPerMemset = 32;
1260     MaxStoresPerMemsetOptSize = 16;
1261     MaxStoresPerMemcpy = 32;
1262     MaxStoresPerMemcpyOptSize = 8;
1263     MaxStoresPerMemmove = 32;
1264     MaxStoresPerMemmoveOptSize = 8;
1265   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1266     // The A2 also benefits from (very) aggressive inlining of memcpy and
1267     // friends. The overhead of a the function call, even when warm, can be
1268     // over one hundred cycles.
1269     MaxStoresPerMemset = 128;
1270     MaxStoresPerMemcpy = 128;
1271     MaxStoresPerMemmove = 128;
1272     MaxLoadsPerMemcmp = 128;
1273   } else {
1274     MaxLoadsPerMemcmp = 8;
1275     MaxLoadsPerMemcmpOptSize = 4;
1276   }
1277 }
1278 
1279 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1280 /// the desired ByVal argument alignment.
1281 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1282                              unsigned MaxMaxAlign) {
1283   if (MaxAlign == MaxMaxAlign)
1284     return;
1285   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1286     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1287       MaxAlign = 32;
1288     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1289       MaxAlign = 16;
1290   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1291     unsigned EltAlign = 0;
1292     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1293     if (EltAlign > MaxAlign)
1294       MaxAlign = EltAlign;
1295   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1296     for (auto *EltTy : STy->elements()) {
1297       unsigned EltAlign = 0;
1298       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1299       if (EltAlign > MaxAlign)
1300         MaxAlign = EltAlign;
1301       if (MaxAlign == MaxMaxAlign)
1302         break;
1303     }
1304   }
1305 }
1306 
1307 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1308 /// function arguments in the caller parameter area.
1309 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1310                                                   const DataLayout &DL) const {
1311   // 16byte and wider vectors are passed on 16byte boundary.
1312   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1313   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1314   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1315     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1316   return Align;
1317 }
1318 
1319 bool PPCTargetLowering::useSoftFloat() const {
1320   return Subtarget.useSoftFloat();
1321 }
1322 
1323 bool PPCTargetLowering::hasSPE() const {
1324   return Subtarget.hasSPE();
1325 }
1326 
1327 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1328   return VT.isScalarInteger();
1329 }
1330 
1331 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1332   switch ((PPCISD::NodeType)Opcode) {
1333   case PPCISD::FIRST_NUMBER:    break;
1334   case PPCISD::FSEL:            return "PPCISD::FSEL";
1335   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1336   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1337   case PPCISD::FCFID:           return "PPCISD::FCFID";
1338   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1339   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1340   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1341   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1342   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1343   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1344   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1345   case PPCISD::FP_TO_UINT_IN_VSR:
1346                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1347   case PPCISD::FP_TO_SINT_IN_VSR:
1348                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1349   case PPCISD::FRE:             return "PPCISD::FRE";
1350   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1351   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1352   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1353   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1354   case PPCISD::VPERM:           return "PPCISD::VPERM";
1355   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1356   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1357   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1358   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1359   case PPCISD::CMPB:            return "PPCISD::CMPB";
1360   case PPCISD::Hi:              return "PPCISD::Hi";
1361   case PPCISD::Lo:              return "PPCISD::Lo";
1362   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1363   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1364   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1365   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1366   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1367   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1368   case PPCISD::SRL:             return "PPCISD::SRL";
1369   case PPCISD::SRA:             return "PPCISD::SRA";
1370   case PPCISD::SHL:             return "PPCISD::SHL";
1371   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1372   case PPCISD::CALL:            return "PPCISD::CALL";
1373   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1374   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1375   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1376   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1377   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1378   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1379   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1380   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1381   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1382   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1383   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1384   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1385   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1386   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1387   case PPCISD::ANDI_rec_1_EQ_BIT:
1388     return "PPCISD::ANDI_rec_1_EQ_BIT";
1389   case PPCISD::ANDI_rec_1_GT_BIT:
1390     return "PPCISD::ANDI_rec_1_GT_BIT";
1391   case PPCISD::VCMP:            return "PPCISD::VCMP";
1392   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1393   case PPCISD::LBRX:            return "PPCISD::LBRX";
1394   case PPCISD::STBRX:           return "PPCISD::STBRX";
1395   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1396   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1397   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1398   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1399   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1400   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1401   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1402   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1403   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1404   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1405   case PPCISD::ST_VSR_SCAL_INT:
1406                                 return "PPCISD::ST_VSR_SCAL_INT";
1407   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1408   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1409   case PPCISD::BDZ:             return "PPCISD::BDZ";
1410   case PPCISD::MFFS:            return "PPCISD::MFFS";
1411   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1412   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1413   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1414   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1415   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1416   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1417   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1418   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1419   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1420   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1421   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1422   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1423   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1424   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1425   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1426   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1427   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1428   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1429   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1430   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1431   case PPCISD::SC:              return "PPCISD::SC";
1432   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1433   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1434   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1435   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1436   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1437   case PPCISD::VABSD:           return "PPCISD::VABSD";
1438   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1439   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1440   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1441   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1442   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1443   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1444   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1445   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1446   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1447   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1448   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1449   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1450   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1451   }
1452   return nullptr;
1453 }
1454 
1455 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1456                                           EVT VT) const {
1457   if (!VT.isVector())
1458     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1459 
1460   if (Subtarget.hasQPX())
1461     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1462 
1463   return VT.changeVectorElementTypeToInteger();
1464 }
1465 
1466 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1467   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1468   return true;
1469 }
1470 
1471 //===----------------------------------------------------------------------===//
1472 // Node matching predicates, for use by the tblgen matching code.
1473 //===----------------------------------------------------------------------===//
1474 
1475 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1476 static bool isFloatingPointZero(SDValue Op) {
1477   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1478     return CFP->getValueAPF().isZero();
1479   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1480     // Maybe this has already been legalized into the constant pool?
1481     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1482       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1483         return CFP->getValueAPF().isZero();
1484   }
1485   return false;
1486 }
1487 
1488 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1489 /// true if Op is undef or if it matches the specified value.
1490 static bool isConstantOrUndef(int Op, int Val) {
1491   return Op < 0 || Op == Val;
1492 }
1493 
1494 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1495 /// VPKUHUM instruction.
1496 /// The ShuffleKind distinguishes between big-endian operations with
1497 /// two different inputs (0), either-endian operations with two identical
1498 /// inputs (1), and little-endian operations with two different inputs (2).
1499 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1500 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1501                                SelectionDAG &DAG) {
1502   bool IsLE = DAG.getDataLayout().isLittleEndian();
1503   if (ShuffleKind == 0) {
1504     if (IsLE)
1505       return false;
1506     for (unsigned i = 0; i != 16; ++i)
1507       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1508         return false;
1509   } else if (ShuffleKind == 2) {
1510     if (!IsLE)
1511       return false;
1512     for (unsigned i = 0; i != 16; ++i)
1513       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1514         return false;
1515   } else if (ShuffleKind == 1) {
1516     unsigned j = IsLE ? 0 : 1;
1517     for (unsigned i = 0; i != 8; ++i)
1518       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1519           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1520         return false;
1521   }
1522   return true;
1523 }
1524 
1525 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1526 /// VPKUWUM instruction.
1527 /// The ShuffleKind distinguishes between big-endian operations with
1528 /// two different inputs (0), either-endian operations with two identical
1529 /// inputs (1), and little-endian operations with two different inputs (2).
1530 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1531 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1532                                SelectionDAG &DAG) {
1533   bool IsLE = DAG.getDataLayout().isLittleEndian();
1534   if (ShuffleKind == 0) {
1535     if (IsLE)
1536       return false;
1537     for (unsigned i = 0; i != 16; i += 2)
1538       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1539           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1540         return false;
1541   } else if (ShuffleKind == 2) {
1542     if (!IsLE)
1543       return false;
1544     for (unsigned i = 0; i != 16; i += 2)
1545       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1546           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1547         return false;
1548   } else if (ShuffleKind == 1) {
1549     unsigned j = IsLE ? 0 : 2;
1550     for (unsigned i = 0; i != 8; i += 2)
1551       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1552           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1553           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1554           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1555         return false;
1556   }
1557   return true;
1558 }
1559 
1560 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1561 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1562 /// current subtarget.
1563 ///
1564 /// The ShuffleKind distinguishes between big-endian operations with
1565 /// two different inputs (0), either-endian operations with two identical
1566 /// inputs (1), and little-endian operations with two different inputs (2).
1567 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1568 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1569                                SelectionDAG &DAG) {
1570   const PPCSubtarget& Subtarget =
1571       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1572   if (!Subtarget.hasP8Vector())
1573     return false;
1574 
1575   bool IsLE = DAG.getDataLayout().isLittleEndian();
1576   if (ShuffleKind == 0) {
1577     if (IsLE)
1578       return false;
1579     for (unsigned i = 0; i != 16; i += 4)
1580       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1581           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1582           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1583           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1584         return false;
1585   } else if (ShuffleKind == 2) {
1586     if (!IsLE)
1587       return false;
1588     for (unsigned i = 0; i != 16; i += 4)
1589       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1590           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1591           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1592           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1593         return false;
1594   } else if (ShuffleKind == 1) {
1595     unsigned j = IsLE ? 0 : 4;
1596     for (unsigned i = 0; i != 8; i += 4)
1597       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1598           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1599           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1600           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1601           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1602           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1603           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1604           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1605         return false;
1606   }
1607   return true;
1608 }
1609 
1610 /// isVMerge - Common function, used to match vmrg* shuffles.
1611 ///
1612 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1613                      unsigned LHSStart, unsigned RHSStart) {
1614   if (N->getValueType(0) != MVT::v16i8)
1615     return false;
1616   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1617          "Unsupported merge size!");
1618 
1619   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1620     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1621       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1622                              LHSStart+j+i*UnitSize) ||
1623           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1624                              RHSStart+j+i*UnitSize))
1625         return false;
1626     }
1627   return true;
1628 }
1629 
1630 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1631 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1632 /// The ShuffleKind distinguishes between big-endian merges with two
1633 /// different inputs (0), either-endian merges with two identical inputs (1),
1634 /// and little-endian merges with two different inputs (2).  For the latter,
1635 /// the input operands are swapped (see PPCInstrAltivec.td).
1636 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1637                              unsigned ShuffleKind, SelectionDAG &DAG) {
1638   if (DAG.getDataLayout().isLittleEndian()) {
1639     if (ShuffleKind == 1) // unary
1640       return isVMerge(N, UnitSize, 0, 0);
1641     else if (ShuffleKind == 2) // swapped
1642       return isVMerge(N, UnitSize, 0, 16);
1643     else
1644       return false;
1645   } else {
1646     if (ShuffleKind == 1) // unary
1647       return isVMerge(N, UnitSize, 8, 8);
1648     else if (ShuffleKind == 0) // normal
1649       return isVMerge(N, UnitSize, 8, 24);
1650     else
1651       return false;
1652   }
1653 }
1654 
1655 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1656 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1657 /// The ShuffleKind distinguishes between big-endian merges with two
1658 /// different inputs (0), either-endian merges with two identical inputs (1),
1659 /// and little-endian merges with two different inputs (2).  For the latter,
1660 /// the input operands are swapped (see PPCInstrAltivec.td).
1661 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1662                              unsigned ShuffleKind, SelectionDAG &DAG) {
1663   if (DAG.getDataLayout().isLittleEndian()) {
1664     if (ShuffleKind == 1) // unary
1665       return isVMerge(N, UnitSize, 8, 8);
1666     else if (ShuffleKind == 2) // swapped
1667       return isVMerge(N, UnitSize, 8, 24);
1668     else
1669       return false;
1670   } else {
1671     if (ShuffleKind == 1) // unary
1672       return isVMerge(N, UnitSize, 0, 0);
1673     else if (ShuffleKind == 0) // normal
1674       return isVMerge(N, UnitSize, 0, 16);
1675     else
1676       return false;
1677   }
1678 }
1679 
1680 /**
1681  * Common function used to match vmrgew and vmrgow shuffles
1682  *
1683  * The indexOffset determines whether to look for even or odd words in
1684  * the shuffle mask. This is based on the of the endianness of the target
1685  * machine.
1686  *   - Little Endian:
1687  *     - Use offset of 0 to check for odd elements
1688  *     - Use offset of 4 to check for even elements
1689  *   - Big Endian:
1690  *     - Use offset of 0 to check for even elements
1691  *     - Use offset of 4 to check for odd elements
1692  * A detailed description of the vector element ordering for little endian and
1693  * big endian can be found at
1694  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1695  * Targeting your applications - what little endian and big endian IBM XL C/C++
1696  * compiler differences mean to you
1697  *
1698  * The mask to the shuffle vector instruction specifies the indices of the
1699  * elements from the two input vectors to place in the result. The elements are
1700  * numbered in array-access order, starting with the first vector. These vectors
1701  * are always of type v16i8, thus each vector will contain 16 elements of size
1702  * 8. More info on the shuffle vector can be found in the
1703  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1704  * Language Reference.
1705  *
1706  * The RHSStartValue indicates whether the same input vectors are used (unary)
1707  * or two different input vectors are used, based on the following:
1708  *   - If the instruction uses the same vector for both inputs, the range of the
1709  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1710  *     be 0.
1711  *   - If the instruction has two different vectors then the range of the
1712  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1713  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1714  *     to 31 specify elements in the second vector).
1715  *
1716  * \param[in] N The shuffle vector SD Node to analyze
1717  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1718  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1719  * vector to the shuffle_vector instruction
1720  * \return true iff this shuffle vector represents an even or odd word merge
1721  */
1722 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1723                      unsigned RHSStartValue) {
1724   if (N->getValueType(0) != MVT::v16i8)
1725     return false;
1726 
1727   for (unsigned i = 0; i < 2; ++i)
1728     for (unsigned j = 0; j < 4; ++j)
1729       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1730                              i*RHSStartValue+j+IndexOffset) ||
1731           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1732                              i*RHSStartValue+j+IndexOffset+8))
1733         return false;
1734   return true;
1735 }
1736 
1737 /**
1738  * Determine if the specified shuffle mask is suitable for the vmrgew or
1739  * vmrgow instructions.
1740  *
1741  * \param[in] N The shuffle vector SD Node to analyze
1742  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1743  * \param[in] ShuffleKind Identify the type of merge:
1744  *   - 0 = big-endian merge with two different inputs;
1745  *   - 1 = either-endian merge with two identical inputs;
1746  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1747  *     little-endian merges).
1748  * \param[in] DAG The current SelectionDAG
1749  * \return true iff this shuffle mask
1750  */
1751 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1752                               unsigned ShuffleKind, SelectionDAG &DAG) {
1753   if (DAG.getDataLayout().isLittleEndian()) {
1754     unsigned indexOffset = CheckEven ? 4 : 0;
1755     if (ShuffleKind == 1) // Unary
1756       return isVMerge(N, indexOffset, 0);
1757     else if (ShuffleKind == 2) // swapped
1758       return isVMerge(N, indexOffset, 16);
1759     else
1760       return false;
1761   }
1762   else {
1763     unsigned indexOffset = CheckEven ? 0 : 4;
1764     if (ShuffleKind == 1) // Unary
1765       return isVMerge(N, indexOffset, 0);
1766     else if (ShuffleKind == 0) // Normal
1767       return isVMerge(N, indexOffset, 16);
1768     else
1769       return false;
1770   }
1771   return false;
1772 }
1773 
1774 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1775 /// amount, otherwise return -1.
1776 /// The ShuffleKind distinguishes between big-endian operations with two
1777 /// different inputs (0), either-endian operations with two identical inputs
1778 /// (1), and little-endian operations with two different inputs (2).  For the
1779 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1780 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1781                              SelectionDAG &DAG) {
1782   if (N->getValueType(0) != MVT::v16i8)
1783     return -1;
1784 
1785   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1786 
1787   // Find the first non-undef value in the shuffle mask.
1788   unsigned i;
1789   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1790     /*search*/;
1791 
1792   if (i == 16) return -1;  // all undef.
1793 
1794   // Otherwise, check to see if the rest of the elements are consecutively
1795   // numbered from this value.
1796   unsigned ShiftAmt = SVOp->getMaskElt(i);
1797   if (ShiftAmt < i) return -1;
1798 
1799   ShiftAmt -= i;
1800   bool isLE = DAG.getDataLayout().isLittleEndian();
1801 
1802   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1803     // Check the rest of the elements to see if they are consecutive.
1804     for (++i; i != 16; ++i)
1805       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1806         return -1;
1807   } else if (ShuffleKind == 1) {
1808     // Check the rest of the elements to see if they are consecutive.
1809     for (++i; i != 16; ++i)
1810       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1811         return -1;
1812   } else
1813     return -1;
1814 
1815   if (isLE)
1816     ShiftAmt = 16 - ShiftAmt;
1817 
1818   return ShiftAmt;
1819 }
1820 
1821 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1822 /// specifies a splat of a single element that is suitable for input to
1823 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1824 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1825   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1826          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1827 
1828   // The consecutive indices need to specify an element, not part of two
1829   // different elements.  So abandon ship early if this isn't the case.
1830   if (N->getMaskElt(0) % EltSize != 0)
1831     return false;
1832 
1833   // This is a splat operation if each element of the permute is the same, and
1834   // if the value doesn't reference the second vector.
1835   unsigned ElementBase = N->getMaskElt(0);
1836 
1837   // FIXME: Handle UNDEF elements too!
1838   if (ElementBase >= 16)
1839     return false;
1840 
1841   // Check that the indices are consecutive, in the case of a multi-byte element
1842   // splatted with a v16i8 mask.
1843   for (unsigned i = 1; i != EltSize; ++i)
1844     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1845       return false;
1846 
1847   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1848     if (N->getMaskElt(i) < 0) continue;
1849     for (unsigned j = 0; j != EltSize; ++j)
1850       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1851         return false;
1852   }
1853   return true;
1854 }
1855 
1856 /// Check that the mask is shuffling N byte elements. Within each N byte
1857 /// element of the mask, the indices could be either in increasing or
1858 /// decreasing order as long as they are consecutive.
1859 /// \param[in] N the shuffle vector SD Node to analyze
1860 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1861 /// Word/DoubleWord/QuadWord).
1862 /// \param[in] StepLen the delta indices number among the N byte element, if
1863 /// the mask is in increasing/decreasing order then it is 1/-1.
1864 /// \return true iff the mask is shuffling N byte elements.
1865 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1866                                    int StepLen) {
1867   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1868          "Unexpected element width.");
1869   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1870 
1871   unsigned NumOfElem = 16 / Width;
1872   unsigned MaskVal[16]; //  Width is never greater than 16
1873   for (unsigned i = 0; i < NumOfElem; ++i) {
1874     MaskVal[0] = N->getMaskElt(i * Width);
1875     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1876       return false;
1877     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1878       return false;
1879     }
1880 
1881     for (unsigned int j = 1; j < Width; ++j) {
1882       MaskVal[j] = N->getMaskElt(i * Width + j);
1883       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1884         return false;
1885       }
1886     }
1887   }
1888 
1889   return true;
1890 }
1891 
1892 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1893                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1894   if (!isNByteElemShuffleMask(N, 4, 1))
1895     return false;
1896 
1897   // Now we look at mask elements 0,4,8,12
1898   unsigned M0 = N->getMaskElt(0) / 4;
1899   unsigned M1 = N->getMaskElt(4) / 4;
1900   unsigned M2 = N->getMaskElt(8) / 4;
1901   unsigned M3 = N->getMaskElt(12) / 4;
1902   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1903   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1904 
1905   // Below, let H and L be arbitrary elements of the shuffle mask
1906   // where H is in the range [4,7] and L is in the range [0,3].
1907   // H, 1, 2, 3 or L, 5, 6, 7
1908   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1909       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1910     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1911     InsertAtByte = IsLE ? 12 : 0;
1912     Swap = M0 < 4;
1913     return true;
1914   }
1915   // 0, H, 2, 3 or 4, L, 6, 7
1916   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1917       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1918     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1919     InsertAtByte = IsLE ? 8 : 4;
1920     Swap = M1 < 4;
1921     return true;
1922   }
1923   // 0, 1, H, 3 or 4, 5, L, 7
1924   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1925       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1926     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1927     InsertAtByte = IsLE ? 4 : 8;
1928     Swap = M2 < 4;
1929     return true;
1930   }
1931   // 0, 1, 2, H or 4, 5, 6, L
1932   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1933       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1934     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1935     InsertAtByte = IsLE ? 0 : 12;
1936     Swap = M3 < 4;
1937     return true;
1938   }
1939 
1940   // If both vector operands for the shuffle are the same vector, the mask will
1941   // contain only elements from the first one and the second one will be undef.
1942   if (N->getOperand(1).isUndef()) {
1943     ShiftElts = 0;
1944     Swap = true;
1945     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1946     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1947       InsertAtByte = IsLE ? 12 : 0;
1948       return true;
1949     }
1950     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1951       InsertAtByte = IsLE ? 8 : 4;
1952       return true;
1953     }
1954     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1955       InsertAtByte = IsLE ? 4 : 8;
1956       return true;
1957     }
1958     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1959       InsertAtByte = IsLE ? 0 : 12;
1960       return true;
1961     }
1962   }
1963 
1964   return false;
1965 }
1966 
1967 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1968                                bool &Swap, bool IsLE) {
1969   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1970   // Ensure each byte index of the word is consecutive.
1971   if (!isNByteElemShuffleMask(N, 4, 1))
1972     return false;
1973 
1974   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1975   unsigned M0 = N->getMaskElt(0) / 4;
1976   unsigned M1 = N->getMaskElt(4) / 4;
1977   unsigned M2 = N->getMaskElt(8) / 4;
1978   unsigned M3 = N->getMaskElt(12) / 4;
1979 
1980   // If both vector operands for the shuffle are the same vector, the mask will
1981   // contain only elements from the first one and the second one will be undef.
1982   if (N->getOperand(1).isUndef()) {
1983     assert(M0 < 4 && "Indexing into an undef vector?");
1984     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1985       return false;
1986 
1987     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1988     Swap = false;
1989     return true;
1990   }
1991 
1992   // Ensure each word index of the ShuffleVector Mask is consecutive.
1993   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1994     return false;
1995 
1996   if (IsLE) {
1997     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1998       // Input vectors don't need to be swapped if the leading element
1999       // of the result is one of the 3 left elements of the second vector
2000       // (or if there is no shift to be done at all).
2001       Swap = false;
2002       ShiftElts = (8 - M0) % 8;
2003     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2004       // Input vectors need to be swapped if the leading element
2005       // of the result is one of the 3 left elements of the first vector
2006       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2007       Swap = true;
2008       ShiftElts = (4 - M0) % 4;
2009     }
2010 
2011     return true;
2012   } else {                                          // BE
2013     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2014       // Input vectors don't need to be swapped if the leading element
2015       // of the result is one of the 4 elements of the first vector.
2016       Swap = false;
2017       ShiftElts = M0;
2018     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2019       // Input vectors need to be swapped if the leading element
2020       // of the result is one of the 4 elements of the right vector.
2021       Swap = true;
2022       ShiftElts = M0 - 4;
2023     }
2024 
2025     return true;
2026   }
2027 }
2028 
2029 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2030   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2031 
2032   if (!isNByteElemShuffleMask(N, Width, -1))
2033     return false;
2034 
2035   for (int i = 0; i < 16; i += Width)
2036     if (N->getMaskElt(i) != i + Width - 1)
2037       return false;
2038 
2039   return true;
2040 }
2041 
2042 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2043   return isXXBRShuffleMaskHelper(N, 2);
2044 }
2045 
2046 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2047   return isXXBRShuffleMaskHelper(N, 4);
2048 }
2049 
2050 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2051   return isXXBRShuffleMaskHelper(N, 8);
2052 }
2053 
2054 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2055   return isXXBRShuffleMaskHelper(N, 16);
2056 }
2057 
2058 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2059 /// if the inputs to the instruction should be swapped and set \p DM to the
2060 /// value for the immediate.
2061 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2062 /// AND element 0 of the result comes from the first input (LE) or second input
2063 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2064 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2065 /// mask.
2066 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2067                                bool &Swap, bool IsLE) {
2068   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2069 
2070   // Ensure each byte index of the double word is consecutive.
2071   if (!isNByteElemShuffleMask(N, 8, 1))
2072     return false;
2073 
2074   unsigned M0 = N->getMaskElt(0) / 8;
2075   unsigned M1 = N->getMaskElt(8) / 8;
2076   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2077 
2078   // If both vector operands for the shuffle are the same vector, the mask will
2079   // contain only elements from the first one and the second one will be undef.
2080   if (N->getOperand(1).isUndef()) {
2081     if ((M0 | M1) < 2) {
2082       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2083       Swap = false;
2084       return true;
2085     } else
2086       return false;
2087   }
2088 
2089   if (IsLE) {
2090     if (M0 > 1 && M1 < 2) {
2091       Swap = false;
2092     } else if (M0 < 2 && M1 > 1) {
2093       M0 = (M0 + 2) % 4;
2094       M1 = (M1 + 2) % 4;
2095       Swap = true;
2096     } else
2097       return false;
2098 
2099     // Note: if control flow comes here that means Swap is already set above
2100     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2101     return true;
2102   } else { // BE
2103     if (M0 < 2 && M1 > 1) {
2104       Swap = false;
2105     } else if (M0 > 1 && M1 < 2) {
2106       M0 = (M0 + 2) % 4;
2107       M1 = (M1 + 2) % 4;
2108       Swap = true;
2109     } else
2110       return false;
2111 
2112     // Note: if control flow comes here that means Swap is already set above
2113     DM = (M0 << 1) + (M1 & 1);
2114     return true;
2115   }
2116 }
2117 
2118 
2119 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2120 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2121 /// elements are counted from the left of the vector register).
2122 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2123                                          SelectionDAG &DAG) {
2124   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2125   assert(isSplatShuffleMask(SVOp, EltSize));
2126   if (DAG.getDataLayout().isLittleEndian())
2127     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2128   else
2129     return SVOp->getMaskElt(0) / EltSize;
2130 }
2131 
2132 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2133 /// by using a vspltis[bhw] instruction of the specified element size, return
2134 /// the constant being splatted.  The ByteSize field indicates the number of
2135 /// bytes of each element [124] -> [bhw].
2136 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2137   SDValue OpVal(nullptr, 0);
2138 
2139   // If ByteSize of the splat is bigger than the element size of the
2140   // build_vector, then we have a case where we are checking for a splat where
2141   // multiple elements of the buildvector are folded together into a single
2142   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2143   unsigned EltSize = 16/N->getNumOperands();
2144   if (EltSize < ByteSize) {
2145     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2146     SDValue UniquedVals[4];
2147     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2148 
2149     // See if all of the elements in the buildvector agree across.
2150     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2151       if (N->getOperand(i).isUndef()) continue;
2152       // If the element isn't a constant, bail fully out.
2153       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2154 
2155       if (!UniquedVals[i&(Multiple-1)].getNode())
2156         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2157       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2158         return SDValue();  // no match.
2159     }
2160 
2161     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2162     // either constant or undef values that are identical for each chunk.  See
2163     // if these chunks can form into a larger vspltis*.
2164 
2165     // Check to see if all of the leading entries are either 0 or -1.  If
2166     // neither, then this won't fit into the immediate field.
2167     bool LeadingZero = true;
2168     bool LeadingOnes = true;
2169     for (unsigned i = 0; i != Multiple-1; ++i) {
2170       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2171 
2172       LeadingZero &= isNullConstant(UniquedVals[i]);
2173       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2174     }
2175     // Finally, check the least significant entry.
2176     if (LeadingZero) {
2177       if (!UniquedVals[Multiple-1].getNode())
2178         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2179       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2180       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2181         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2182     }
2183     if (LeadingOnes) {
2184       if (!UniquedVals[Multiple-1].getNode())
2185         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2186       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2187       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2188         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2189     }
2190 
2191     return SDValue();
2192   }
2193 
2194   // Check to see if this buildvec has a single non-undef value in its elements.
2195   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2196     if (N->getOperand(i).isUndef()) continue;
2197     if (!OpVal.getNode())
2198       OpVal = N->getOperand(i);
2199     else if (OpVal != N->getOperand(i))
2200       return SDValue();
2201   }
2202 
2203   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2204 
2205   unsigned ValSizeInBytes = EltSize;
2206   uint64_t Value = 0;
2207   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2208     Value = CN->getZExtValue();
2209   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2210     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2211     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2212   }
2213 
2214   // If the splat value is larger than the element value, then we can never do
2215   // this splat.  The only case that we could fit the replicated bits into our
2216   // immediate field for would be zero, and we prefer to use vxor for it.
2217   if (ValSizeInBytes < ByteSize) return SDValue();
2218 
2219   // If the element value is larger than the splat value, check if it consists
2220   // of a repeated bit pattern of size ByteSize.
2221   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2222     return SDValue();
2223 
2224   // Properly sign extend the value.
2225   int MaskVal = SignExtend32(Value, ByteSize * 8);
2226 
2227   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2228   if (MaskVal == 0) return SDValue();
2229 
2230   // Finally, if this value fits in a 5 bit sext field, return it
2231   if (SignExtend32<5>(MaskVal) == MaskVal)
2232     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2233   return SDValue();
2234 }
2235 
2236 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2237 /// amount, otherwise return -1.
2238 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2239   EVT VT = N->getValueType(0);
2240   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2241     return -1;
2242 
2243   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2244 
2245   // Find the first non-undef value in the shuffle mask.
2246   unsigned i;
2247   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2248     /*search*/;
2249 
2250   if (i == 4) return -1;  // all undef.
2251 
2252   // Otherwise, check to see if the rest of the elements are consecutively
2253   // numbered from this value.
2254   unsigned ShiftAmt = SVOp->getMaskElt(i);
2255   if (ShiftAmt < i) return -1;
2256   ShiftAmt -= i;
2257 
2258   // Check the rest of the elements to see if they are consecutive.
2259   for (++i; i != 4; ++i)
2260     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2261       return -1;
2262 
2263   return ShiftAmt;
2264 }
2265 
2266 //===----------------------------------------------------------------------===//
2267 //  Addressing Mode Selection
2268 //===----------------------------------------------------------------------===//
2269 
2270 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2271 /// or 64-bit immediate, and if the value can be accurately represented as a
2272 /// sign extension from a 16-bit value.  If so, this returns true and the
2273 /// immediate.
2274 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2275   if (!isa<ConstantSDNode>(N))
2276     return false;
2277 
2278   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2279   if (N->getValueType(0) == MVT::i32)
2280     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2281   else
2282     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2283 }
2284 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2285   return isIntS16Immediate(Op.getNode(), Imm);
2286 }
2287 
2288 
2289 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2290 /// be represented as an indexed [r+r] operation.
2291 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2292                                                SDValue &Index,
2293                                                SelectionDAG &DAG) const {
2294   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2295       UI != E; ++UI) {
2296     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2297       if (Memop->getMemoryVT() == MVT::f64) {
2298           Base = N.getOperand(0);
2299           Index = N.getOperand(1);
2300           return true;
2301       }
2302     }
2303   }
2304   return false;
2305 }
2306 
2307 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2308 /// can be represented as an indexed [r+r] operation.  Returns false if it
2309 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2310 /// non-zero and N can be represented by a base register plus a signed 16-bit
2311 /// displacement, make a more precise judgement by checking (displacement % \p
2312 /// EncodingAlignment).
2313 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2314                                             SDValue &Index, SelectionDAG &DAG,
2315                                             unsigned EncodingAlignment) const {
2316   int16_t imm = 0;
2317   if (N.getOpcode() == ISD::ADD) {
2318     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2319     // SPE load/store can only handle 8-bit offsets.
2320     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2321         return true;
2322     if (isIntS16Immediate(N.getOperand(1), imm) &&
2323         (!EncodingAlignment || !(imm % EncodingAlignment)))
2324       return false; // r+i
2325     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2326       return false;    // r+i
2327 
2328     Base = N.getOperand(0);
2329     Index = N.getOperand(1);
2330     return true;
2331   } else if (N.getOpcode() == ISD::OR) {
2332     if (isIntS16Immediate(N.getOperand(1), imm) &&
2333         (!EncodingAlignment || !(imm % EncodingAlignment)))
2334       return false; // r+i can fold it if we can.
2335 
2336     // If this is an or of disjoint bitfields, we can codegen this as an add
2337     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2338     // disjoint.
2339     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2340 
2341     if (LHSKnown.Zero.getBoolValue()) {
2342       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2343       // If all of the bits are known zero on the LHS or RHS, the add won't
2344       // carry.
2345       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2346         Base = N.getOperand(0);
2347         Index = N.getOperand(1);
2348         return true;
2349       }
2350     }
2351   }
2352 
2353   return false;
2354 }
2355 
2356 // If we happen to be doing an i64 load or store into a stack slot that has
2357 // less than a 4-byte alignment, then the frame-index elimination may need to
2358 // use an indexed load or store instruction (because the offset may not be a
2359 // multiple of 4). The extra register needed to hold the offset comes from the
2360 // register scavenger, and it is possible that the scavenger will need to use
2361 // an emergency spill slot. As a result, we need to make sure that a spill slot
2362 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2363 // stack slot.
2364 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2365   // FIXME: This does not handle the LWA case.
2366   if (VT != MVT::i64)
2367     return;
2368 
2369   // NOTE: We'll exclude negative FIs here, which come from argument
2370   // lowering, because there are no known test cases triggering this problem
2371   // using packed structures (or similar). We can remove this exclusion if
2372   // we find such a test case. The reason why this is so test-case driven is
2373   // because this entire 'fixup' is only to prevent crashes (from the
2374   // register scavenger) on not-really-valid inputs. For example, if we have:
2375   //   %a = alloca i1
2376   //   %b = bitcast i1* %a to i64*
2377   //   store i64* a, i64 b
2378   // then the store should really be marked as 'align 1', but is not. If it
2379   // were marked as 'align 1' then the indexed form would have been
2380   // instruction-selected initially, and the problem this 'fixup' is preventing
2381   // won't happen regardless.
2382   if (FrameIdx < 0)
2383     return;
2384 
2385   MachineFunction &MF = DAG.getMachineFunction();
2386   MachineFrameInfo &MFI = MF.getFrameInfo();
2387 
2388   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2389   if (Align >= 4)
2390     return;
2391 
2392   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2393   FuncInfo->setHasNonRISpills();
2394 }
2395 
2396 /// Returns true if the address N can be represented by a base register plus
2397 /// a signed 16-bit displacement [r+imm], and if it is not better
2398 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2399 /// displacements that are multiples of that value.
2400 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2401                                             SDValue &Base,
2402                                             SelectionDAG &DAG,
2403                                             unsigned EncodingAlignment) const {
2404   // FIXME dl should come from parent load or store, not from address
2405   SDLoc dl(N);
2406   // If this can be more profitably realized as r+r, fail.
2407   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2408     return false;
2409 
2410   if (N.getOpcode() == ISD::ADD) {
2411     int16_t imm = 0;
2412     if (isIntS16Immediate(N.getOperand(1), imm) &&
2413         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2414       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2415       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2416         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2417         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2418       } else {
2419         Base = N.getOperand(0);
2420       }
2421       return true; // [r+i]
2422     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2423       // Match LOAD (ADD (X, Lo(G))).
2424       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2425              && "Cannot handle constant offsets yet!");
2426       Disp = N.getOperand(1).getOperand(0);  // The global address.
2427       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2428              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2429              Disp.getOpcode() == ISD::TargetConstantPool ||
2430              Disp.getOpcode() == ISD::TargetJumpTable);
2431       Base = N.getOperand(0);
2432       return true;  // [&g+r]
2433     }
2434   } else if (N.getOpcode() == ISD::OR) {
2435     int16_t imm = 0;
2436     if (isIntS16Immediate(N.getOperand(1), imm) &&
2437         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2438       // If this is an or of disjoint bitfields, we can codegen this as an add
2439       // (for better address arithmetic) if the LHS and RHS of the OR are
2440       // provably disjoint.
2441       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2442 
2443       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2444         // If all of the bits are known zero on the LHS or RHS, the add won't
2445         // carry.
2446         if (FrameIndexSDNode *FI =
2447               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2448           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2449           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2450         } else {
2451           Base = N.getOperand(0);
2452         }
2453         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2454         return true;
2455       }
2456     }
2457   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2458     // Loading from a constant address.
2459 
2460     // If this address fits entirely in a 16-bit sext immediate field, codegen
2461     // this as "d, 0"
2462     int16_t Imm;
2463     if (isIntS16Immediate(CN, Imm) &&
2464         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2465       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2466       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2467                              CN->getValueType(0));
2468       return true;
2469     }
2470 
2471     // Handle 32-bit sext immediates with LIS + addr mode.
2472     if ((CN->getValueType(0) == MVT::i32 ||
2473          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2474         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2475       int Addr = (int)CN->getZExtValue();
2476 
2477       // Otherwise, break this down into an LIS + disp.
2478       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2479 
2480       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2481                                    MVT::i32);
2482       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2483       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2484       return true;
2485     }
2486   }
2487 
2488   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2489   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2490     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2491     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2492   } else
2493     Base = N;
2494   return true;      // [r+0]
2495 }
2496 
2497 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2498 /// represented as an indexed [r+r] operation.
2499 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2500                                                 SDValue &Index,
2501                                                 SelectionDAG &DAG) const {
2502   // Check to see if we can easily represent this as an [r+r] address.  This
2503   // will fail if it thinks that the address is more profitably represented as
2504   // reg+imm, e.g. where imm = 0.
2505   if (SelectAddressRegReg(N, Base, Index, DAG))
2506     return true;
2507 
2508   // If the address is the result of an add, we will utilize the fact that the
2509   // address calculation includes an implicit add.  However, we can reduce
2510   // register pressure if we do not materialize a constant just for use as the
2511   // index register.  We only get rid of the add if it is not an add of a
2512   // value and a 16-bit signed constant and both have a single use.
2513   int16_t imm = 0;
2514   if (N.getOpcode() == ISD::ADD &&
2515       (!isIntS16Immediate(N.getOperand(1), imm) ||
2516        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2517     Base = N.getOperand(0);
2518     Index = N.getOperand(1);
2519     return true;
2520   }
2521 
2522   // Otherwise, do it the hard way, using R0 as the base register.
2523   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2524                          N.getValueType());
2525   Index = N;
2526   return true;
2527 }
2528 
2529 /// Returns true if we should use a direct load into vector instruction
2530 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2531 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2532 
2533   // If there are any other uses other than scalar to vector, then we should
2534   // keep it as a scalar load -> direct move pattern to prevent multiple
2535   // loads.
2536   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2537   if (!LD)
2538     return false;
2539 
2540   EVT MemVT = LD->getMemoryVT();
2541   if (!MemVT.isSimple())
2542     return false;
2543   switch(MemVT.getSimpleVT().SimpleTy) {
2544   case MVT::i64:
2545     break;
2546   case MVT::i32:
2547     if (!ST.hasP8Vector())
2548       return false;
2549     break;
2550   case MVT::i16:
2551   case MVT::i8:
2552     if (!ST.hasP9Vector())
2553       return false;
2554     break;
2555   default:
2556     return false;
2557   }
2558 
2559   SDValue LoadedVal(N, 0);
2560   if (!LoadedVal.hasOneUse())
2561     return false;
2562 
2563   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2564        UI != UE; ++UI)
2565     if (UI.getUse().get().getResNo() == 0 &&
2566         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2567       return false;
2568 
2569   return true;
2570 }
2571 
2572 /// getPreIndexedAddressParts - returns true by value, base pointer and
2573 /// offset pointer and addressing mode by reference if the node's address
2574 /// can be legally represented as pre-indexed load / store address.
2575 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2576                                                   SDValue &Offset,
2577                                                   ISD::MemIndexedMode &AM,
2578                                                   SelectionDAG &DAG) const {
2579   if (DisablePPCPreinc) return false;
2580 
2581   bool isLoad = true;
2582   SDValue Ptr;
2583   EVT VT;
2584   unsigned Alignment;
2585   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2586     Ptr = LD->getBasePtr();
2587     VT = LD->getMemoryVT();
2588     Alignment = LD->getAlignment();
2589   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2590     Ptr = ST->getBasePtr();
2591     VT  = ST->getMemoryVT();
2592     Alignment = ST->getAlignment();
2593     isLoad = false;
2594   } else
2595     return false;
2596 
2597   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2598   // instructions because we can fold these into a more efficient instruction
2599   // instead, (such as LXSD).
2600   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2601     return false;
2602   }
2603 
2604   // PowerPC doesn't have preinc load/store instructions for vectors (except
2605   // for QPX, which does have preinc r+r forms).
2606   if (VT.isVector()) {
2607     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2608       return false;
2609     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2610       AM = ISD::PRE_INC;
2611       return true;
2612     }
2613   }
2614 
2615   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2616     // Common code will reject creating a pre-inc form if the base pointer
2617     // is a frame index, or if N is a store and the base pointer is either
2618     // the same as or a predecessor of the value being stored.  Check for
2619     // those situations here, and try with swapped Base/Offset instead.
2620     bool Swap = false;
2621 
2622     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2623       Swap = true;
2624     else if (!isLoad) {
2625       SDValue Val = cast<StoreSDNode>(N)->getValue();
2626       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2627         Swap = true;
2628     }
2629 
2630     if (Swap)
2631       std::swap(Base, Offset);
2632 
2633     AM = ISD::PRE_INC;
2634     return true;
2635   }
2636 
2637   // LDU/STU can only handle immediates that are a multiple of 4.
2638   if (VT != MVT::i64) {
2639     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2640       return false;
2641   } else {
2642     // LDU/STU need an address with at least 4-byte alignment.
2643     if (Alignment < 4)
2644       return false;
2645 
2646     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2647       return false;
2648   }
2649 
2650   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2651     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2652     // sext i32 to i64 when addr mode is r+i.
2653     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2654         LD->getExtensionType() == ISD::SEXTLOAD &&
2655         isa<ConstantSDNode>(Offset))
2656       return false;
2657   }
2658 
2659   AM = ISD::PRE_INC;
2660   return true;
2661 }
2662 
2663 //===----------------------------------------------------------------------===//
2664 //  LowerOperation implementation
2665 //===----------------------------------------------------------------------===//
2666 
2667 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2668 /// and LoOpFlags to the target MO flags.
2669 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2670                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2671                                const GlobalValue *GV = nullptr) {
2672   HiOpFlags = PPCII::MO_HA;
2673   LoOpFlags = PPCII::MO_LO;
2674 
2675   // Don't use the pic base if not in PIC relocation model.
2676   if (IsPIC) {
2677     HiOpFlags |= PPCII::MO_PIC_FLAG;
2678     LoOpFlags |= PPCII::MO_PIC_FLAG;
2679   }
2680 }
2681 
2682 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2683                              SelectionDAG &DAG) {
2684   SDLoc DL(HiPart);
2685   EVT PtrVT = HiPart.getValueType();
2686   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2687 
2688   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2689   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2690 
2691   // With PIC, the first instruction is actually "GR+hi(&G)".
2692   if (isPIC)
2693     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2694                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2695 
2696   // Generate non-pic code that has direct accesses to the constant pool.
2697   // The address of the global is just (hi(&g)+lo(&g)).
2698   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2699 }
2700 
2701 static void setUsesTOCBasePtr(MachineFunction &MF) {
2702   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2703   FuncInfo->setUsesTOCBasePtr();
2704 }
2705 
2706 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2707   setUsesTOCBasePtr(DAG.getMachineFunction());
2708 }
2709 
2710 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2711                                        SDValue GA) const {
2712   const bool Is64Bit = Subtarget.isPPC64();
2713   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2714   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2715                         : Subtarget.isAIXABI()
2716                               ? DAG.getRegister(PPC::R2, VT)
2717                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2718   SDValue Ops[] = { GA, Reg };
2719   return DAG.getMemIntrinsicNode(
2720       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2721       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2722       MachineMemOperand::MOLoad);
2723 }
2724 
2725 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2726                                              SelectionDAG &DAG) const {
2727   EVT PtrVT = Op.getValueType();
2728   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2729   const Constant *C = CP->getConstVal();
2730 
2731   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2732   // The actual address of the GlobalValue is stored in the TOC.
2733   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2734     setUsesTOCBasePtr(DAG);
2735     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2736     return getTOCEntry(DAG, SDLoc(CP), GA);
2737   }
2738 
2739   unsigned MOHiFlag, MOLoFlag;
2740   bool IsPIC = isPositionIndependent();
2741   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2742 
2743   if (IsPIC && Subtarget.isSVR4ABI()) {
2744     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2745                                            PPCII::MO_PIC_FLAG);
2746     return getTOCEntry(DAG, SDLoc(CP), GA);
2747   }
2748 
2749   SDValue CPIHi =
2750     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2751   SDValue CPILo =
2752     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2753   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2754 }
2755 
2756 // For 64-bit PowerPC, prefer the more compact relative encodings.
2757 // This trades 32 bits per jump table entry for one or two instructions
2758 // on the jump site.
2759 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2760   if (isJumpTableRelative())
2761     return MachineJumpTableInfo::EK_LabelDifference32;
2762 
2763   return TargetLowering::getJumpTableEncoding();
2764 }
2765 
2766 bool PPCTargetLowering::isJumpTableRelative() const {
2767   if (UseAbsoluteJumpTables)
2768     return false;
2769   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2770     return true;
2771   return TargetLowering::isJumpTableRelative();
2772 }
2773 
2774 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2775                                                     SelectionDAG &DAG) const {
2776   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2777     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2778 
2779   switch (getTargetMachine().getCodeModel()) {
2780   case CodeModel::Small:
2781   case CodeModel::Medium:
2782     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2783   default:
2784     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2785                        getPointerTy(DAG.getDataLayout()));
2786   }
2787 }
2788 
2789 const MCExpr *
2790 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2791                                                 unsigned JTI,
2792                                                 MCContext &Ctx) const {
2793   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2794     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2795 
2796   switch (getTargetMachine().getCodeModel()) {
2797   case CodeModel::Small:
2798   case CodeModel::Medium:
2799     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2800   default:
2801     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2802   }
2803 }
2804 
2805 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2806   EVT PtrVT = Op.getValueType();
2807   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2808 
2809   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2810   // The actual address of the GlobalValue is stored in the TOC.
2811   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2812     setUsesTOCBasePtr(DAG);
2813     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2814     return getTOCEntry(DAG, SDLoc(JT), GA);
2815   }
2816 
2817   unsigned MOHiFlag, MOLoFlag;
2818   bool IsPIC = isPositionIndependent();
2819   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2820 
2821   if (IsPIC && Subtarget.isSVR4ABI()) {
2822     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2823                                         PPCII::MO_PIC_FLAG);
2824     return getTOCEntry(DAG, SDLoc(GA), GA);
2825   }
2826 
2827   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2828   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2829   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2830 }
2831 
2832 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2833                                              SelectionDAG &DAG) const {
2834   EVT PtrVT = Op.getValueType();
2835   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2836   const BlockAddress *BA = BASDN->getBlockAddress();
2837 
2838   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2839   // The actual BlockAddress is stored in the TOC.
2840   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2841     setUsesTOCBasePtr(DAG);
2842     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2843     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2844   }
2845 
2846   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2847   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2848     return getTOCEntry(
2849         DAG, SDLoc(BASDN),
2850         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2851 
2852   unsigned MOHiFlag, MOLoFlag;
2853   bool IsPIC = isPositionIndependent();
2854   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2855   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2856   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2857   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2858 }
2859 
2860 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2861                                               SelectionDAG &DAG) const {
2862   // FIXME: TLS addresses currently use medium model code sequences,
2863   // which is the most useful form.  Eventually support for small and
2864   // large models could be added if users need it, at the cost of
2865   // additional complexity.
2866   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2867   if (DAG.getTarget().useEmulatedTLS())
2868     return LowerToTLSEmulatedModel(GA, DAG);
2869 
2870   SDLoc dl(GA);
2871   const GlobalValue *GV = GA->getGlobal();
2872   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2873   bool is64bit = Subtarget.isPPC64();
2874   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2875   PICLevel::Level picLevel = M->getPICLevel();
2876 
2877   const TargetMachine &TM = getTargetMachine();
2878   TLSModel::Model Model = TM.getTLSModel(GV);
2879 
2880   if (Model == TLSModel::LocalExec) {
2881     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2882                                                PPCII::MO_TPREL_HA);
2883     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2884                                                PPCII::MO_TPREL_LO);
2885     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2886                              : DAG.getRegister(PPC::R2, MVT::i32);
2887 
2888     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2889     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2890   }
2891 
2892   if (Model == TLSModel::InitialExec) {
2893     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2894     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2895                                                 PPCII::MO_TLS);
2896     SDValue GOTPtr;
2897     if (is64bit) {
2898       setUsesTOCBasePtr(DAG);
2899       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2900       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2901                            PtrVT, GOTReg, TGA);
2902     } else {
2903       if (!TM.isPositionIndependent())
2904         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2905       else if (picLevel == PICLevel::SmallPIC)
2906         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2907       else
2908         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2909     }
2910     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2911                                    PtrVT, TGA, GOTPtr);
2912     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2913   }
2914 
2915   if (Model == TLSModel::GeneralDynamic) {
2916     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2917     SDValue GOTPtr;
2918     if (is64bit) {
2919       setUsesTOCBasePtr(DAG);
2920       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2921       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2922                                    GOTReg, TGA);
2923     } else {
2924       if (picLevel == PICLevel::SmallPIC)
2925         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2926       else
2927         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2928     }
2929     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2930                        GOTPtr, TGA, TGA);
2931   }
2932 
2933   if (Model == TLSModel::LocalDynamic) {
2934     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2935     SDValue GOTPtr;
2936     if (is64bit) {
2937       setUsesTOCBasePtr(DAG);
2938       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2939       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2940                            GOTReg, TGA);
2941     } else {
2942       if (picLevel == PICLevel::SmallPIC)
2943         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2944       else
2945         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2946     }
2947     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2948                                   PtrVT, GOTPtr, TGA, TGA);
2949     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2950                                       PtrVT, TLSAddr, TGA);
2951     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2952   }
2953 
2954   llvm_unreachable("Unknown TLS model!");
2955 }
2956 
2957 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2958                                               SelectionDAG &DAG) const {
2959   EVT PtrVT = Op.getValueType();
2960   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2961   SDLoc DL(GSDN);
2962   const GlobalValue *GV = GSDN->getGlobal();
2963 
2964   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
2965   // The actual address of the GlobalValue is stored in the TOC.
2966   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2967     setUsesTOCBasePtr(DAG);
2968     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2969     return getTOCEntry(DAG, DL, GA);
2970   }
2971 
2972   unsigned MOHiFlag, MOLoFlag;
2973   bool IsPIC = isPositionIndependent();
2974   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2975 
2976   if (IsPIC && Subtarget.isSVR4ABI()) {
2977     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2978                                             GSDN->getOffset(),
2979                                             PPCII::MO_PIC_FLAG);
2980     return getTOCEntry(DAG, DL, GA);
2981   }
2982 
2983   SDValue GAHi =
2984     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2985   SDValue GALo =
2986     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2987 
2988   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2989 }
2990 
2991 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2992   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2993   SDLoc dl(Op);
2994 
2995   if (Op.getValueType() == MVT::v2i64) {
2996     // When the operands themselves are v2i64 values, we need to do something
2997     // special because VSX has no underlying comparison operations for these.
2998     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2999       // Equality can be handled by casting to the legal type for Altivec
3000       // comparisons, everything else needs to be expanded.
3001       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3002         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3003                  DAG.getSetCC(dl, MVT::v4i32,
3004                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3005                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3006                    CC));
3007       }
3008 
3009       return SDValue();
3010     }
3011 
3012     // We handle most of these in the usual way.
3013     return Op;
3014   }
3015 
3016   // If we're comparing for equality to zero, expose the fact that this is
3017   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3018   // fold the new nodes.
3019   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3020     return V;
3021 
3022   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3023     // Leave comparisons against 0 and -1 alone for now, since they're usually
3024     // optimized.  FIXME: revisit this when we can custom lower all setcc
3025     // optimizations.
3026     if (C->isAllOnesValue() || C->isNullValue())
3027       return SDValue();
3028   }
3029 
3030   // If we have an integer seteq/setne, turn it into a compare against zero
3031   // by xor'ing the rhs with the lhs, which is faster than setting a
3032   // condition register, reading it back out, and masking the correct bit.  The
3033   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3034   // the result to other bit-twiddling opportunities.
3035   EVT LHSVT = Op.getOperand(0).getValueType();
3036   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3037     EVT VT = Op.getValueType();
3038     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3039                                 Op.getOperand(1));
3040     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3041   }
3042   return SDValue();
3043 }
3044 
3045 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3046   SDNode *Node = Op.getNode();
3047   EVT VT = Node->getValueType(0);
3048   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3049   SDValue InChain = Node->getOperand(0);
3050   SDValue VAListPtr = Node->getOperand(1);
3051   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3052   SDLoc dl(Node);
3053 
3054   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3055 
3056   // gpr_index
3057   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3058                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3059   InChain = GprIndex.getValue(1);
3060 
3061   if (VT == MVT::i64) {
3062     // Check if GprIndex is even
3063     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3064                                  DAG.getConstant(1, dl, MVT::i32));
3065     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3066                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3067     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3068                                           DAG.getConstant(1, dl, MVT::i32));
3069     // Align GprIndex to be even if it isn't
3070     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3071                            GprIndex);
3072   }
3073 
3074   // fpr index is 1 byte after gpr
3075   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3076                                DAG.getConstant(1, dl, MVT::i32));
3077 
3078   // fpr
3079   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3080                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3081   InChain = FprIndex.getValue(1);
3082 
3083   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3084                                        DAG.getConstant(8, dl, MVT::i32));
3085 
3086   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3087                                         DAG.getConstant(4, dl, MVT::i32));
3088 
3089   // areas
3090   SDValue OverflowArea =
3091       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3092   InChain = OverflowArea.getValue(1);
3093 
3094   SDValue RegSaveArea =
3095       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3096   InChain = RegSaveArea.getValue(1);
3097 
3098   // select overflow_area if index > 8
3099   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3100                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3101 
3102   // adjustment constant gpr_index * 4/8
3103   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3104                                     VT.isInteger() ? GprIndex : FprIndex,
3105                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3106                                                     MVT::i32));
3107 
3108   // OurReg = RegSaveArea + RegConstant
3109   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3110                                RegConstant);
3111 
3112   // Floating types are 32 bytes into RegSaveArea
3113   if (VT.isFloatingPoint())
3114     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3115                          DAG.getConstant(32, dl, MVT::i32));
3116 
3117   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3118   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3119                                    VT.isInteger() ? GprIndex : FprIndex,
3120                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3121                                                    MVT::i32));
3122 
3123   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3124                               VT.isInteger() ? VAListPtr : FprPtr,
3125                               MachinePointerInfo(SV), MVT::i8);
3126 
3127   // determine if we should load from reg_save_area or overflow_area
3128   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3129 
3130   // increase overflow_area by 4/8 if gpr/fpr > 8
3131   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3132                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3133                                           dl, MVT::i32));
3134 
3135   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3136                              OverflowAreaPlusN);
3137 
3138   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3139                               MachinePointerInfo(), MVT::i32);
3140 
3141   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3142 }
3143 
3144 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3145   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3146 
3147   // We have to copy the entire va_list struct:
3148   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3149   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3150                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3151                        false, true, false, MachinePointerInfo(),
3152                        MachinePointerInfo());
3153 }
3154 
3155 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3156                                                   SelectionDAG &DAG) const {
3157   if (Subtarget.isAIXABI())
3158     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3159 
3160   return Op.getOperand(0);
3161 }
3162 
3163 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3164                                                 SelectionDAG &DAG) const {
3165   if (Subtarget.isAIXABI())
3166     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3167 
3168   SDValue Chain = Op.getOperand(0);
3169   SDValue Trmp = Op.getOperand(1); // trampoline
3170   SDValue FPtr = Op.getOperand(2); // nested function
3171   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3172   SDLoc dl(Op);
3173 
3174   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3175   bool isPPC64 = (PtrVT == MVT::i64);
3176   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3177 
3178   TargetLowering::ArgListTy Args;
3179   TargetLowering::ArgListEntry Entry;
3180 
3181   Entry.Ty = IntPtrTy;
3182   Entry.Node = Trmp; Args.push_back(Entry);
3183 
3184   // TrampSize == (isPPC64 ? 48 : 40);
3185   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3186                                isPPC64 ? MVT::i64 : MVT::i32);
3187   Args.push_back(Entry);
3188 
3189   Entry.Node = FPtr; Args.push_back(Entry);
3190   Entry.Node = Nest; Args.push_back(Entry);
3191 
3192   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3193   TargetLowering::CallLoweringInfo CLI(DAG);
3194   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3195       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3196       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3197 
3198   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3199   return CallResult.second;
3200 }
3201 
3202 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3203   MachineFunction &MF = DAG.getMachineFunction();
3204   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3205   EVT PtrVT = getPointerTy(MF.getDataLayout());
3206 
3207   SDLoc dl(Op);
3208 
3209   if (Subtarget.isPPC64()) {
3210     // vastart just stores the address of the VarArgsFrameIndex slot into the
3211     // memory location argument.
3212     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3213     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3214     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3215                         MachinePointerInfo(SV));
3216   }
3217 
3218   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3219   // We suppose the given va_list is already allocated.
3220   //
3221   // typedef struct {
3222   //  char gpr;     /* index into the array of 8 GPRs
3223   //                 * stored in the register save area
3224   //                 * gpr=0 corresponds to r3,
3225   //                 * gpr=1 to r4, etc.
3226   //                 */
3227   //  char fpr;     /* index into the array of 8 FPRs
3228   //                 * stored in the register save area
3229   //                 * fpr=0 corresponds to f1,
3230   //                 * fpr=1 to f2, etc.
3231   //                 */
3232   //  char *overflow_arg_area;
3233   //                /* location on stack that holds
3234   //                 * the next overflow argument
3235   //                 */
3236   //  char *reg_save_area;
3237   //               /* where r3:r10 and f1:f8 (if saved)
3238   //                * are stored
3239   //                */
3240   // } va_list[1];
3241 
3242   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3243   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3244   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3245                                             PtrVT);
3246   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3247                                  PtrVT);
3248 
3249   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3250   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3251 
3252   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3253   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3254 
3255   uint64_t FPROffset = 1;
3256   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3257 
3258   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3259 
3260   // Store first byte : number of int regs
3261   SDValue firstStore =
3262       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3263                         MachinePointerInfo(SV), MVT::i8);
3264   uint64_t nextOffset = FPROffset;
3265   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3266                                   ConstFPROffset);
3267 
3268   // Store second byte : number of float regs
3269   SDValue secondStore =
3270       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3271                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3272   nextOffset += StackOffset;
3273   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3274 
3275   // Store second word : arguments given on stack
3276   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3277                                     MachinePointerInfo(SV, nextOffset));
3278   nextOffset += FrameOffset;
3279   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3280 
3281   // Store third word : arguments given in registers
3282   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3283                       MachinePointerInfo(SV, nextOffset));
3284 }
3285 
3286 /// FPR - The set of FP registers that should be allocated for arguments
3287 /// on Darwin and AIX.
3288 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3289                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3290                                 PPC::F11, PPC::F12, PPC::F13};
3291 
3292 /// QFPR - The set of QPX registers that should be allocated for arguments.
3293 static const MCPhysReg QFPR[] = {
3294     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3295     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3296 
3297 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3298 /// the stack.
3299 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3300                                        unsigned PtrByteSize) {
3301   unsigned ArgSize = ArgVT.getStoreSize();
3302   if (Flags.isByVal())
3303     ArgSize = Flags.getByValSize();
3304 
3305   // Round up to multiples of the pointer size, except for array members,
3306   // which are always packed.
3307   if (!Flags.isInConsecutiveRegs())
3308     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3309 
3310   return ArgSize;
3311 }
3312 
3313 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3314 /// on the stack.
3315 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3316                                          ISD::ArgFlagsTy Flags,
3317                                          unsigned PtrByteSize) {
3318   Align Alignment(PtrByteSize);
3319 
3320   // Altivec parameters are padded to a 16 byte boundary.
3321   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3322       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3323       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3324       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3325     Alignment = Align(16);
3326   // QPX vector types stored in double-precision are padded to a 32 byte
3327   // boundary.
3328   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3329     Alignment = Align(32);
3330 
3331   // ByVal parameters are aligned as requested.
3332   if (Flags.isByVal()) {
3333     auto BVAlign = Flags.getNonZeroByValAlign();
3334     if (BVAlign > PtrByteSize) {
3335       if (BVAlign.value() % PtrByteSize != 0)
3336         llvm_unreachable(
3337             "ByVal alignment is not a multiple of the pointer size");
3338 
3339       Alignment = BVAlign;
3340     }
3341   }
3342 
3343   // Array members are always packed to their original alignment.
3344   if (Flags.isInConsecutiveRegs()) {
3345     // If the array member was split into multiple registers, the first
3346     // needs to be aligned to the size of the full type.  (Except for
3347     // ppcf128, which is only aligned as its f64 components.)
3348     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3349       Alignment = Align(OrigVT.getStoreSize());
3350     else
3351       Alignment = Align(ArgVT.getStoreSize());
3352   }
3353 
3354   return Alignment;
3355 }
3356 
3357 /// CalculateStackSlotUsed - Return whether this argument will use its
3358 /// stack slot (instead of being passed in registers).  ArgOffset,
3359 /// AvailableFPRs, and AvailableVRs must hold the current argument
3360 /// position, and will be updated to account for this argument.
3361 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3362                                    ISD::ArgFlagsTy Flags,
3363                                    unsigned PtrByteSize,
3364                                    unsigned LinkageSize,
3365                                    unsigned ParamAreaSize,
3366                                    unsigned &ArgOffset,
3367                                    unsigned &AvailableFPRs,
3368                                    unsigned &AvailableVRs, bool HasQPX) {
3369   bool UseMemory = false;
3370 
3371   // Respect alignment of argument on the stack.
3372   Align Alignment =
3373       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3374   ArgOffset = alignTo(ArgOffset, Alignment);
3375   // If there's no space left in the argument save area, we must
3376   // use memory (this check also catches zero-sized arguments).
3377   if (ArgOffset >= LinkageSize + ParamAreaSize)
3378     UseMemory = true;
3379 
3380   // Allocate argument on the stack.
3381   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3382   if (Flags.isInConsecutiveRegsLast())
3383     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3384   // If we overran the argument save area, we must use memory
3385   // (this check catches arguments passed partially in memory)
3386   if (ArgOffset > LinkageSize + ParamAreaSize)
3387     UseMemory = true;
3388 
3389   // However, if the argument is actually passed in an FPR or a VR,
3390   // we don't use memory after all.
3391   if (!Flags.isByVal()) {
3392     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3393         // QPX registers overlap with the scalar FP registers.
3394         (HasQPX && (ArgVT == MVT::v4f32 ||
3395                     ArgVT == MVT::v4f64 ||
3396                     ArgVT == MVT::v4i1)))
3397       if (AvailableFPRs > 0) {
3398         --AvailableFPRs;
3399         return false;
3400       }
3401     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3402         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3403         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3404         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3405       if (AvailableVRs > 0) {
3406         --AvailableVRs;
3407         return false;
3408       }
3409   }
3410 
3411   return UseMemory;
3412 }
3413 
3414 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3415 /// ensure minimum alignment required for target.
3416 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3417                                      unsigned NumBytes) {
3418   unsigned TargetAlign = Lowering->getStackAlignment();
3419   unsigned AlignMask = TargetAlign - 1;
3420   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3421   return NumBytes;
3422 }
3423 
3424 SDValue PPCTargetLowering::LowerFormalArguments(
3425     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3426     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3427     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3428   if (Subtarget.isAIXABI())
3429     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3430                                     InVals);
3431   if (Subtarget.is64BitELFABI())
3432     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3433                                        InVals);
3434   if (Subtarget.is32BitELFABI())
3435     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3436                                        InVals);
3437 
3438   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3439                                      InVals);
3440 }
3441 
3442 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3443     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3444     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3445     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3446 
3447   // 32-bit SVR4 ABI Stack Frame Layout:
3448   //              +-----------------------------------+
3449   //        +-->  |            Back chain             |
3450   //        |     +-----------------------------------+
3451   //        |     | Floating-point register save area |
3452   //        |     +-----------------------------------+
3453   //        |     |    General register save area     |
3454   //        |     +-----------------------------------+
3455   //        |     |          CR save word             |
3456   //        |     +-----------------------------------+
3457   //        |     |         VRSAVE save word          |
3458   //        |     +-----------------------------------+
3459   //        |     |         Alignment padding         |
3460   //        |     +-----------------------------------+
3461   //        |     |     Vector register save area     |
3462   //        |     +-----------------------------------+
3463   //        |     |       Local variable space        |
3464   //        |     +-----------------------------------+
3465   //        |     |        Parameter list area        |
3466   //        |     +-----------------------------------+
3467   //        |     |           LR save word            |
3468   //        |     +-----------------------------------+
3469   // SP-->  +---  |            Back chain             |
3470   //              +-----------------------------------+
3471   //
3472   // Specifications:
3473   //   System V Application Binary Interface PowerPC Processor Supplement
3474   //   AltiVec Technology Programming Interface Manual
3475 
3476   MachineFunction &MF = DAG.getMachineFunction();
3477   MachineFrameInfo &MFI = MF.getFrameInfo();
3478   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3479 
3480   EVT PtrVT = getPointerTy(MF.getDataLayout());
3481   // Potential tail calls could cause overwriting of argument stack slots.
3482   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3483                        (CallConv == CallingConv::Fast));
3484   unsigned PtrByteSize = 4;
3485 
3486   // Assign locations to all of the incoming arguments.
3487   SmallVector<CCValAssign, 16> ArgLocs;
3488   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3489                  *DAG.getContext());
3490 
3491   // Reserve space for the linkage area on the stack.
3492   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3493   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3494   if (useSoftFloat())
3495     CCInfo.PreAnalyzeFormalArguments(Ins);
3496 
3497   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3498   CCInfo.clearWasPPCF128();
3499 
3500   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3501     CCValAssign &VA = ArgLocs[i];
3502 
3503     // Arguments stored in registers.
3504     if (VA.isRegLoc()) {
3505       const TargetRegisterClass *RC;
3506       EVT ValVT = VA.getValVT();
3507 
3508       switch (ValVT.getSimpleVT().SimpleTy) {
3509         default:
3510           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3511         case MVT::i1:
3512         case MVT::i32:
3513           RC = &PPC::GPRCRegClass;
3514           break;
3515         case MVT::f32:
3516           if (Subtarget.hasP8Vector())
3517             RC = &PPC::VSSRCRegClass;
3518           else if (Subtarget.hasSPE())
3519             RC = &PPC::GPRCRegClass;
3520           else
3521             RC = &PPC::F4RCRegClass;
3522           break;
3523         case MVT::f64:
3524           if (Subtarget.hasVSX())
3525             RC = &PPC::VSFRCRegClass;
3526           else if (Subtarget.hasSPE())
3527             // SPE passes doubles in GPR pairs.
3528             RC = &PPC::GPRCRegClass;
3529           else
3530             RC = &PPC::F8RCRegClass;
3531           break;
3532         case MVT::v16i8:
3533         case MVT::v8i16:
3534         case MVT::v4i32:
3535           RC = &PPC::VRRCRegClass;
3536           break;
3537         case MVT::v4f32:
3538           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3539           break;
3540         case MVT::v2f64:
3541         case MVT::v2i64:
3542           RC = &PPC::VRRCRegClass;
3543           break;
3544         case MVT::v4f64:
3545           RC = &PPC::QFRCRegClass;
3546           break;
3547         case MVT::v4i1:
3548           RC = &PPC::QBRCRegClass;
3549           break;
3550       }
3551 
3552       SDValue ArgValue;
3553       // Transform the arguments stored in physical registers into
3554       // virtual ones.
3555       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3556         assert(i + 1 < e && "No second half of double precision argument");
3557         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3558         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3559         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3560         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3561         if (!Subtarget.isLittleEndian())
3562           std::swap (ArgValueLo, ArgValueHi);
3563         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3564                                ArgValueHi);
3565       } else {
3566         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3567         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3568                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3569         if (ValVT == MVT::i1)
3570           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3571       }
3572 
3573       InVals.push_back(ArgValue);
3574     } else {
3575       // Argument stored in memory.
3576       assert(VA.isMemLoc());
3577 
3578       // Get the extended size of the argument type in stack
3579       unsigned ArgSize = VA.getLocVT().getStoreSize();
3580       // Get the actual size of the argument type
3581       unsigned ObjSize = VA.getValVT().getStoreSize();
3582       unsigned ArgOffset = VA.getLocMemOffset();
3583       // Stack objects in PPC32 are right justified.
3584       ArgOffset += ArgSize - ObjSize;
3585       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3586 
3587       // Create load nodes to retrieve arguments from the stack.
3588       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3589       InVals.push_back(
3590           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3591     }
3592   }
3593 
3594   // Assign locations to all of the incoming aggregate by value arguments.
3595   // Aggregates passed by value are stored in the local variable space of the
3596   // caller's stack frame, right above the parameter list area.
3597   SmallVector<CCValAssign, 16> ByValArgLocs;
3598   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3599                       ByValArgLocs, *DAG.getContext());
3600 
3601   // Reserve stack space for the allocations in CCInfo.
3602   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3603 
3604   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3605 
3606   // Area that is at least reserved in the caller of this function.
3607   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3608   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3609 
3610   // Set the size that is at least reserved in caller of this function.  Tail
3611   // call optimized function's reserved stack space needs to be aligned so that
3612   // taking the difference between two stack areas will result in an aligned
3613   // stack.
3614   MinReservedArea =
3615       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3616   FuncInfo->setMinReservedArea(MinReservedArea);
3617 
3618   SmallVector<SDValue, 8> MemOps;
3619 
3620   // If the function takes variable number of arguments, make a frame index for
3621   // the start of the first vararg value... for expansion of llvm.va_start.
3622   if (isVarArg) {
3623     static const MCPhysReg GPArgRegs[] = {
3624       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3625       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3626     };
3627     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3628 
3629     static const MCPhysReg FPArgRegs[] = {
3630       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3631       PPC::F8
3632     };
3633     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3634 
3635     if (useSoftFloat() || hasSPE())
3636        NumFPArgRegs = 0;
3637 
3638     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3639     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3640 
3641     // Make room for NumGPArgRegs and NumFPArgRegs.
3642     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3643                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3644 
3645     FuncInfo->setVarArgsStackOffset(
3646       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3647                             CCInfo.getNextStackOffset(), true));
3648 
3649     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3650     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3651 
3652     // The fixed integer arguments of a variadic function are stored to the
3653     // VarArgsFrameIndex on the stack so that they may be loaded by
3654     // dereferencing the result of va_next.
3655     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3656       // Get an existing live-in vreg, or add a new one.
3657       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3658       if (!VReg)
3659         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3660 
3661       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3662       SDValue Store =
3663           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3664       MemOps.push_back(Store);
3665       // Increment the address by four for the next argument to store
3666       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3667       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3668     }
3669 
3670     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3671     // is set.
3672     // The double arguments are stored to the VarArgsFrameIndex
3673     // on the stack.
3674     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3675       // Get an existing live-in vreg, or add a new one.
3676       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3677       if (!VReg)
3678         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3679 
3680       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3681       SDValue Store =
3682           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3683       MemOps.push_back(Store);
3684       // Increment the address by eight for the next argument to store
3685       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3686                                          PtrVT);
3687       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3688     }
3689   }
3690 
3691   if (!MemOps.empty())
3692     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3693 
3694   return Chain;
3695 }
3696 
3697 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3698 // value to MVT::i64 and then truncate to the correct register size.
3699 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3700                                              EVT ObjectVT, SelectionDAG &DAG,
3701                                              SDValue ArgVal,
3702                                              const SDLoc &dl) const {
3703   if (Flags.isSExt())
3704     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3705                          DAG.getValueType(ObjectVT));
3706   else if (Flags.isZExt())
3707     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3708                          DAG.getValueType(ObjectVT));
3709 
3710   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3711 }
3712 
3713 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3714     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3715     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3716     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3717   // TODO: add description of PPC stack frame format, or at least some docs.
3718   //
3719   bool isELFv2ABI = Subtarget.isELFv2ABI();
3720   bool isLittleEndian = Subtarget.isLittleEndian();
3721   MachineFunction &MF = DAG.getMachineFunction();
3722   MachineFrameInfo &MFI = MF.getFrameInfo();
3723   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3724 
3725   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3726          "fastcc not supported on varargs functions");
3727 
3728   EVT PtrVT = getPointerTy(MF.getDataLayout());
3729   // Potential tail calls could cause overwriting of argument stack slots.
3730   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3731                        (CallConv == CallingConv::Fast));
3732   unsigned PtrByteSize = 8;
3733   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3734 
3735   static const MCPhysReg GPR[] = {
3736     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3737     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3738   };
3739   static const MCPhysReg VR[] = {
3740     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3741     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3742   };
3743 
3744   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3745   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3746   const unsigned Num_VR_Regs  = array_lengthof(VR);
3747   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3748 
3749   // Do a first pass over the arguments to determine whether the ABI
3750   // guarantees that our caller has allocated the parameter save area
3751   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3752   // in the ELFv2 ABI, it is true if this is a vararg function or if
3753   // any parameter is located in a stack slot.
3754 
3755   bool HasParameterArea = !isELFv2ABI || isVarArg;
3756   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3757   unsigned NumBytes = LinkageSize;
3758   unsigned AvailableFPRs = Num_FPR_Regs;
3759   unsigned AvailableVRs = Num_VR_Regs;
3760   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3761     if (Ins[i].Flags.isNest())
3762       continue;
3763 
3764     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3765                                PtrByteSize, LinkageSize, ParamAreaSize,
3766                                NumBytes, AvailableFPRs, AvailableVRs,
3767                                Subtarget.hasQPX()))
3768       HasParameterArea = true;
3769   }
3770 
3771   // Add DAG nodes to load the arguments or copy them out of registers.  On
3772   // entry to a function on PPC, the arguments start after the linkage area,
3773   // although the first ones are often in registers.
3774 
3775   unsigned ArgOffset = LinkageSize;
3776   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3777   unsigned &QFPR_idx = FPR_idx;
3778   SmallVector<SDValue, 8> MemOps;
3779   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3780   unsigned CurArgIdx = 0;
3781   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3782     SDValue ArgVal;
3783     bool needsLoad = false;
3784     EVT ObjectVT = Ins[ArgNo].VT;
3785     EVT OrigVT = Ins[ArgNo].ArgVT;
3786     unsigned ObjSize = ObjectVT.getStoreSize();
3787     unsigned ArgSize = ObjSize;
3788     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3789     if (Ins[ArgNo].isOrigArg()) {
3790       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3791       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3792     }
3793     // We re-align the argument offset for each argument, except when using the
3794     // fast calling convention, when we need to make sure we do that only when
3795     // we'll actually use a stack slot.
3796     unsigned CurArgOffset;
3797     Align Alignment;
3798     auto ComputeArgOffset = [&]() {
3799       /* Respect alignment of argument on the stack.  */
3800       Alignment =
3801           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3802       ArgOffset = alignTo(ArgOffset, Alignment);
3803       CurArgOffset = ArgOffset;
3804     };
3805 
3806     if (CallConv != CallingConv::Fast) {
3807       ComputeArgOffset();
3808 
3809       /* Compute GPR index associated with argument offset.  */
3810       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3811       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3812     }
3813 
3814     // FIXME the codegen can be much improved in some cases.
3815     // We do not have to keep everything in memory.
3816     if (Flags.isByVal()) {
3817       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3818 
3819       if (CallConv == CallingConv::Fast)
3820         ComputeArgOffset();
3821 
3822       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3823       ObjSize = Flags.getByValSize();
3824       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3825       // Empty aggregate parameters do not take up registers.  Examples:
3826       //   struct { } a;
3827       //   union  { } b;
3828       //   int c[0];
3829       // etc.  However, we have to provide a place-holder in InVals, so
3830       // pretend we have an 8-byte item at the current address for that
3831       // purpose.
3832       if (!ObjSize) {
3833         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3834         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3835         InVals.push_back(FIN);
3836         continue;
3837       }
3838 
3839       // Create a stack object covering all stack doublewords occupied
3840       // by the argument.  If the argument is (fully or partially) on
3841       // the stack, or if the argument is fully in registers but the
3842       // caller has allocated the parameter save anyway, we can refer
3843       // directly to the caller's stack frame.  Otherwise, create a
3844       // local copy in our own frame.
3845       int FI;
3846       if (HasParameterArea ||
3847           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3848         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3849       else
3850         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3851       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3852 
3853       // Handle aggregates smaller than 8 bytes.
3854       if (ObjSize < PtrByteSize) {
3855         // The value of the object is its address, which differs from the
3856         // address of the enclosing doubleword on big-endian systems.
3857         SDValue Arg = FIN;
3858         if (!isLittleEndian) {
3859           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3860           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3861         }
3862         InVals.push_back(Arg);
3863 
3864         if (GPR_idx != Num_GPR_Regs) {
3865           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3866           FuncInfo->addLiveInAttr(VReg, Flags);
3867           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3868           SDValue Store;
3869 
3870           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3871             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3872                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3873             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3874                                       MachinePointerInfo(&*FuncArg), ObjType);
3875           } else {
3876             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3877             // store the whole register as-is to the parameter save area
3878             // slot.
3879             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3880                                  MachinePointerInfo(&*FuncArg));
3881           }
3882 
3883           MemOps.push_back(Store);
3884         }
3885         // Whether we copied from a register or not, advance the offset
3886         // into the parameter save area by a full doubleword.
3887         ArgOffset += PtrByteSize;
3888         continue;
3889       }
3890 
3891       // The value of the object is its address, which is the address of
3892       // its first stack doubleword.
3893       InVals.push_back(FIN);
3894 
3895       // Store whatever pieces of the object are in registers to memory.
3896       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3897         if (GPR_idx == Num_GPR_Regs)
3898           break;
3899 
3900         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3901         FuncInfo->addLiveInAttr(VReg, Flags);
3902         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3903         SDValue Addr = FIN;
3904         if (j) {
3905           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3906           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3907         }
3908         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3909                                      MachinePointerInfo(&*FuncArg, j));
3910         MemOps.push_back(Store);
3911         ++GPR_idx;
3912       }
3913       ArgOffset += ArgSize;
3914       continue;
3915     }
3916 
3917     switch (ObjectVT.getSimpleVT().SimpleTy) {
3918     default: llvm_unreachable("Unhandled argument type!");
3919     case MVT::i1:
3920     case MVT::i32:
3921     case MVT::i64:
3922       if (Flags.isNest()) {
3923         // The 'nest' parameter, if any, is passed in R11.
3924         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3925         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3926 
3927         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3928           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3929 
3930         break;
3931       }
3932 
3933       // These can be scalar arguments or elements of an integer array type
3934       // passed directly.  Clang may use those instead of "byval" aggregate
3935       // types to avoid forcing arguments to memory unnecessarily.
3936       if (GPR_idx != Num_GPR_Regs) {
3937         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3938         FuncInfo->addLiveInAttr(VReg, Flags);
3939         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3940 
3941         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3942           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3943           // value to MVT::i64 and then truncate to the correct register size.
3944           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3945       } else {
3946         if (CallConv == CallingConv::Fast)
3947           ComputeArgOffset();
3948 
3949         needsLoad = true;
3950         ArgSize = PtrByteSize;
3951       }
3952       if (CallConv != CallingConv::Fast || needsLoad)
3953         ArgOffset += 8;
3954       break;
3955 
3956     case MVT::f32:
3957     case MVT::f64:
3958       // These can be scalar arguments or elements of a float array type
3959       // passed directly.  The latter are used to implement ELFv2 homogenous
3960       // float aggregates.
3961       if (FPR_idx != Num_FPR_Regs) {
3962         unsigned VReg;
3963 
3964         if (ObjectVT == MVT::f32)
3965           VReg = MF.addLiveIn(FPR[FPR_idx],
3966                               Subtarget.hasP8Vector()
3967                                   ? &PPC::VSSRCRegClass
3968                                   : &PPC::F4RCRegClass);
3969         else
3970           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3971                                                 ? &PPC::VSFRCRegClass
3972                                                 : &PPC::F8RCRegClass);
3973 
3974         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3975         ++FPR_idx;
3976       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3977         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3978         // once we support fp <-> gpr moves.
3979 
3980         // This can only ever happen in the presence of f32 array types,
3981         // since otherwise we never run out of FPRs before running out
3982         // of GPRs.
3983         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3984         FuncInfo->addLiveInAttr(VReg, Flags);
3985         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3986 
3987         if (ObjectVT == MVT::f32) {
3988           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3989             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3990                                  DAG.getConstant(32, dl, MVT::i32));
3991           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3992         }
3993 
3994         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3995       } else {
3996         if (CallConv == CallingConv::Fast)
3997           ComputeArgOffset();
3998 
3999         needsLoad = true;
4000       }
4001 
4002       // When passing an array of floats, the array occupies consecutive
4003       // space in the argument area; only round up to the next doubleword
4004       // at the end of the array.  Otherwise, each float takes 8 bytes.
4005       if (CallConv != CallingConv::Fast || needsLoad) {
4006         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4007         ArgOffset += ArgSize;
4008         if (Flags.isInConsecutiveRegsLast())
4009           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4010       }
4011       break;
4012     case MVT::v4f32:
4013     case MVT::v4i32:
4014     case MVT::v8i16:
4015     case MVT::v16i8:
4016     case MVT::v2f64:
4017     case MVT::v2i64:
4018     case MVT::v1i128:
4019     case MVT::f128:
4020       if (!Subtarget.hasQPX()) {
4021         // These can be scalar arguments or elements of a vector array type
4022         // passed directly.  The latter are used to implement ELFv2 homogenous
4023         // vector aggregates.
4024         if (VR_idx != Num_VR_Regs) {
4025           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4026           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4027           ++VR_idx;
4028         } else {
4029           if (CallConv == CallingConv::Fast)
4030             ComputeArgOffset();
4031           needsLoad = true;
4032         }
4033         if (CallConv != CallingConv::Fast || needsLoad)
4034           ArgOffset += 16;
4035         break;
4036       } // not QPX
4037 
4038       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4039              "Invalid QPX parameter type");
4040       LLVM_FALLTHROUGH;
4041 
4042     case MVT::v4f64:
4043     case MVT::v4i1:
4044       // QPX vectors are treated like their scalar floating-point subregisters
4045       // (except that they're larger).
4046       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4047       if (QFPR_idx != Num_QFPR_Regs) {
4048         const TargetRegisterClass *RC;
4049         switch (ObjectVT.getSimpleVT().SimpleTy) {
4050         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4051         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4052         default:         RC = &PPC::QBRCRegClass; break;
4053         }
4054 
4055         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4056         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4057         ++QFPR_idx;
4058       } else {
4059         if (CallConv == CallingConv::Fast)
4060           ComputeArgOffset();
4061         needsLoad = true;
4062       }
4063       if (CallConv != CallingConv::Fast || needsLoad)
4064         ArgOffset += Sz;
4065       break;
4066     }
4067 
4068     // We need to load the argument to a virtual register if we determined
4069     // above that we ran out of physical registers of the appropriate type.
4070     if (needsLoad) {
4071       if (ObjSize < ArgSize && !isLittleEndian)
4072         CurArgOffset += ArgSize - ObjSize;
4073       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4074       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4075       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4076     }
4077 
4078     InVals.push_back(ArgVal);
4079   }
4080 
4081   // Area that is at least reserved in the caller of this function.
4082   unsigned MinReservedArea;
4083   if (HasParameterArea)
4084     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4085   else
4086     MinReservedArea = LinkageSize;
4087 
4088   // Set the size that is at least reserved in caller of this function.  Tail
4089   // call optimized functions' reserved stack space needs to be aligned so that
4090   // taking the difference between two stack areas will result in an aligned
4091   // stack.
4092   MinReservedArea =
4093       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4094   FuncInfo->setMinReservedArea(MinReservedArea);
4095 
4096   // If the function takes variable number of arguments, make a frame index for
4097   // the start of the first vararg value... for expansion of llvm.va_start.
4098   if (isVarArg) {
4099     int Depth = ArgOffset;
4100 
4101     FuncInfo->setVarArgsFrameIndex(
4102       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4103     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4104 
4105     // If this function is vararg, store any remaining integer argument regs
4106     // to their spots on the stack so that they may be loaded by dereferencing
4107     // the result of va_next.
4108     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4109          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4110       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4111       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4112       SDValue Store =
4113           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4114       MemOps.push_back(Store);
4115       // Increment the address by four for the next argument to store
4116       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4117       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4118     }
4119   }
4120 
4121   if (!MemOps.empty())
4122     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4123 
4124   return Chain;
4125 }
4126 
4127 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4128     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4129     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4130     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4131   // TODO: add description of PPC stack frame format, or at least some docs.
4132   //
4133   MachineFunction &MF = DAG.getMachineFunction();
4134   MachineFrameInfo &MFI = MF.getFrameInfo();
4135   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4136 
4137   EVT PtrVT = getPointerTy(MF.getDataLayout());
4138   bool isPPC64 = PtrVT == MVT::i64;
4139   // Potential tail calls could cause overwriting of argument stack slots.
4140   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4141                        (CallConv == CallingConv::Fast));
4142   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4143   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4144   unsigned ArgOffset = LinkageSize;
4145   // Area that is at least reserved in caller of this function.
4146   unsigned MinReservedArea = ArgOffset;
4147 
4148   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4149     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4150     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4151   };
4152   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4153     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4154     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4155   };
4156   static const MCPhysReg VR[] = {
4157     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4158     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4159   };
4160 
4161   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4162   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4163   const unsigned Num_VR_Regs  = array_lengthof( VR);
4164 
4165   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4166 
4167   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4168 
4169   // In 32-bit non-varargs functions, the stack space for vectors is after the
4170   // stack space for non-vectors.  We do not use this space unless we have
4171   // too many vectors to fit in registers, something that only occurs in
4172   // constructed examples:), but we have to walk the arglist to figure
4173   // that out...for the pathological case, compute VecArgOffset as the
4174   // start of the vector parameter area.  Computing VecArgOffset is the
4175   // entire point of the following loop.
4176   unsigned VecArgOffset = ArgOffset;
4177   if (!isVarArg && !isPPC64) {
4178     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4179          ++ArgNo) {
4180       EVT ObjectVT = Ins[ArgNo].VT;
4181       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4182 
4183       if (Flags.isByVal()) {
4184         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4185         unsigned ObjSize = Flags.getByValSize();
4186         unsigned ArgSize =
4187                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4188         VecArgOffset += ArgSize;
4189         continue;
4190       }
4191 
4192       switch(ObjectVT.getSimpleVT().SimpleTy) {
4193       default: llvm_unreachable("Unhandled argument type!");
4194       case MVT::i1:
4195       case MVT::i32:
4196       case MVT::f32:
4197         VecArgOffset += 4;
4198         break;
4199       case MVT::i64:  // PPC64
4200       case MVT::f64:
4201         // FIXME: We are guaranteed to be !isPPC64 at this point.
4202         // Does MVT::i64 apply?
4203         VecArgOffset += 8;
4204         break;
4205       case MVT::v4f32:
4206       case MVT::v4i32:
4207       case MVT::v8i16:
4208       case MVT::v16i8:
4209         // Nothing to do, we're only looking at Nonvector args here.
4210         break;
4211       }
4212     }
4213   }
4214   // We've found where the vector parameter area in memory is.  Skip the
4215   // first 12 parameters; these don't use that memory.
4216   VecArgOffset = ((VecArgOffset+15)/16)*16;
4217   VecArgOffset += 12*16;
4218 
4219   // Add DAG nodes to load the arguments or copy them out of registers.  On
4220   // entry to a function on PPC, the arguments start after the linkage area,
4221   // although the first ones are often in registers.
4222 
4223   SmallVector<SDValue, 8> MemOps;
4224   unsigned nAltivecParamsAtEnd = 0;
4225   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4226   unsigned CurArgIdx = 0;
4227   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4228     SDValue ArgVal;
4229     bool needsLoad = false;
4230     EVT ObjectVT = Ins[ArgNo].VT;
4231     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4232     unsigned ArgSize = ObjSize;
4233     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4234     if (Ins[ArgNo].isOrigArg()) {
4235       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4236       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4237     }
4238     unsigned CurArgOffset = ArgOffset;
4239 
4240     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4241     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4242         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4243       if (isVarArg || isPPC64) {
4244         MinReservedArea = ((MinReservedArea+15)/16)*16;
4245         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4246                                                   Flags,
4247                                                   PtrByteSize);
4248       } else  nAltivecParamsAtEnd++;
4249     } else
4250       // Calculate min reserved area.
4251       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4252                                                 Flags,
4253                                                 PtrByteSize);
4254 
4255     // FIXME the codegen can be much improved in some cases.
4256     // We do not have to keep everything in memory.
4257     if (Flags.isByVal()) {
4258       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4259 
4260       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4261       ObjSize = Flags.getByValSize();
4262       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4263       // Objects of size 1 and 2 are right justified, everything else is
4264       // left justified.  This means the memory address is adjusted forwards.
4265       if (ObjSize==1 || ObjSize==2) {
4266         CurArgOffset = CurArgOffset + (4 - ObjSize);
4267       }
4268       // The value of the object is its address.
4269       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4270       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4271       InVals.push_back(FIN);
4272       if (ObjSize==1 || ObjSize==2) {
4273         if (GPR_idx != Num_GPR_Regs) {
4274           unsigned VReg;
4275           if (isPPC64)
4276             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4277           else
4278             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4279           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4280           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4281           SDValue Store =
4282               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4283                                 MachinePointerInfo(&*FuncArg), ObjType);
4284           MemOps.push_back(Store);
4285           ++GPR_idx;
4286         }
4287 
4288         ArgOffset += PtrByteSize;
4289 
4290         continue;
4291       }
4292       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4293         // Store whatever pieces of the object are in registers
4294         // to memory.  ArgOffset will be the address of the beginning
4295         // of the object.
4296         if (GPR_idx != Num_GPR_Regs) {
4297           unsigned VReg;
4298           if (isPPC64)
4299             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4300           else
4301             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4302           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4303           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4304           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4305           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4306                                        MachinePointerInfo(&*FuncArg, j));
4307           MemOps.push_back(Store);
4308           ++GPR_idx;
4309           ArgOffset += PtrByteSize;
4310         } else {
4311           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4312           break;
4313         }
4314       }
4315       continue;
4316     }
4317 
4318     switch (ObjectVT.getSimpleVT().SimpleTy) {
4319     default: llvm_unreachable("Unhandled argument type!");
4320     case MVT::i1:
4321     case MVT::i32:
4322       if (!isPPC64) {
4323         if (GPR_idx != Num_GPR_Regs) {
4324           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4325           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4326 
4327           if (ObjectVT == MVT::i1)
4328             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4329 
4330           ++GPR_idx;
4331         } else {
4332           needsLoad = true;
4333           ArgSize = PtrByteSize;
4334         }
4335         // All int arguments reserve stack space in the Darwin ABI.
4336         ArgOffset += PtrByteSize;
4337         break;
4338       }
4339       LLVM_FALLTHROUGH;
4340     case MVT::i64:  // PPC64
4341       if (GPR_idx != Num_GPR_Regs) {
4342         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4343         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4344 
4345         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4346           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4347           // value to MVT::i64 and then truncate to the correct register size.
4348           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4349 
4350         ++GPR_idx;
4351       } else {
4352         needsLoad = true;
4353         ArgSize = PtrByteSize;
4354       }
4355       // All int arguments reserve stack space in the Darwin ABI.
4356       ArgOffset += 8;
4357       break;
4358 
4359     case MVT::f32:
4360     case MVT::f64:
4361       // Every 4 bytes of argument space consumes one of the GPRs available for
4362       // argument passing.
4363       if (GPR_idx != Num_GPR_Regs) {
4364         ++GPR_idx;
4365         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4366           ++GPR_idx;
4367       }
4368       if (FPR_idx != Num_FPR_Regs) {
4369         unsigned VReg;
4370 
4371         if (ObjectVT == MVT::f32)
4372           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4373         else
4374           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4375 
4376         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4377         ++FPR_idx;
4378       } else {
4379         needsLoad = true;
4380       }
4381 
4382       // All FP arguments reserve stack space in the Darwin ABI.
4383       ArgOffset += isPPC64 ? 8 : ObjSize;
4384       break;
4385     case MVT::v4f32:
4386     case MVT::v4i32:
4387     case MVT::v8i16:
4388     case MVT::v16i8:
4389       // Note that vector arguments in registers don't reserve stack space,
4390       // except in varargs functions.
4391       if (VR_idx != Num_VR_Regs) {
4392         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4393         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4394         if (isVarArg) {
4395           while ((ArgOffset % 16) != 0) {
4396             ArgOffset += PtrByteSize;
4397             if (GPR_idx != Num_GPR_Regs)
4398               GPR_idx++;
4399           }
4400           ArgOffset += 16;
4401           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4402         }
4403         ++VR_idx;
4404       } else {
4405         if (!isVarArg && !isPPC64) {
4406           // Vectors go after all the nonvectors.
4407           CurArgOffset = VecArgOffset;
4408           VecArgOffset += 16;
4409         } else {
4410           // Vectors are aligned.
4411           ArgOffset = ((ArgOffset+15)/16)*16;
4412           CurArgOffset = ArgOffset;
4413           ArgOffset += 16;
4414         }
4415         needsLoad = true;
4416       }
4417       break;
4418     }
4419 
4420     // We need to load the argument to a virtual register if we determined above
4421     // that we ran out of physical registers of the appropriate type.
4422     if (needsLoad) {
4423       int FI = MFI.CreateFixedObject(ObjSize,
4424                                      CurArgOffset + (ArgSize - ObjSize),
4425                                      isImmutable);
4426       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4427       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4428     }
4429 
4430     InVals.push_back(ArgVal);
4431   }
4432 
4433   // Allow for Altivec parameters at the end, if needed.
4434   if (nAltivecParamsAtEnd) {
4435     MinReservedArea = ((MinReservedArea+15)/16)*16;
4436     MinReservedArea += 16*nAltivecParamsAtEnd;
4437   }
4438 
4439   // Area that is at least reserved in the caller of this function.
4440   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4441 
4442   // Set the size that is at least reserved in caller of this function.  Tail
4443   // call optimized functions' reserved stack space needs to be aligned so that
4444   // taking the difference between two stack areas will result in an aligned
4445   // stack.
4446   MinReservedArea =
4447       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4448   FuncInfo->setMinReservedArea(MinReservedArea);
4449 
4450   // If the function takes variable number of arguments, make a frame index for
4451   // the start of the first vararg value... for expansion of llvm.va_start.
4452   if (isVarArg) {
4453     int Depth = ArgOffset;
4454 
4455     FuncInfo->setVarArgsFrameIndex(
4456       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4457                             Depth, true));
4458     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4459 
4460     // If this function is vararg, store any remaining integer argument regs
4461     // to their spots on the stack so that they may be loaded by dereferencing
4462     // the result of va_next.
4463     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4464       unsigned VReg;
4465 
4466       if (isPPC64)
4467         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4468       else
4469         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4470 
4471       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4472       SDValue Store =
4473           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4474       MemOps.push_back(Store);
4475       // Increment the address by four for the next argument to store
4476       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4477       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4478     }
4479   }
4480 
4481   if (!MemOps.empty())
4482     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4483 
4484   return Chain;
4485 }
4486 
4487 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4488 /// adjusted to accommodate the arguments for the tailcall.
4489 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4490                                    unsigned ParamSize) {
4491 
4492   if (!isTailCall) return 0;
4493 
4494   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4495   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4496   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4497   // Remember only if the new adjustment is bigger.
4498   if (SPDiff < FI->getTailCallSPDelta())
4499     FI->setTailCallSPDelta(SPDiff);
4500 
4501   return SPDiff;
4502 }
4503 
4504 static bool isFunctionGlobalAddress(SDValue Callee);
4505 
4506 static bool
4507 callsShareTOCBase(const Function *Caller, SDValue Callee,
4508                     const TargetMachine &TM) {
4509    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4510    // don't have enough information to determine if the caller and calle share
4511    // the same  TOC base, so we have to pessimistically assume they don't for
4512    // correctness.
4513    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4514    if (!G)
4515      return false;
4516 
4517    const GlobalValue *GV = G->getGlobal();
4518   // The medium and large code models are expected to provide a sufficiently
4519   // large TOC to provide all data addressing needs of a module with a
4520   // single TOC. Since each module will be addressed with a single TOC then we
4521   // only need to check that caller and callee don't cross dso boundaries.
4522   if (CodeModel::Medium == TM.getCodeModel() ||
4523       CodeModel::Large == TM.getCodeModel())
4524     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4525 
4526   // Otherwise we need to ensure callee and caller are in the same section,
4527   // since the linker may allocate multiple TOCs, and we don't know which
4528   // sections will belong to the same TOC base.
4529 
4530   if (!GV->isStrongDefinitionForLinker())
4531     return false;
4532 
4533   // Any explicitly-specified sections and section prefixes must also match.
4534   // Also, if we're using -ffunction-sections, then each function is always in
4535   // a different section (the same is true for COMDAT functions).
4536   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4537       GV->getSection() != Caller->getSection())
4538     return false;
4539   if (const auto *F = dyn_cast<Function>(GV)) {
4540     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4541       return false;
4542   }
4543 
4544   // If the callee might be interposed, then we can't assume the ultimate call
4545   // target will be in the same section. Even in cases where we can assume that
4546   // interposition won't happen, in any case where the linker might insert a
4547   // stub to allow for interposition, we must generate code as though
4548   // interposition might occur. To understand why this matters, consider a
4549   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4550   // in the same section, but a is in a different module (i.e. has a different
4551   // TOC base pointer). If the linker allows for interposition between b and c,
4552   // then it will generate a stub for the call edge between b and c which will
4553   // save the TOC pointer into the designated stack slot allocated by b. If we
4554   // return true here, and therefore allow a tail call between b and c, that
4555   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4556   // pointer into the stack slot allocated by a (where the a -> b stub saved
4557   // a's TOC base pointer). If we're not considering a tail call, but rather,
4558   // whether a nop is needed after the call instruction in b, because the linker
4559   // will insert a stub, it might complain about a missing nop if we omit it
4560   // (although many don't complain in this case).
4561   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4562     return false;
4563 
4564   return true;
4565 }
4566 
4567 static bool
4568 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4569                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4570   assert(Subtarget.is64BitELFABI());
4571 
4572   const unsigned PtrByteSize = 8;
4573   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4574 
4575   static const MCPhysReg GPR[] = {
4576     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4577     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4578   };
4579   static const MCPhysReg VR[] = {
4580     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4581     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4582   };
4583 
4584   const unsigned NumGPRs = array_lengthof(GPR);
4585   const unsigned NumFPRs = 13;
4586   const unsigned NumVRs = array_lengthof(VR);
4587   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4588 
4589   unsigned NumBytes = LinkageSize;
4590   unsigned AvailableFPRs = NumFPRs;
4591   unsigned AvailableVRs = NumVRs;
4592 
4593   for (const ISD::OutputArg& Param : Outs) {
4594     if (Param.Flags.isNest()) continue;
4595 
4596     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4597                                PtrByteSize, LinkageSize, ParamAreaSize,
4598                                NumBytes, AvailableFPRs, AvailableVRs,
4599                                Subtarget.hasQPX()))
4600       return true;
4601   }
4602   return false;
4603 }
4604 
4605 static bool
4606 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4607   if (CS.arg_size() != CallerFn->arg_size())
4608     return false;
4609 
4610   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4611   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4612   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4613 
4614   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4615     const Value* CalleeArg = *CalleeArgIter;
4616     const Value* CallerArg = &(*CallerArgIter);
4617     if (CalleeArg == CallerArg)
4618       continue;
4619 
4620     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4621     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4622     //      }
4623     // 1st argument of callee is undef and has the same type as caller.
4624     if (CalleeArg->getType() == CallerArg->getType() &&
4625         isa<UndefValue>(CalleeArg))
4626       continue;
4627 
4628     return false;
4629   }
4630 
4631   return true;
4632 }
4633 
4634 // Returns true if TCO is possible between the callers and callees
4635 // calling conventions.
4636 static bool
4637 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4638                                     CallingConv::ID CalleeCC) {
4639   // Tail calls are possible with fastcc and ccc.
4640   auto isTailCallableCC  = [] (CallingConv::ID CC){
4641       return  CC == CallingConv::C || CC == CallingConv::Fast;
4642   };
4643   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4644     return false;
4645 
4646   // We can safely tail call both fastcc and ccc callees from a c calling
4647   // convention caller. If the caller is fastcc, we may have less stack space
4648   // than a non-fastcc caller with the same signature so disable tail-calls in
4649   // that case.
4650   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4651 }
4652 
4653 bool
4654 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4655                                     SDValue Callee,
4656                                     CallingConv::ID CalleeCC,
4657                                     ImmutableCallSite CS,
4658                                     bool isVarArg,
4659                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4660                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4661                                     SelectionDAG& DAG) const {
4662   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4663 
4664   if (DisableSCO && !TailCallOpt) return false;
4665 
4666   // Variadic argument functions are not supported.
4667   if (isVarArg) return false;
4668 
4669   auto &Caller = DAG.getMachineFunction().getFunction();
4670   // Check that the calling conventions are compatible for tco.
4671   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4672     return false;
4673 
4674   // Caller contains any byval parameter is not supported.
4675   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4676     return false;
4677 
4678   // Callee contains any byval parameter is not supported, too.
4679   // Note: This is a quick work around, because in some cases, e.g.
4680   // caller's stack size > callee's stack size, we are still able to apply
4681   // sibling call optimization. For example, gcc is able to do SCO for caller1
4682   // in the following example, but not for caller2.
4683   //   struct test {
4684   //     long int a;
4685   //     char ary[56];
4686   //   } gTest;
4687   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4688   //     b->a = v.a;
4689   //     return 0;
4690   //   }
4691   //   void caller1(struct test a, struct test c, struct test *b) {
4692   //     callee(gTest, b); }
4693   //   void caller2(struct test *b) { callee(gTest, b); }
4694   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4695     return false;
4696 
4697   // If callee and caller use different calling conventions, we cannot pass
4698   // parameters on stack since offsets for the parameter area may be different.
4699   if (Caller.getCallingConv() != CalleeCC &&
4700       needStackSlotPassParameters(Subtarget, Outs))
4701     return false;
4702 
4703   // No TCO/SCO on indirect call because Caller have to restore its TOC
4704   if (!isFunctionGlobalAddress(Callee) &&
4705       !isa<ExternalSymbolSDNode>(Callee))
4706     return false;
4707 
4708   // If the caller and callee potentially have different TOC bases then we
4709   // cannot tail call since we need to restore the TOC pointer after the call.
4710   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4711   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4712     return false;
4713 
4714   // TCO allows altering callee ABI, so we don't have to check further.
4715   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4716     return true;
4717 
4718   if (DisableSCO) return false;
4719 
4720   // If callee use the same argument list that caller is using, then we can
4721   // apply SCO on this case. If it is not, then we need to check if callee needs
4722   // stack for passing arguments.
4723   if (!hasSameArgumentList(&Caller, CS) &&
4724       needStackSlotPassParameters(Subtarget, Outs)) {
4725     return false;
4726   }
4727 
4728   return true;
4729 }
4730 
4731 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4732 /// for tail call optimization. Targets which want to do tail call
4733 /// optimization should implement this function.
4734 bool
4735 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4736                                                      CallingConv::ID CalleeCC,
4737                                                      bool isVarArg,
4738                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4739                                                      SelectionDAG& DAG) const {
4740   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4741     return false;
4742 
4743   // Variable argument functions are not supported.
4744   if (isVarArg)
4745     return false;
4746 
4747   MachineFunction &MF = DAG.getMachineFunction();
4748   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4749   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4750     // Functions containing by val parameters are not supported.
4751     for (unsigned i = 0; i != Ins.size(); i++) {
4752        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4753        if (Flags.isByVal()) return false;
4754     }
4755 
4756     // Non-PIC/GOT tail calls are supported.
4757     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4758       return true;
4759 
4760     // At the moment we can only do local tail calls (in same module, hidden
4761     // or protected) if we are generating PIC.
4762     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4763       return G->getGlobal()->hasHiddenVisibility()
4764           || G->getGlobal()->hasProtectedVisibility();
4765   }
4766 
4767   return false;
4768 }
4769 
4770 /// isCallCompatibleAddress - Return the immediate to use if the specified
4771 /// 32-bit value is representable in the immediate field of a BxA instruction.
4772 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4773   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4774   if (!C) return nullptr;
4775 
4776   int Addr = C->getZExtValue();
4777   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4778       SignExtend32<26>(Addr) != Addr)
4779     return nullptr;  // Top 6 bits have to be sext of immediate.
4780 
4781   return DAG
4782       .getConstant(
4783           (int)C->getZExtValue() >> 2, SDLoc(Op),
4784           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4785       .getNode();
4786 }
4787 
4788 namespace {
4789 
4790 struct TailCallArgumentInfo {
4791   SDValue Arg;
4792   SDValue FrameIdxOp;
4793   int FrameIdx = 0;
4794 
4795   TailCallArgumentInfo() = default;
4796 };
4797 
4798 } // end anonymous namespace
4799 
4800 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4801 static void StoreTailCallArgumentsToStackSlot(
4802     SelectionDAG &DAG, SDValue Chain,
4803     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4804     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4805   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4806     SDValue Arg = TailCallArgs[i].Arg;
4807     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4808     int FI = TailCallArgs[i].FrameIdx;
4809     // Store relative to framepointer.
4810     MemOpChains.push_back(DAG.getStore(
4811         Chain, dl, Arg, FIN,
4812         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4813   }
4814 }
4815 
4816 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4817 /// the appropriate stack slot for the tail call optimized function call.
4818 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4819                                              SDValue OldRetAddr, SDValue OldFP,
4820                                              int SPDiff, const SDLoc &dl) {
4821   if (SPDiff) {
4822     // Calculate the new stack slot for the return address.
4823     MachineFunction &MF = DAG.getMachineFunction();
4824     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4825     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4826     bool isPPC64 = Subtarget.isPPC64();
4827     int SlotSize = isPPC64 ? 8 : 4;
4828     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4829     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4830                                                          NewRetAddrLoc, true);
4831     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4832     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4833     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4834                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4835   }
4836   return Chain;
4837 }
4838 
4839 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4840 /// the position of the argument.
4841 static void
4842 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4843                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4844                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4845   int Offset = ArgOffset + SPDiff;
4846   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4847   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4848   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4849   SDValue FIN = DAG.getFrameIndex(FI, VT);
4850   TailCallArgumentInfo Info;
4851   Info.Arg = Arg;
4852   Info.FrameIdxOp = FIN;
4853   Info.FrameIdx = FI;
4854   TailCallArguments.push_back(Info);
4855 }
4856 
4857 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4858 /// stack slot. Returns the chain as result and the loaded frame pointers in
4859 /// LROpOut/FPOpout. Used when tail calling.
4860 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4861     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4862     SDValue &FPOpOut, const SDLoc &dl) const {
4863   if (SPDiff) {
4864     // Load the LR and FP stack slot for later adjusting.
4865     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4866     LROpOut = getReturnAddrFrameIndex(DAG);
4867     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4868     Chain = SDValue(LROpOut.getNode(), 1);
4869   }
4870   return Chain;
4871 }
4872 
4873 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4874 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4875 /// specified by the specific parameter attribute. The copy will be passed as
4876 /// a byval function parameter.
4877 /// Sometimes what we are copying is the end of a larger object, the part that
4878 /// does not fit in registers.
4879 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4880                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4881                                          SelectionDAG &DAG, const SDLoc &dl) {
4882   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4883   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4884                        Flags.getNonZeroByValAlign(), false, false, false,
4885                        MachinePointerInfo(), MachinePointerInfo());
4886 }
4887 
4888 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4889 /// tail calls.
4890 static void LowerMemOpCallTo(
4891     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4892     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4893     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4894     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4895   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4896   if (!isTailCall) {
4897     if (isVector) {
4898       SDValue StackPtr;
4899       if (isPPC64)
4900         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4901       else
4902         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4903       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4904                            DAG.getConstant(ArgOffset, dl, PtrVT));
4905     }
4906     MemOpChains.push_back(
4907         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4908     // Calculate and remember argument location.
4909   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4910                                   TailCallArguments);
4911 }
4912 
4913 static void
4914 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4915                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4916                 SDValue FPOp,
4917                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4918   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4919   // might overwrite each other in case of tail call optimization.
4920   SmallVector<SDValue, 8> MemOpChains2;
4921   // Do not flag preceding copytoreg stuff together with the following stuff.
4922   InFlag = SDValue();
4923   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4924                                     MemOpChains2, dl);
4925   if (!MemOpChains2.empty())
4926     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4927 
4928   // Store the return address to the appropriate stack slot.
4929   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4930 
4931   // Emit callseq_end just before tailcall node.
4932   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4933                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4934   InFlag = Chain.getValue(1);
4935 }
4936 
4937 // Is this global address that of a function that can be called by name? (as
4938 // opposed to something that must hold a descriptor for an indirect call).
4939 static bool isFunctionGlobalAddress(SDValue Callee) {
4940   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4941     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4942         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4943       return false;
4944 
4945     return G->getGlobal()->getValueType()->isFunctionTy();
4946   }
4947 
4948   return false;
4949 }
4950 
4951 SDValue PPCTargetLowering::LowerCallResult(
4952     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4953     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4954     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4955   SmallVector<CCValAssign, 16> RVLocs;
4956   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4957                     *DAG.getContext());
4958 
4959   CCRetInfo.AnalyzeCallResult(
4960       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4961                ? RetCC_PPC_Cold
4962                : RetCC_PPC);
4963 
4964   // Copy all of the result registers out of their specified physreg.
4965   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4966     CCValAssign &VA = RVLocs[i];
4967     assert(VA.isRegLoc() && "Can only return in registers!");
4968 
4969     SDValue Val;
4970 
4971     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
4972       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4973                                       InFlag);
4974       Chain = Lo.getValue(1);
4975       InFlag = Lo.getValue(2);
4976       VA = RVLocs[++i]; // skip ahead to next loc
4977       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4978                                       InFlag);
4979       Chain = Hi.getValue(1);
4980       InFlag = Hi.getValue(2);
4981       if (!Subtarget.isLittleEndian())
4982         std::swap (Lo, Hi);
4983       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
4984     } else {
4985       Val = DAG.getCopyFromReg(Chain, dl,
4986                                VA.getLocReg(), VA.getLocVT(), InFlag);
4987       Chain = Val.getValue(1);
4988       InFlag = Val.getValue(2);
4989     }
4990 
4991     switch (VA.getLocInfo()) {
4992     default: llvm_unreachable("Unknown loc info!");
4993     case CCValAssign::Full: break;
4994     case CCValAssign::AExt:
4995       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4996       break;
4997     case CCValAssign::ZExt:
4998       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4999                         DAG.getValueType(VA.getValVT()));
5000       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5001       break;
5002     case CCValAssign::SExt:
5003       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5004                         DAG.getValueType(VA.getValVT()));
5005       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5006       break;
5007     }
5008 
5009     InVals.push_back(Val);
5010   }
5011 
5012   return Chain;
5013 }
5014 
5015 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5016                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5017   // PatchPoint calls are not indirect.
5018   if (isPatchPoint)
5019     return false;
5020 
5021   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5022     return false;
5023 
5024   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5025   // becuase the immediate function pointer points to a descriptor instead of
5026   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5027   // pointer immediate points to the global entry point, while the BLA would
5028   // need to jump to the local entry point (see rL211174).
5029   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5030       isBLACompatibleAddress(Callee, DAG))
5031     return false;
5032 
5033   return true;
5034 }
5035 
5036 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5037                               const Function &Caller,
5038                               const SDValue &Callee,
5039                               const PPCSubtarget &Subtarget,
5040                               const TargetMachine &TM) {
5041   if (CFlags.IsTailCall)
5042     return PPCISD::TC_RETURN;
5043 
5044   // This is a call through a function pointer.
5045   if (CFlags.IsIndirect) {
5046     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5047     // indirect calls. The save of the caller's TOC pointer to the stack will be
5048     // inserted into the DAG as part of call lowering. The restore of the TOC
5049     // pointer is modeled by using a pseudo instruction for the call opcode that
5050     // represents the 2 instruction sequence of an indirect branch and link,
5051     // immediately followed by a load of the TOC pointer from the the stack save
5052     // slot into gpr2.
5053     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5054       return PPCISD::BCTRL_LOAD_TOC;
5055 
5056     // An indirect call that does not need a TOC restore.
5057     return PPCISD::BCTRL;
5058   }
5059 
5060   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5061   // immediately following the call instruction if the caller and callee may
5062   // have different TOC bases. At link time if the linker determines the calls
5063   // may not share a TOC base, the call is redirected to a trampoline inserted
5064   // by the linker. The trampoline will (among other things) save the callers
5065   // TOC pointer at an ABI designated offset in the linkage area and the linker
5066   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5067   // into gpr2.
5068   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5069     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5070                                                   : PPCISD::CALL_NOP;
5071 
5072   return PPCISD::CALL;
5073 }
5074 
5075 static bool isValidAIXExternalSymSDNode(StringRef SymName) {
5076   return StringSwitch<bool>(SymName)
5077       .Cases("__divdi3", "__fixunsdfdi", "__floatundidf", "__floatundisf",
5078              "__moddi3", "__udivdi3", "__umoddi3", true)
5079       .Cases("ceil", "floor", "memcpy", "memmove", "memset", "round", true)
5080       .Default(false);
5081 }
5082 
5083 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5084                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5085   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5086     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5087       return SDValue(Dest, 0);
5088 
5089   // Returns true if the callee is local, and false otherwise.
5090   auto isLocalCallee = [&]() {
5091     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5092     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5093     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5094 
5095     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5096            !dyn_cast_or_null<GlobalIFunc>(GV);
5097   };
5098 
5099   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5100   // a static relocation model causes some versions of GNU LD (2.17.50, at
5101   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5102   // built with secure-PLT.
5103   bool UsePlt =
5104       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5105       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5106 
5107   // On AIX, direct function calls reference the symbol for the function's
5108   // entry point, which is named by prepending a "." before the function's
5109   // C-linkage name.
5110   const auto getAIXFuncEntryPointSymbolSDNode =
5111       [&](StringRef FuncName, bool IsDeclaration,
5112           const XCOFF::StorageClass &SC) {
5113         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5114 
5115         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5116             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5117 
5118         if (IsDeclaration && !S->hasContainingCsect()) {
5119           // On AIX, an undefined symbol needs to be associated with a
5120           // MCSectionXCOFF to get the correct storage mapping class.
5121           // In this case, XCOFF::XMC_PR.
5122           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5123               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5124               SectionKind::getMetadata());
5125           S->setContainingCsect(Sec);
5126         }
5127 
5128         MVT PtrVT =
5129             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5130         return DAG.getMCSymbol(S, PtrVT);
5131       };
5132 
5133   if (isFunctionGlobalAddress(Callee)) {
5134     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5135     const GlobalValue *GV = G->getGlobal();
5136 
5137     if (!Subtarget.isAIXABI())
5138       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5139                                         UsePlt ? PPCII::MO_PLT : 0);
5140 
5141     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5142     const GlobalObject *GO = cast<GlobalObject>(GV);
5143     const XCOFF::StorageClass SC =
5144         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5145     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5146                                             SC);
5147   }
5148 
5149   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5150     const char *SymName = S->getSymbol();
5151     if (!Subtarget.isAIXABI())
5152       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5153                                          UsePlt ? PPCII::MO_PLT : 0);
5154 
5155     // If there exists a user-declared function whose name is the same as the
5156     // ExternalSymbol's, then we pick up the user-declared version.
5157     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5158     if (const Function *F =
5159             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5160       const XCOFF::StorageClass SC =
5161           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5162       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5163                                               SC);
5164     }
5165 
5166     // TODO: Remove this when the support for ExternalSymbolSDNode is complete.
5167     if (isValidAIXExternalSymSDNode(SymName)) {
5168       return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5169     }
5170 
5171     report_fatal_error("Unexpected ExternalSymbolSDNode: " + Twine(SymName));
5172   }
5173 
5174   // No transformation needed.
5175   assert(Callee.getNode() && "What no callee?");
5176   return Callee;
5177 }
5178 
5179 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5180   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5181          "Expected a CALLSEQ_STARTSDNode.");
5182 
5183   // The last operand is the chain, except when the node has glue. If the node
5184   // has glue, then the last operand is the glue, and the chain is the second
5185   // last operand.
5186   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5187   if (LastValue.getValueType() != MVT::Glue)
5188     return LastValue;
5189 
5190   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5191 }
5192 
5193 // Creates the node that moves a functions address into the count register
5194 // to prepare for an indirect call instruction.
5195 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5196                                 SDValue &Glue, SDValue &Chain,
5197                                 const SDLoc &dl) {
5198   SDValue MTCTROps[] = {Chain, Callee, Glue};
5199   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5200   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5201                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5202   // The glue is the second value produced.
5203   Glue = Chain.getValue(1);
5204 }
5205 
5206 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5207                                           SDValue &Glue, SDValue &Chain,
5208                                           SDValue CallSeqStart,
5209                                           ImmutableCallSite CS, const SDLoc &dl,
5210                                           bool hasNest,
5211                                           const PPCSubtarget &Subtarget) {
5212   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5213   // entry point, but to the function descriptor (the function entry point
5214   // address is part of the function descriptor though).
5215   // The function descriptor is a three doubleword structure with the
5216   // following fields: function entry point, TOC base address and
5217   // environment pointer.
5218   // Thus for a call through a function pointer, the following actions need
5219   // to be performed:
5220   //   1. Save the TOC of the caller in the TOC save area of its stack
5221   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5222   //   2. Load the address of the function entry point from the function
5223   //      descriptor.
5224   //   3. Load the TOC of the callee from the function descriptor into r2.
5225   //   4. Load the environment pointer from the function descriptor into
5226   //      r11.
5227   //   5. Branch to the function entry point address.
5228   //   6. On return of the callee, the TOC of the caller needs to be
5229   //      restored (this is done in FinishCall()).
5230   //
5231   // The loads are scheduled at the beginning of the call sequence, and the
5232   // register copies are flagged together to ensure that no other
5233   // operations can be scheduled in between. E.g. without flagging the
5234   // copies together, a TOC access in the caller could be scheduled between
5235   // the assignment of the callee TOC and the branch to the callee, which leads
5236   // to incorrect code.
5237 
5238   // Start by loading the function address from the descriptor.
5239   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5240   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5241                       ? (MachineMemOperand::MODereferenceable |
5242                          MachineMemOperand::MOInvariant)
5243                       : MachineMemOperand::MONone;
5244 
5245   MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5246 
5247   // Registers used in building the DAG.
5248   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5249   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5250 
5251   // Offsets of descriptor members.
5252   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5253   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5254 
5255   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5256   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5257 
5258   // One load for the functions entry point address.
5259   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5260                                     Alignment, MMOFlags);
5261 
5262   // One for loading the TOC anchor for the module that contains the called
5263   // function.
5264   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5265   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5266   SDValue TOCPtr =
5267       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5268                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5269 
5270   // One for loading the environment pointer.
5271   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5272   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5273   SDValue LoadEnvPtr =
5274       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5275                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5276 
5277 
5278   // Then copy the newly loaded TOC anchor to the TOC pointer.
5279   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5280   Chain = TOCVal.getValue(0);
5281   Glue = TOCVal.getValue(1);
5282 
5283   // If the function call has an explicit 'nest' parameter, it takes the
5284   // place of the environment pointer.
5285   assert((!hasNest || !Subtarget.isAIXABI()) &&
5286          "Nest parameter is not supported on AIX.");
5287   if (!hasNest) {
5288     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5289     Chain = EnvVal.getValue(0);
5290     Glue = EnvVal.getValue(1);
5291   }
5292 
5293   // The rest of the indirect call sequence is the same as the non-descriptor
5294   // DAG.
5295   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5296 }
5297 
5298 static void
5299 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5300                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5301                   SelectionDAG &DAG,
5302                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5303                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5304                   const PPCSubtarget &Subtarget) {
5305   const bool IsPPC64 = Subtarget.isPPC64();
5306   // MVT for a general purpose register.
5307   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5308 
5309   // First operand is always the chain.
5310   Ops.push_back(Chain);
5311 
5312   // If it's a direct call pass the callee as the second operand.
5313   if (!CFlags.IsIndirect)
5314     Ops.push_back(Callee);
5315   else {
5316     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5317 
5318     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5319     // on the stack (this would have been done in `LowerCall_64SVR4` or
5320     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5321     // represents both the indirect branch and a load that restores the TOC
5322     // pointer from the linkage area. The operand for the TOC restore is an add
5323     // of the TOC save offset to the stack pointer. This must be the second
5324     // operand: after the chain input but before any other variadic arguments.
5325     if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5326       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5327 
5328       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5329       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5330       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5331       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5332       Ops.push_back(AddTOC);
5333     }
5334 
5335     // Add the register used for the environment pointer.
5336     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5337       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5338                                     RegVT));
5339 
5340 
5341     // Add CTR register as callee so a bctr can be emitted later.
5342     if (CFlags.IsTailCall)
5343       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5344   }
5345 
5346   // If this is a tail call add stack pointer delta.
5347   if (CFlags.IsTailCall)
5348     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5349 
5350   // Add argument registers to the end of the list so that they are known live
5351   // into the call.
5352   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5353     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5354                                   RegsToPass[i].second.getValueType()));
5355 
5356   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5357   // no way to mark dependencies as implicit here.
5358   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5359   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5360       !CFlags.IsPatchPoint)
5361     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5362 
5363   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5364   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5365     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5366 
5367   // Add a register mask operand representing the call-preserved registers.
5368   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5369   const uint32_t *Mask =
5370       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5371   assert(Mask && "Missing call preserved mask for calling convention");
5372   Ops.push_back(DAG.getRegisterMask(Mask));
5373 
5374   // If the glue is valid, it is the last operand.
5375   if (Glue.getNode())
5376     Ops.push_back(Glue);
5377 }
5378 
5379 SDValue PPCTargetLowering::FinishCall(
5380     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5381     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5382     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5383     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5384     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5385 
5386   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI())
5387     setUsesTOCBasePtr(DAG);
5388 
5389   unsigned CallOpc =
5390       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5391                     Subtarget, DAG.getTarget());
5392 
5393   if (!CFlags.IsIndirect)
5394     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5395   else if (Subtarget.usesFunctionDescriptors())
5396     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS,
5397                                   dl, CFlags.HasNest, Subtarget);
5398   else
5399     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5400 
5401   // Build the operand list for the call instruction.
5402   SmallVector<SDValue, 8> Ops;
5403   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5404                     SPDiff, Subtarget);
5405 
5406   // Emit tail call.
5407   if (CFlags.IsTailCall) {
5408     assert(((Callee.getOpcode() == ISD::Register &&
5409              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5410             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5411             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5412             isa<ConstantSDNode>(Callee)) &&
5413            "Expecting a global address, external symbol, absolute value or "
5414            "register");
5415     assert(CallOpc == PPCISD::TC_RETURN &&
5416            "Unexpected call opcode for a tail call.");
5417     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5418     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5419   }
5420 
5421   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5422   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5423   Glue = Chain.getValue(1);
5424 
5425   // When performing tail call optimization the callee pops its arguments off
5426   // the stack. Account for this here so these bytes can be pushed back on in
5427   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5428   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5429                          getTargetMachine().Options.GuaranteedTailCallOpt)
5430                             ? NumBytes
5431                             : 0;
5432 
5433   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5434                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5435                              Glue, dl);
5436   Glue = Chain.getValue(1);
5437 
5438   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5439                          DAG, InVals);
5440 }
5441 
5442 SDValue
5443 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5444                              SmallVectorImpl<SDValue> &InVals) const {
5445   SelectionDAG &DAG                     = CLI.DAG;
5446   SDLoc &dl                             = CLI.DL;
5447   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5448   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5449   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5450   SDValue Chain                         = CLI.Chain;
5451   SDValue Callee                        = CLI.Callee;
5452   bool &isTailCall                      = CLI.IsTailCall;
5453   CallingConv::ID CallConv              = CLI.CallConv;
5454   bool isVarArg                         = CLI.IsVarArg;
5455   bool isPatchPoint                     = CLI.IsPatchPoint;
5456   ImmutableCallSite CS                  = CLI.CS;
5457 
5458   if (isTailCall) {
5459     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5460       isTailCall = false;
5461     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5462       isTailCall =
5463         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5464                                                  isVarArg, Outs, Ins, DAG);
5465     else
5466       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5467                                                      Ins, DAG);
5468     if (isTailCall) {
5469       ++NumTailCalls;
5470       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5471         ++NumSiblingCalls;
5472 
5473       assert(isa<GlobalAddressSDNode>(Callee) &&
5474              "Callee should be an llvm::Function object.");
5475       LLVM_DEBUG(
5476           const GlobalValue *GV =
5477               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5478           const unsigned Width =
5479               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5480           dbgs() << "TCO caller: "
5481                  << left_justify(DAG.getMachineFunction().getName(), Width)
5482                  << ", callee linkage: " << GV->getVisibility() << ", "
5483                  << GV->getLinkage() << "\n");
5484     }
5485   }
5486 
5487   if (!isTailCall && CS && CS.isMustTailCall())
5488     report_fatal_error("failed to perform tail call elimination on a call "
5489                        "site marked musttail");
5490 
5491   // When long calls (i.e. indirect calls) are always used, calls are always
5492   // made via function pointer. If we have a function name, first translate it
5493   // into a pointer.
5494   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5495       !isTailCall)
5496     Callee = LowerGlobalAddress(Callee, DAG);
5497 
5498   CallFlags CFlags(
5499       CallConv, isTailCall, isVarArg, isPatchPoint,
5500       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5501       // hasNest
5502       Subtarget.is64BitELFABI() &&
5503           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }));
5504 
5505   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5506     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5507                             InVals, CS);
5508 
5509   if (Subtarget.isSVR4ABI())
5510     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5511                             InVals, CS);
5512 
5513   if (Subtarget.isAIXABI())
5514     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5515                          InVals, CS);
5516 
5517   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5518                           InVals, CS);
5519 }
5520 
5521 SDValue PPCTargetLowering::LowerCall_32SVR4(
5522     SDValue Chain, SDValue Callee, CallFlags CFlags,
5523     const SmallVectorImpl<ISD::OutputArg> &Outs,
5524     const SmallVectorImpl<SDValue> &OutVals,
5525     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5526     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5527     ImmutableCallSite CS) const {
5528   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5529   // of the 32-bit SVR4 ABI stack frame layout.
5530 
5531   const CallingConv::ID CallConv = CFlags.CallConv;
5532   const bool IsVarArg = CFlags.IsVarArg;
5533   const bool IsTailCall = CFlags.IsTailCall;
5534 
5535   assert((CallConv == CallingConv::C ||
5536           CallConv == CallingConv::Cold ||
5537           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5538 
5539   unsigned PtrByteSize = 4;
5540 
5541   MachineFunction &MF = DAG.getMachineFunction();
5542 
5543   // Mark this function as potentially containing a function that contains a
5544   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5545   // and restoring the callers stack pointer in this functions epilog. This is
5546   // done because by tail calling the called function might overwrite the value
5547   // in this function's (MF) stack pointer stack slot 0(SP).
5548   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5549       CallConv == CallingConv::Fast)
5550     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5551 
5552   // Count how many bytes are to be pushed on the stack, including the linkage
5553   // area, parameter list area and the part of the local variable space which
5554   // contains copies of aggregates which are passed by value.
5555 
5556   // Assign locations to all of the outgoing arguments.
5557   SmallVector<CCValAssign, 16> ArgLocs;
5558   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5559 
5560   // Reserve space for the linkage area on the stack.
5561   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5562                        PtrByteSize);
5563   if (useSoftFloat())
5564     CCInfo.PreAnalyzeCallOperands(Outs);
5565 
5566   if (IsVarArg) {
5567     // Handle fixed and variable vector arguments differently.
5568     // Fixed vector arguments go into registers as long as registers are
5569     // available. Variable vector arguments always go into memory.
5570     unsigned NumArgs = Outs.size();
5571 
5572     for (unsigned i = 0; i != NumArgs; ++i) {
5573       MVT ArgVT = Outs[i].VT;
5574       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5575       bool Result;
5576 
5577       if (Outs[i].IsFixed) {
5578         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5579                                CCInfo);
5580       } else {
5581         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5582                                       ArgFlags, CCInfo);
5583       }
5584 
5585       if (Result) {
5586 #ifndef NDEBUG
5587         errs() << "Call operand #" << i << " has unhandled type "
5588              << EVT(ArgVT).getEVTString() << "\n";
5589 #endif
5590         llvm_unreachable(nullptr);
5591       }
5592     }
5593   } else {
5594     // All arguments are treated the same.
5595     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5596   }
5597   CCInfo.clearWasPPCF128();
5598 
5599   // Assign locations to all of the outgoing aggregate by value arguments.
5600   SmallVector<CCValAssign, 16> ByValArgLocs;
5601   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5602 
5603   // Reserve stack space for the allocations in CCInfo.
5604   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5605 
5606   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5607 
5608   // Size of the linkage area, parameter list area and the part of the local
5609   // space variable where copies of aggregates which are passed by value are
5610   // stored.
5611   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5612 
5613   // Calculate by how many bytes the stack has to be adjusted in case of tail
5614   // call optimization.
5615   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5616 
5617   // Adjust the stack pointer for the new arguments...
5618   // These operations are automatically eliminated by the prolog/epilog pass
5619   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5620   SDValue CallSeqStart = Chain;
5621 
5622   // Load the return address and frame pointer so it can be moved somewhere else
5623   // later.
5624   SDValue LROp, FPOp;
5625   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5626 
5627   // Set up a copy of the stack pointer for use loading and storing any
5628   // arguments that may not fit in the registers available for argument
5629   // passing.
5630   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5631 
5632   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5633   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5634   SmallVector<SDValue, 8> MemOpChains;
5635 
5636   bool seenFloatArg = false;
5637   // Walk the register/memloc assignments, inserting copies/loads.
5638   // i - Tracks the index into the list of registers allocated for the call
5639   // RealArgIdx - Tracks the index into the list of actual function arguments
5640   // j - Tracks the index into the list of byval arguments
5641   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5642        i != e;
5643        ++i, ++RealArgIdx) {
5644     CCValAssign &VA = ArgLocs[i];
5645     SDValue Arg = OutVals[RealArgIdx];
5646     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5647 
5648     if (Flags.isByVal()) {
5649       // Argument is an aggregate which is passed by value, thus we need to
5650       // create a copy of it in the local variable space of the current stack
5651       // frame (which is the stack frame of the caller) and pass the address of
5652       // this copy to the callee.
5653       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5654       CCValAssign &ByValVA = ByValArgLocs[j++];
5655       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5656 
5657       // Memory reserved in the local variable space of the callers stack frame.
5658       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5659 
5660       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5661       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5662                            StackPtr, PtrOff);
5663 
5664       // Create a copy of the argument in the local area of the current
5665       // stack frame.
5666       SDValue MemcpyCall =
5667         CreateCopyOfByValArgument(Arg, PtrOff,
5668                                   CallSeqStart.getNode()->getOperand(0),
5669                                   Flags, DAG, dl);
5670 
5671       // This must go outside the CALLSEQ_START..END.
5672       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5673                                                      SDLoc(MemcpyCall));
5674       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5675                              NewCallSeqStart.getNode());
5676       Chain = CallSeqStart = NewCallSeqStart;
5677 
5678       // Pass the address of the aggregate copy on the stack either in a
5679       // physical register or in the parameter list area of the current stack
5680       // frame to the callee.
5681       Arg = PtrOff;
5682     }
5683 
5684     // When useCRBits() is true, there can be i1 arguments.
5685     // It is because getRegisterType(MVT::i1) => MVT::i1,
5686     // and for other integer types getRegisterType() => MVT::i32.
5687     // Extend i1 and ensure callee will get i32.
5688     if (Arg.getValueType() == MVT::i1)
5689       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5690                         dl, MVT::i32, Arg);
5691 
5692     if (VA.isRegLoc()) {
5693       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5694       // Put argument in a physical register.
5695       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5696         bool IsLE = Subtarget.isLittleEndian();
5697         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5698                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5699         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5700         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5701                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5702         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5703                              SVal.getValue(0)));
5704       } else
5705         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5706     } else {
5707       // Put argument in the parameter list area of the current stack frame.
5708       assert(VA.isMemLoc());
5709       unsigned LocMemOffset = VA.getLocMemOffset();
5710 
5711       if (!IsTailCall) {
5712         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5713         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5714                              StackPtr, PtrOff);
5715 
5716         MemOpChains.push_back(
5717             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5718       } else {
5719         // Calculate and remember argument location.
5720         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5721                                  TailCallArguments);
5722       }
5723     }
5724   }
5725 
5726   if (!MemOpChains.empty())
5727     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5728 
5729   // Build a sequence of copy-to-reg nodes chained together with token chain
5730   // and flag operands which copy the outgoing args into the appropriate regs.
5731   SDValue InFlag;
5732   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5733     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5734                              RegsToPass[i].second, InFlag);
5735     InFlag = Chain.getValue(1);
5736   }
5737 
5738   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5739   // registers.
5740   if (IsVarArg) {
5741     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5742     SDValue Ops[] = { Chain, InFlag };
5743 
5744     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5745                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5746 
5747     InFlag = Chain.getValue(1);
5748   }
5749 
5750   if (IsTailCall)
5751     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5752                     TailCallArguments);
5753 
5754   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5755                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
5756 }
5757 
5758 // Copy an argument into memory, being careful to do this outside the
5759 // call sequence for the call to which the argument belongs.
5760 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5761     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5762     SelectionDAG &DAG, const SDLoc &dl) const {
5763   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5764                         CallSeqStart.getNode()->getOperand(0),
5765                         Flags, DAG, dl);
5766   // The MEMCPY must go outside the CALLSEQ_START..END.
5767   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5768   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5769                                                  SDLoc(MemcpyCall));
5770   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5771                          NewCallSeqStart.getNode());
5772   return NewCallSeqStart;
5773 }
5774 
5775 SDValue PPCTargetLowering::LowerCall_64SVR4(
5776     SDValue Chain, SDValue Callee, CallFlags CFlags,
5777     const SmallVectorImpl<ISD::OutputArg> &Outs,
5778     const SmallVectorImpl<SDValue> &OutVals,
5779     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5780     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5781     ImmutableCallSite CS) const {
5782   bool isELFv2ABI = Subtarget.isELFv2ABI();
5783   bool isLittleEndian = Subtarget.isLittleEndian();
5784   unsigned NumOps = Outs.size();
5785   bool IsSibCall = false;
5786   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5787 
5788   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5789   unsigned PtrByteSize = 8;
5790 
5791   MachineFunction &MF = DAG.getMachineFunction();
5792 
5793   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5794     IsSibCall = true;
5795 
5796   // Mark this function as potentially containing a function that contains a
5797   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5798   // and restoring the callers stack pointer in this functions epilog. This is
5799   // done because by tail calling the called function might overwrite the value
5800   // in this function's (MF) stack pointer stack slot 0(SP).
5801   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5802     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5803 
5804   assert(!(IsFastCall && CFlags.IsVarArg) &&
5805          "fastcc not supported on varargs functions");
5806 
5807   // Count how many bytes are to be pushed on the stack, including the linkage
5808   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5809   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5810   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5811   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5812   unsigned NumBytes = LinkageSize;
5813   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5814   unsigned &QFPR_idx = FPR_idx;
5815 
5816   static const MCPhysReg GPR[] = {
5817     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5818     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5819   };
5820   static const MCPhysReg VR[] = {
5821     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5822     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5823   };
5824 
5825   const unsigned NumGPRs = array_lengthof(GPR);
5826   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5827   const unsigned NumVRs  = array_lengthof(VR);
5828   const unsigned NumQFPRs = NumFPRs;
5829 
5830   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5831   // can be passed to the callee in registers.
5832   // For the fast calling convention, there is another check below.
5833   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5834   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5835   if (!HasParameterArea) {
5836     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5837     unsigned AvailableFPRs = NumFPRs;
5838     unsigned AvailableVRs = NumVRs;
5839     unsigned NumBytesTmp = NumBytes;
5840     for (unsigned i = 0; i != NumOps; ++i) {
5841       if (Outs[i].Flags.isNest()) continue;
5842       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5843                                 PtrByteSize, LinkageSize, ParamAreaSize,
5844                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5845                                 Subtarget.hasQPX()))
5846         HasParameterArea = true;
5847     }
5848   }
5849 
5850   // When using the fast calling convention, we don't provide backing for
5851   // arguments that will be in registers.
5852   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5853 
5854   // Avoid allocating parameter area for fastcc functions if all the arguments
5855   // can be passed in the registers.
5856   if (IsFastCall)
5857     HasParameterArea = false;
5858 
5859   // Add up all the space actually used.
5860   for (unsigned i = 0; i != NumOps; ++i) {
5861     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5862     EVT ArgVT = Outs[i].VT;
5863     EVT OrigVT = Outs[i].ArgVT;
5864 
5865     if (Flags.isNest())
5866       continue;
5867 
5868     if (IsFastCall) {
5869       if (Flags.isByVal()) {
5870         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5871         if (NumGPRsUsed > NumGPRs)
5872           HasParameterArea = true;
5873       } else {
5874         switch (ArgVT.getSimpleVT().SimpleTy) {
5875         default: llvm_unreachable("Unexpected ValueType for argument!");
5876         case MVT::i1:
5877         case MVT::i32:
5878         case MVT::i64:
5879           if (++NumGPRsUsed <= NumGPRs)
5880             continue;
5881           break;
5882         case MVT::v4i32:
5883         case MVT::v8i16:
5884         case MVT::v16i8:
5885         case MVT::v2f64:
5886         case MVT::v2i64:
5887         case MVT::v1i128:
5888         case MVT::f128:
5889           if (++NumVRsUsed <= NumVRs)
5890             continue;
5891           break;
5892         case MVT::v4f32:
5893           // When using QPX, this is handled like a FP register, otherwise, it
5894           // is an Altivec register.
5895           if (Subtarget.hasQPX()) {
5896             if (++NumFPRsUsed <= NumFPRs)
5897               continue;
5898           } else {
5899             if (++NumVRsUsed <= NumVRs)
5900               continue;
5901           }
5902           break;
5903         case MVT::f32:
5904         case MVT::f64:
5905         case MVT::v4f64: // QPX
5906         case MVT::v4i1:  // QPX
5907           if (++NumFPRsUsed <= NumFPRs)
5908             continue;
5909           break;
5910         }
5911         HasParameterArea = true;
5912       }
5913     }
5914 
5915     /* Respect alignment of argument on the stack.  */
5916     auto Alignement =
5917         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5918     NumBytes = alignTo(NumBytes, Alignement);
5919 
5920     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5921     if (Flags.isInConsecutiveRegsLast())
5922       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5923   }
5924 
5925   unsigned NumBytesActuallyUsed = NumBytes;
5926 
5927   // In the old ELFv1 ABI,
5928   // the prolog code of the callee may store up to 8 GPR argument registers to
5929   // the stack, allowing va_start to index over them in memory if its varargs.
5930   // Because we cannot tell if this is needed on the caller side, we have to
5931   // conservatively assume that it is needed.  As such, make sure we have at
5932   // least enough stack space for the caller to store the 8 GPRs.
5933   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5934   // really requires memory operands, e.g. a vararg function.
5935   if (HasParameterArea)
5936     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5937   else
5938     NumBytes = LinkageSize;
5939 
5940   // Tail call needs the stack to be aligned.
5941   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5942     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5943 
5944   int SPDiff = 0;
5945 
5946   // Calculate by how many bytes the stack has to be adjusted in case of tail
5947   // call optimization.
5948   if (!IsSibCall)
5949     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
5950 
5951   // To protect arguments on the stack from being clobbered in a tail call,
5952   // force all the loads to happen before doing any other lowering.
5953   if (CFlags.IsTailCall)
5954     Chain = DAG.getStackArgumentTokenFactor(Chain);
5955 
5956   // Adjust the stack pointer for the new arguments...
5957   // These operations are automatically eliminated by the prolog/epilog pass
5958   if (!IsSibCall)
5959     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5960   SDValue CallSeqStart = Chain;
5961 
5962   // Load the return address and frame pointer so it can be move somewhere else
5963   // later.
5964   SDValue LROp, FPOp;
5965   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5966 
5967   // Set up a copy of the stack pointer for use loading and storing any
5968   // arguments that may not fit in the registers available for argument
5969   // passing.
5970   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5971 
5972   // Figure out which arguments are going to go in registers, and which in
5973   // memory.  Also, if this is a vararg function, floating point operations
5974   // must be stored to our stack, and loaded into integer regs as well, if
5975   // any integer regs are available for argument passing.
5976   unsigned ArgOffset = LinkageSize;
5977 
5978   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5979   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5980 
5981   SmallVector<SDValue, 8> MemOpChains;
5982   for (unsigned i = 0; i != NumOps; ++i) {
5983     SDValue Arg = OutVals[i];
5984     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5985     EVT ArgVT = Outs[i].VT;
5986     EVT OrigVT = Outs[i].ArgVT;
5987 
5988     // PtrOff will be used to store the current argument to the stack if a
5989     // register cannot be found for it.
5990     SDValue PtrOff;
5991 
5992     // We re-align the argument offset for each argument, except when using the
5993     // fast calling convention, when we need to make sure we do that only when
5994     // we'll actually use a stack slot.
5995     auto ComputePtrOff = [&]() {
5996       /* Respect alignment of argument on the stack.  */
5997       auto Alignment =
5998           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5999       ArgOffset = alignTo(ArgOffset, Alignment);
6000 
6001       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6002 
6003       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6004     };
6005 
6006     if (!IsFastCall) {
6007       ComputePtrOff();
6008 
6009       /* Compute GPR index associated with argument offset.  */
6010       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6011       GPR_idx = std::min(GPR_idx, NumGPRs);
6012     }
6013 
6014     // Promote integers to 64-bit values.
6015     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6016       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6017       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6018       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6019     }
6020 
6021     // FIXME memcpy is used way more than necessary.  Correctness first.
6022     // Note: "by value" is code for passing a structure by value, not
6023     // basic types.
6024     if (Flags.isByVal()) {
6025       // Note: Size includes alignment padding, so
6026       //   struct x { short a; char b; }
6027       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6028       // These are the proper values we need for right-justifying the
6029       // aggregate in a parameter register.
6030       unsigned Size = Flags.getByValSize();
6031 
6032       // An empty aggregate parameter takes up no storage and no
6033       // registers.
6034       if (Size == 0)
6035         continue;
6036 
6037       if (IsFastCall)
6038         ComputePtrOff();
6039 
6040       // All aggregates smaller than 8 bytes must be passed right-justified.
6041       if (Size==1 || Size==2 || Size==4) {
6042         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6043         if (GPR_idx != NumGPRs) {
6044           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6045                                         MachinePointerInfo(), VT);
6046           MemOpChains.push_back(Load.getValue(1));
6047           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6048 
6049           ArgOffset += PtrByteSize;
6050           continue;
6051         }
6052       }
6053 
6054       if (GPR_idx == NumGPRs && Size < 8) {
6055         SDValue AddPtr = PtrOff;
6056         if (!isLittleEndian) {
6057           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6058                                           PtrOff.getValueType());
6059           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6060         }
6061         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6062                                                           CallSeqStart,
6063                                                           Flags, DAG, dl);
6064         ArgOffset += PtrByteSize;
6065         continue;
6066       }
6067       // Copy entire object into memory.  There are cases where gcc-generated
6068       // code assumes it is there, even if it could be put entirely into
6069       // registers.  (This is not what the doc says.)
6070 
6071       // FIXME: The above statement is likely due to a misunderstanding of the
6072       // documents.  All arguments must be copied into the parameter area BY
6073       // THE CALLEE in the event that the callee takes the address of any
6074       // formal argument.  That has not yet been implemented.  However, it is
6075       // reasonable to use the stack area as a staging area for the register
6076       // load.
6077 
6078       // Skip this for small aggregates, as we will use the same slot for a
6079       // right-justified copy, below.
6080       if (Size >= 8)
6081         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6082                                                           CallSeqStart,
6083                                                           Flags, DAG, dl);
6084 
6085       // When a register is available, pass a small aggregate right-justified.
6086       if (Size < 8 && GPR_idx != NumGPRs) {
6087         // The easiest way to get this right-justified in a register
6088         // is to copy the structure into the rightmost portion of a
6089         // local variable slot, then load the whole slot into the
6090         // register.
6091         // FIXME: The memcpy seems to produce pretty awful code for
6092         // small aggregates, particularly for packed ones.
6093         // FIXME: It would be preferable to use the slot in the
6094         // parameter save area instead of a new local variable.
6095         SDValue AddPtr = PtrOff;
6096         if (!isLittleEndian) {
6097           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6098           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6099         }
6100         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6101                                                           CallSeqStart,
6102                                                           Flags, DAG, dl);
6103 
6104         // Load the slot into the register.
6105         SDValue Load =
6106             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6107         MemOpChains.push_back(Load.getValue(1));
6108         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6109 
6110         // Done with this argument.
6111         ArgOffset += PtrByteSize;
6112         continue;
6113       }
6114 
6115       // For aggregates larger than PtrByteSize, copy the pieces of the
6116       // object that fit into registers from the parameter save area.
6117       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6118         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6119         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6120         if (GPR_idx != NumGPRs) {
6121           SDValue Load =
6122               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6123           MemOpChains.push_back(Load.getValue(1));
6124           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6125           ArgOffset += PtrByteSize;
6126         } else {
6127           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6128           break;
6129         }
6130       }
6131       continue;
6132     }
6133 
6134     switch (Arg.getSimpleValueType().SimpleTy) {
6135     default: llvm_unreachable("Unexpected ValueType for argument!");
6136     case MVT::i1:
6137     case MVT::i32:
6138     case MVT::i64:
6139       if (Flags.isNest()) {
6140         // The 'nest' parameter, if any, is passed in R11.
6141         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6142         break;
6143       }
6144 
6145       // These can be scalar arguments or elements of an integer array type
6146       // passed directly.  Clang may use those instead of "byval" aggregate
6147       // types to avoid forcing arguments to memory unnecessarily.
6148       if (GPR_idx != NumGPRs) {
6149         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6150       } else {
6151         if (IsFastCall)
6152           ComputePtrOff();
6153 
6154         assert(HasParameterArea &&
6155                "Parameter area must exist to pass an argument in memory.");
6156         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6157                          true, CFlags.IsTailCall, false, MemOpChains,
6158                          TailCallArguments, dl);
6159         if (IsFastCall)
6160           ArgOffset += PtrByteSize;
6161       }
6162       if (!IsFastCall)
6163         ArgOffset += PtrByteSize;
6164       break;
6165     case MVT::f32:
6166     case MVT::f64: {
6167       // These can be scalar arguments or elements of a float array type
6168       // passed directly.  The latter are used to implement ELFv2 homogenous
6169       // float aggregates.
6170 
6171       // Named arguments go into FPRs first, and once they overflow, the
6172       // remaining arguments go into GPRs and then the parameter save area.
6173       // Unnamed arguments for vararg functions always go to GPRs and
6174       // then the parameter save area.  For now, put all arguments to vararg
6175       // routines always in both locations (FPR *and* GPR or stack slot).
6176       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6177       bool NeededLoad = false;
6178 
6179       // First load the argument into the next available FPR.
6180       if (FPR_idx != NumFPRs)
6181         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6182 
6183       // Next, load the argument into GPR or stack slot if needed.
6184       if (!NeedGPROrStack)
6185         ;
6186       else if (GPR_idx != NumGPRs && !IsFastCall) {
6187         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6188         // once we support fp <-> gpr moves.
6189 
6190         // In the non-vararg case, this can only ever happen in the
6191         // presence of f32 array types, since otherwise we never run
6192         // out of FPRs before running out of GPRs.
6193         SDValue ArgVal;
6194 
6195         // Double values are always passed in a single GPR.
6196         if (Arg.getValueType() != MVT::f32) {
6197           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6198 
6199         // Non-array float values are extended and passed in a GPR.
6200         } else if (!Flags.isInConsecutiveRegs()) {
6201           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6202           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6203 
6204         // If we have an array of floats, we collect every odd element
6205         // together with its predecessor into one GPR.
6206         } else if (ArgOffset % PtrByteSize != 0) {
6207           SDValue Lo, Hi;
6208           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6209           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6210           if (!isLittleEndian)
6211             std::swap(Lo, Hi);
6212           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6213 
6214         // The final element, if even, goes into the first half of a GPR.
6215         } else if (Flags.isInConsecutiveRegsLast()) {
6216           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6217           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6218           if (!isLittleEndian)
6219             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6220                                  DAG.getConstant(32, dl, MVT::i32));
6221 
6222         // Non-final even elements are skipped; they will be handled
6223         // together the with subsequent argument on the next go-around.
6224         } else
6225           ArgVal = SDValue();
6226 
6227         if (ArgVal.getNode())
6228           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6229       } else {
6230         if (IsFastCall)
6231           ComputePtrOff();
6232 
6233         // Single-precision floating-point values are mapped to the
6234         // second (rightmost) word of the stack doubleword.
6235         if (Arg.getValueType() == MVT::f32 &&
6236             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6237           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6238           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6239         }
6240 
6241         assert(HasParameterArea &&
6242                "Parameter area must exist to pass an argument in memory.");
6243         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6244                          true, CFlags.IsTailCall, false, MemOpChains,
6245                          TailCallArguments, dl);
6246 
6247         NeededLoad = true;
6248       }
6249       // When passing an array of floats, the array occupies consecutive
6250       // space in the argument area; only round up to the next doubleword
6251       // at the end of the array.  Otherwise, each float takes 8 bytes.
6252       if (!IsFastCall || NeededLoad) {
6253         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6254                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6255         if (Flags.isInConsecutiveRegsLast())
6256           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6257       }
6258       break;
6259     }
6260     case MVT::v4f32:
6261     case MVT::v4i32:
6262     case MVT::v8i16:
6263     case MVT::v16i8:
6264     case MVT::v2f64:
6265     case MVT::v2i64:
6266     case MVT::v1i128:
6267     case MVT::f128:
6268       if (!Subtarget.hasQPX()) {
6269       // These can be scalar arguments or elements of a vector array type
6270       // passed directly.  The latter are used to implement ELFv2 homogenous
6271       // vector aggregates.
6272 
6273       // For a varargs call, named arguments go into VRs or on the stack as
6274       // usual; unnamed arguments always go to the stack or the corresponding
6275       // GPRs when within range.  For now, we always put the value in both
6276       // locations (or even all three).
6277       if (CFlags.IsVarArg) {
6278         assert(HasParameterArea &&
6279                "Parameter area must exist if we have a varargs call.");
6280         // We could elide this store in the case where the object fits
6281         // entirely in R registers.  Maybe later.
6282         SDValue Store =
6283             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6284         MemOpChains.push_back(Store);
6285         if (VR_idx != NumVRs) {
6286           SDValue Load =
6287               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6288           MemOpChains.push_back(Load.getValue(1));
6289           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6290         }
6291         ArgOffset += 16;
6292         for (unsigned i=0; i<16; i+=PtrByteSize) {
6293           if (GPR_idx == NumGPRs)
6294             break;
6295           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6296                                    DAG.getConstant(i, dl, PtrVT));
6297           SDValue Load =
6298               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6299           MemOpChains.push_back(Load.getValue(1));
6300           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6301         }
6302         break;
6303       }
6304 
6305       // Non-varargs Altivec params go into VRs or on the stack.
6306       if (VR_idx != NumVRs) {
6307         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6308       } else {
6309         if (IsFastCall)
6310           ComputePtrOff();
6311 
6312         assert(HasParameterArea &&
6313                "Parameter area must exist to pass an argument in memory.");
6314         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6315                          true, CFlags.IsTailCall, true, MemOpChains,
6316                          TailCallArguments, dl);
6317         if (IsFastCall)
6318           ArgOffset += 16;
6319       }
6320 
6321       if (!IsFastCall)
6322         ArgOffset += 16;
6323       break;
6324       } // not QPX
6325 
6326       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6327              "Invalid QPX parameter type");
6328 
6329       LLVM_FALLTHROUGH;
6330     case MVT::v4f64:
6331     case MVT::v4i1: {
6332       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6333       if (CFlags.IsVarArg) {
6334         assert(HasParameterArea &&
6335                "Parameter area must exist if we have a varargs call.");
6336         // We could elide this store in the case where the object fits
6337         // entirely in R registers.  Maybe later.
6338         SDValue Store =
6339             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6340         MemOpChains.push_back(Store);
6341         if (QFPR_idx != NumQFPRs) {
6342           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6343                                      PtrOff, MachinePointerInfo());
6344           MemOpChains.push_back(Load.getValue(1));
6345           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6346         }
6347         ArgOffset += (IsF32 ? 16 : 32);
6348         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6349           if (GPR_idx == NumGPRs)
6350             break;
6351           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6352                                    DAG.getConstant(i, dl, PtrVT));
6353           SDValue Load =
6354               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6355           MemOpChains.push_back(Load.getValue(1));
6356           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6357         }
6358         break;
6359       }
6360 
6361       // Non-varargs QPX params go into registers or on the stack.
6362       if (QFPR_idx != NumQFPRs) {
6363         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6364       } else {
6365         if (IsFastCall)
6366           ComputePtrOff();
6367 
6368         assert(HasParameterArea &&
6369                "Parameter area must exist to pass an argument in memory.");
6370         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6371                          true, CFlags.IsTailCall, true, MemOpChains,
6372                          TailCallArguments, dl);
6373         if (IsFastCall)
6374           ArgOffset += (IsF32 ? 16 : 32);
6375       }
6376 
6377       if (!IsFastCall)
6378         ArgOffset += (IsF32 ? 16 : 32);
6379       break;
6380       }
6381     }
6382   }
6383 
6384   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6385          "mismatch in size of parameter area");
6386   (void)NumBytesActuallyUsed;
6387 
6388   if (!MemOpChains.empty())
6389     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6390 
6391   // Check if this is an indirect call (MTCTR/BCTRL).
6392   // See prepareDescriptorIndirectCall and buildCallOperands for more
6393   // information about calls through function pointers in the 64-bit SVR4 ABI.
6394   if (CFlags.IsIndirect) {
6395     assert(!CFlags.IsTailCall &&  "Indirect tails calls not supported");
6396     // Load r2 into a virtual register and store it to the TOC save area.
6397     setUsesTOCBasePtr(DAG);
6398     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6399     // TOC save area offset.
6400     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6401     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6402     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6403     Chain = DAG.getStore(
6404         Val.getValue(1), dl, Val, AddPtr,
6405         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6406     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6407     // This does not mean the MTCTR instruction must use R12; it's easier
6408     // to model this as an extra parameter, so do that.
6409     if (isELFv2ABI && !CFlags.IsPatchPoint)
6410       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6411   }
6412 
6413   // Build a sequence of copy-to-reg nodes chained together with token chain
6414   // and flag operands which copy the outgoing args into the appropriate regs.
6415   SDValue InFlag;
6416   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6417     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6418                              RegsToPass[i].second, InFlag);
6419     InFlag = Chain.getValue(1);
6420   }
6421 
6422   if (CFlags.IsTailCall && !IsSibCall)
6423     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6424                     TailCallArguments);
6425 
6426   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6427                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
6428 }
6429 
6430 SDValue PPCTargetLowering::LowerCall_Darwin(
6431     SDValue Chain, SDValue Callee, CallFlags CFlags,
6432     const SmallVectorImpl<ISD::OutputArg> &Outs,
6433     const SmallVectorImpl<SDValue> &OutVals,
6434     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6435     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6436     ImmutableCallSite CS) const {
6437   unsigned NumOps = Outs.size();
6438 
6439   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6440   bool isPPC64 = PtrVT == MVT::i64;
6441   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6442 
6443   MachineFunction &MF = DAG.getMachineFunction();
6444 
6445   // Mark this function as potentially containing a function that contains a
6446   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6447   // and restoring the callers stack pointer in this functions epilog. This is
6448   // done because by tail calling the called function might overwrite the value
6449   // in this function's (MF) stack pointer stack slot 0(SP).
6450   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6451       CFlags.CallConv == CallingConv::Fast)
6452     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6453 
6454   // Count how many bytes are to be pushed on the stack, including the linkage
6455   // area, and parameter passing area.  We start with 24/48 bytes, which is
6456   // prereserved space for [SP][CR][LR][3 x unused].
6457   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6458   unsigned NumBytes = LinkageSize;
6459 
6460   // Add up all the space actually used.
6461   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6462   // they all go in registers, but we must reserve stack space for them for
6463   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6464   // assigned stack space in order, with padding so Altivec parameters are
6465   // 16-byte aligned.
6466   unsigned nAltivecParamsAtEnd = 0;
6467   for (unsigned i = 0; i != NumOps; ++i) {
6468     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6469     EVT ArgVT = Outs[i].VT;
6470     // Varargs Altivec parameters are padded to a 16 byte boundary.
6471     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6472         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6473         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6474       if (!CFlags.IsVarArg && !isPPC64) {
6475         // Non-varargs Altivec parameters go after all the non-Altivec
6476         // parameters; handle those later so we know how much padding we need.
6477         nAltivecParamsAtEnd++;
6478         continue;
6479       }
6480       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6481       NumBytes = ((NumBytes+15)/16)*16;
6482     }
6483     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6484   }
6485 
6486   // Allow for Altivec parameters at the end, if needed.
6487   if (nAltivecParamsAtEnd) {
6488     NumBytes = ((NumBytes+15)/16)*16;
6489     NumBytes += 16*nAltivecParamsAtEnd;
6490   }
6491 
6492   // The prolog code of the callee may store up to 8 GPR argument registers to
6493   // the stack, allowing va_start to index over them in memory if its varargs.
6494   // Because we cannot tell if this is needed on the caller side, we have to
6495   // conservatively assume that it is needed.  As such, make sure we have at
6496   // least enough stack space for the caller to store the 8 GPRs.
6497   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6498 
6499   // Tail call needs the stack to be aligned.
6500   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6501       CFlags.CallConv == CallingConv::Fast)
6502     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6503 
6504   // Calculate by how many bytes the stack has to be adjusted in case of tail
6505   // call optimization.
6506   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6507 
6508   // To protect arguments on the stack from being clobbered in a tail call,
6509   // force all the loads to happen before doing any other lowering.
6510   if (CFlags.IsTailCall)
6511     Chain = DAG.getStackArgumentTokenFactor(Chain);
6512 
6513   // Adjust the stack pointer for the new arguments...
6514   // These operations are automatically eliminated by the prolog/epilog pass
6515   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6516   SDValue CallSeqStart = Chain;
6517 
6518   // Load the return address and frame pointer so it can be move somewhere else
6519   // later.
6520   SDValue LROp, FPOp;
6521   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6522 
6523   // Set up a copy of the stack pointer for use loading and storing any
6524   // arguments that may not fit in the registers available for argument
6525   // passing.
6526   SDValue StackPtr;
6527   if (isPPC64)
6528     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6529   else
6530     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6531 
6532   // Figure out which arguments are going to go in registers, and which in
6533   // memory.  Also, if this is a vararg function, floating point operations
6534   // must be stored to our stack, and loaded into integer regs as well, if
6535   // any integer regs are available for argument passing.
6536   unsigned ArgOffset = LinkageSize;
6537   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6538 
6539   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6540     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6541     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6542   };
6543   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6544     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6545     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6546   };
6547   static const MCPhysReg VR[] = {
6548     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6549     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6550   };
6551   const unsigned NumGPRs = array_lengthof(GPR_32);
6552   const unsigned NumFPRs = 13;
6553   const unsigned NumVRs  = array_lengthof(VR);
6554 
6555   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6556 
6557   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6558   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6559 
6560   SmallVector<SDValue, 8> MemOpChains;
6561   for (unsigned i = 0; i != NumOps; ++i) {
6562     SDValue Arg = OutVals[i];
6563     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6564 
6565     // PtrOff will be used to store the current argument to the stack if a
6566     // register cannot be found for it.
6567     SDValue PtrOff;
6568 
6569     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6570 
6571     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6572 
6573     // On PPC64, promote integers to 64-bit values.
6574     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6575       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6576       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6577       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6578     }
6579 
6580     // FIXME memcpy is used way more than necessary.  Correctness first.
6581     // Note: "by value" is code for passing a structure by value, not
6582     // basic types.
6583     if (Flags.isByVal()) {
6584       unsigned Size = Flags.getByValSize();
6585       // Very small objects are passed right-justified.  Everything else is
6586       // passed left-justified.
6587       if (Size==1 || Size==2) {
6588         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6589         if (GPR_idx != NumGPRs) {
6590           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6591                                         MachinePointerInfo(), VT);
6592           MemOpChains.push_back(Load.getValue(1));
6593           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6594 
6595           ArgOffset += PtrByteSize;
6596         } else {
6597           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6598                                           PtrOff.getValueType());
6599           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6600           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6601                                                             CallSeqStart,
6602                                                             Flags, DAG, dl);
6603           ArgOffset += PtrByteSize;
6604         }
6605         continue;
6606       }
6607       // Copy entire object into memory.  There are cases where gcc-generated
6608       // code assumes it is there, even if it could be put entirely into
6609       // registers.  (This is not what the doc says.)
6610       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6611                                                         CallSeqStart,
6612                                                         Flags, DAG, dl);
6613 
6614       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6615       // copy the pieces of the object that fit into registers from the
6616       // parameter save area.
6617       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6618         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6619         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6620         if (GPR_idx != NumGPRs) {
6621           SDValue Load =
6622               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6623           MemOpChains.push_back(Load.getValue(1));
6624           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6625           ArgOffset += PtrByteSize;
6626         } else {
6627           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6628           break;
6629         }
6630       }
6631       continue;
6632     }
6633 
6634     switch (Arg.getSimpleValueType().SimpleTy) {
6635     default: llvm_unreachable("Unexpected ValueType for argument!");
6636     case MVT::i1:
6637     case MVT::i32:
6638     case MVT::i64:
6639       if (GPR_idx != NumGPRs) {
6640         if (Arg.getValueType() == MVT::i1)
6641           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6642 
6643         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6644       } else {
6645         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6646                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6647                          TailCallArguments, dl);
6648       }
6649       ArgOffset += PtrByteSize;
6650       break;
6651     case MVT::f32:
6652     case MVT::f64:
6653       if (FPR_idx != NumFPRs) {
6654         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6655 
6656         if (CFlags.IsVarArg) {
6657           SDValue Store =
6658               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6659           MemOpChains.push_back(Store);
6660 
6661           // Float varargs are always shadowed in available integer registers
6662           if (GPR_idx != NumGPRs) {
6663             SDValue Load =
6664                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6665             MemOpChains.push_back(Load.getValue(1));
6666             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6667           }
6668           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6669             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6670             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6671             SDValue Load =
6672                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6673             MemOpChains.push_back(Load.getValue(1));
6674             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6675           }
6676         } else {
6677           // If we have any FPRs remaining, we may also have GPRs remaining.
6678           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6679           // GPRs.
6680           if (GPR_idx != NumGPRs)
6681             ++GPR_idx;
6682           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6683               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6684             ++GPR_idx;
6685         }
6686       } else
6687         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6688                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6689                          TailCallArguments, dl);
6690       if (isPPC64)
6691         ArgOffset += 8;
6692       else
6693         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6694       break;
6695     case MVT::v4f32:
6696     case MVT::v4i32:
6697     case MVT::v8i16:
6698     case MVT::v16i8:
6699       if (CFlags.IsVarArg) {
6700         // These go aligned on the stack, or in the corresponding R registers
6701         // when within range.  The Darwin PPC ABI doc claims they also go in
6702         // V registers; in fact gcc does this only for arguments that are
6703         // prototyped, not for those that match the ...  We do it for all
6704         // arguments, seems to work.
6705         while (ArgOffset % 16 !=0) {
6706           ArgOffset += PtrByteSize;
6707           if (GPR_idx != NumGPRs)
6708             GPR_idx++;
6709         }
6710         // We could elide this store in the case where the object fits
6711         // entirely in R registers.  Maybe later.
6712         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6713                              DAG.getConstant(ArgOffset, dl, PtrVT));
6714         SDValue Store =
6715             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6716         MemOpChains.push_back(Store);
6717         if (VR_idx != NumVRs) {
6718           SDValue Load =
6719               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6720           MemOpChains.push_back(Load.getValue(1));
6721           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6722         }
6723         ArgOffset += 16;
6724         for (unsigned i=0; i<16; i+=PtrByteSize) {
6725           if (GPR_idx == NumGPRs)
6726             break;
6727           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6728                                    DAG.getConstant(i, dl, PtrVT));
6729           SDValue Load =
6730               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6731           MemOpChains.push_back(Load.getValue(1));
6732           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6733         }
6734         break;
6735       }
6736 
6737       // Non-varargs Altivec params generally go in registers, but have
6738       // stack space allocated at the end.
6739       if (VR_idx != NumVRs) {
6740         // Doesn't have GPR space allocated.
6741         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6742       } else if (nAltivecParamsAtEnd==0) {
6743         // We are emitting Altivec params in order.
6744         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6745                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6746                          TailCallArguments, dl);
6747         ArgOffset += 16;
6748       }
6749       break;
6750     }
6751   }
6752   // If all Altivec parameters fit in registers, as they usually do,
6753   // they get stack space following the non-Altivec parameters.  We
6754   // don't track this here because nobody below needs it.
6755   // If there are more Altivec parameters than fit in registers emit
6756   // the stores here.
6757   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6758     unsigned j = 0;
6759     // Offset is aligned; skip 1st 12 params which go in V registers.
6760     ArgOffset = ((ArgOffset+15)/16)*16;
6761     ArgOffset += 12*16;
6762     for (unsigned i = 0; i != NumOps; ++i) {
6763       SDValue Arg = OutVals[i];
6764       EVT ArgType = Outs[i].VT;
6765       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6766           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6767         if (++j > NumVRs) {
6768           SDValue PtrOff;
6769           // We are emitting Altivec params in order.
6770           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6771                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6772                            TailCallArguments, dl);
6773           ArgOffset += 16;
6774         }
6775       }
6776     }
6777   }
6778 
6779   if (!MemOpChains.empty())
6780     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6781 
6782   // On Darwin, R12 must contain the address of an indirect callee.  This does
6783   // not mean the MTCTR instruction must use R12; it's easier to model this as
6784   // an extra parameter, so do that.
6785   if (CFlags.IsIndirect) {
6786     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6787     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6788                                                    PPC::R12), Callee));
6789   }
6790 
6791   // Build a sequence of copy-to-reg nodes chained together with token chain
6792   // and flag operands which copy the outgoing args into the appropriate regs.
6793   SDValue InFlag;
6794   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6795     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6796                              RegsToPass[i].second, InFlag);
6797     InFlag = Chain.getValue(1);
6798   }
6799 
6800   if (CFlags.IsTailCall)
6801     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6802                     TailCallArguments);
6803 
6804   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6805                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
6806 }
6807 
6808 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6809                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6810                    CCState &State) {
6811 
6812   if (ValVT == MVT::f128)
6813     report_fatal_error("f128 is unimplemented on AIX.");
6814 
6815   if (ArgFlags.isByVal())
6816     report_fatal_error("Passing structure by value is unimplemented.");
6817 
6818   if (ArgFlags.isNest())
6819     report_fatal_error("Nest arguments are unimplemented.");
6820 
6821   if (ValVT.isVector() || LocVT.isVector())
6822     report_fatal_error("Vector arguments are unimplemented on AIX.");
6823 
6824   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6825       State.getMachineFunction().getSubtarget());
6826   const bool IsPPC64 = Subtarget.isPPC64();
6827   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6828 
6829   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6830                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6831                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6832   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6833                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6834                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6835 
6836   // Arguments always reserve parameter save area.
6837   switch (ValVT.SimpleTy) {
6838   default:
6839     report_fatal_error("Unhandled value type for argument.");
6840   case MVT::i64:
6841     // i64 arguments should have been split to i32 for PPC32.
6842     assert(IsPPC64 && "PPC32 should have split i64 values.");
6843     LLVM_FALLTHROUGH;
6844   case MVT::i1:
6845   case MVT::i32: {
6846     const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize);
6847     const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6848     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6849       // Promote integers if needed.
6850       if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6851         LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6852                                     : CCValAssign::LocInfo::ZExt;
6853       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6854     }
6855     else
6856       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6857 
6858     return false;
6859   }
6860   case MVT::f32:
6861   case MVT::f64: {
6862     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6863     const unsigned StoreSize = LocVT.getStoreSize();
6864     // Floats are always 4-byte aligned in the PSA on AIX.
6865     // This includes f64 in 64-bit mode for ABI compatibility.
6866     const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6867     unsigned FReg = State.AllocateReg(FPR);
6868     if (FReg)
6869       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6870 
6871     // Reserve and initialize GPRs or initialize the PSA as required.
6872     const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6873     for (unsigned I = 0; I < StoreSize; I += PtrByteSize) {
6874       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6875         assert(FReg && "An FPR should be available when a GPR is reserved.");
6876         if (State.isVarArg()) {
6877           // Successfully reserved GPRs are only initialized for vararg calls.
6878           // Custom handling is required for:
6879           //   f64 in PPC32 needs to be split into 2 GPRs.
6880           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6881           State.addLoc(
6882               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6883         }
6884       } else {
6885         // If there are insufficient GPRs, the PSA needs to be initialized.
6886         // Initialization occurs even if an FPR was initialized for
6887         // compatibility with the AIX XL compiler. The full memory for the
6888         // argument will be initialized even if a prior word is saved in GPR.
6889         // A custom memLoc is used when the argument also passes in FPR so
6890         // that the callee handling can skip over it easily.
6891         State.addLoc(
6892             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6893                                              LocInfo)
6894                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6895         break;
6896       }
6897     }
6898 
6899     return false;
6900   }
6901   }
6902   return true;
6903 }
6904 
6905 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6906                                                     bool IsPPC64) {
6907   assert((IsPPC64 || SVT != MVT::i64) &&
6908          "i64 should have been split for 32-bit codegen.");
6909 
6910   switch (SVT) {
6911   default:
6912     report_fatal_error("Unexpected value type for formal argument");
6913   case MVT::i1:
6914   case MVT::i32:
6915   case MVT::i64:
6916     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6917   case MVT::f32:
6918     return &PPC::F4RCRegClass;
6919   case MVT::f64:
6920     return &PPC::F8RCRegClass;
6921   }
6922 }
6923 
6924 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6925                                         SelectionDAG &DAG, SDValue ArgValue,
6926                                         MVT LocVT, const SDLoc &dl) {
6927   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6928   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6929 
6930   if (Flags.isSExt())
6931     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6932                            DAG.getValueType(ValVT));
6933   else if (Flags.isZExt())
6934     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6935                            DAG.getValueType(ValVT));
6936 
6937   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6938 }
6939 
6940 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6941     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6942     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6943     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6944 
6945   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6946           CallConv == CallingConv::Fast) &&
6947          "Unexpected calling convention!");
6948 
6949   if (isVarArg)
6950     report_fatal_error("This call type is unimplemented on AIX.");
6951 
6952   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6953     report_fatal_error("Tail call support is unimplemented on AIX.");
6954 
6955   if (useSoftFloat())
6956     report_fatal_error("Soft float support is unimplemented on AIX.");
6957 
6958   const PPCSubtarget &Subtarget =
6959       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6960   if (Subtarget.hasQPX())
6961     report_fatal_error("QPX support is not supported on AIX.");
6962 
6963   const bool IsPPC64 = Subtarget.isPPC64();
6964   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6965 
6966   // Assign locations to all of the incoming arguments.
6967   SmallVector<CCValAssign, 16> ArgLocs;
6968   MachineFunction &MF = DAG.getMachineFunction();
6969   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6970 
6971   // Reserve space for the linkage area on the stack.
6972   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6973   // On AIX a minimum of 8 words is saved to the parameter save area.
6974   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
6975   CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize);
6976   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6977 
6978   for (CCValAssign &VA : ArgLocs) {
6979 
6980     if (VA.isMemLoc()) {
6981       // For compatibility with the AIX XL compiler, the float args in the
6982       // parameter save area are initialized even if the argument is available
6983       // in register.  The caller is required to initialize both the register
6984       // and memory, however, the callee can choose to expect it in either.  The
6985       // memloc is dismissed here because the argument is retrieved from the
6986       // register.
6987       if (VA.needsCustom())
6988         continue;
6989       report_fatal_error(
6990           "Handling of formal arguments on the stack is unimplemented!");
6991     }
6992 
6993     assert(VA.isRegLoc() && "Unexpected argument location.");
6994 
6995     EVT ValVT = VA.getValVT();
6996     MVT LocVT = VA.getLocVT();
6997     MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
6998     unsigned VReg =
6999         MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7000     SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7001     if (ValVT.isScalarInteger() &&
7002         (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7003       ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7004       ArgValue =
7005           truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7006     }
7007     InVals.push_back(ArgValue);
7008   }
7009 
7010   // Area that is at least reserved in the caller of this function.
7011   unsigned MinReservedArea = CCInfo.getNextStackOffset();
7012 
7013   // Set the size that is at least reserved in caller of this function. Tail
7014   // call optimized function's reserved stack space needs to be aligned so
7015   // that taking the difference between two stack areas will result in an
7016   // aligned stack.
7017   MinReservedArea =
7018       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
7019   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7020   FuncInfo->setMinReservedArea(MinReservedArea);
7021 
7022   return Chain;
7023 }
7024 
7025 SDValue PPCTargetLowering::LowerCall_AIX(
7026     SDValue Chain, SDValue Callee, CallFlags CFlags,
7027     const SmallVectorImpl<ISD::OutputArg> &Outs,
7028     const SmallVectorImpl<SDValue> &OutVals,
7029     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7030     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7031     ImmutableCallSite CS) const {
7032 
7033   assert((CFlags.CallConv == CallingConv::C ||
7034           CFlags.CallConv == CallingConv::Cold ||
7035           CFlags.CallConv == CallingConv::Fast) &&
7036          "Unexpected calling convention!");
7037 
7038   if (CFlags.IsPatchPoint)
7039     report_fatal_error("This call type is unimplemented on AIX.");
7040 
7041   const PPCSubtarget& Subtarget =
7042       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7043   if (Subtarget.hasQPX())
7044     report_fatal_error("QPX is not supported on AIX.");
7045   if (Subtarget.hasAltivec())
7046     report_fatal_error("Altivec support is unimplemented on AIX.");
7047 
7048   MachineFunction &MF = DAG.getMachineFunction();
7049   SmallVector<CCValAssign, 16> ArgLocs;
7050   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7051                  *DAG.getContext());
7052 
7053   // Reserve space for the linkage save area (LSA) on the stack.
7054   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7055   //   [SP][CR][LR][2 x reserved][TOC].
7056   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7057   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7058   const bool IsPPC64 = Subtarget.isPPC64();
7059   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7060   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7061   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7062   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7063 
7064   // The prolog code of the callee may store up to 8 GPR argument registers to
7065   // the stack, allowing va_start to index over them in memory if the callee
7066   // is variadic.
7067   // Because we cannot tell if this is needed on the caller side, we have to
7068   // conservatively assume that it is needed.  As such, make sure we have at
7069   // least enough stack space for the caller to store the 8 GPRs.
7070   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7071   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7072                                      CCInfo.getNextStackOffset());
7073 
7074   // Adjust the stack pointer for the new arguments...
7075   // These operations are automatically eliminated by the prolog/epilog pass.
7076   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7077   SDValue CallSeqStart = Chain;
7078 
7079   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7080   SmallVector<SDValue, 8> MemOpChains;
7081 
7082   // Set up a copy of the stack pointer for loading and storing any
7083   // arguments that may not fit in the registers available for argument
7084   // passing.
7085   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7086                                    : DAG.getRegister(PPC::R1, MVT::i32);
7087 
7088   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7089     CCValAssign &VA = ArgLocs[I++];
7090 
7091     SDValue Arg = OutVals[VA.getValNo()];
7092 
7093     if (!VA.isRegLoc() && !VA.isMemLoc())
7094       report_fatal_error("Unexpected location for function call argument.");
7095 
7096     if (VA.isRegLoc() && !VA.needsCustom()) {
7097       switch (VA.getLocInfo()) {
7098       default:
7099         report_fatal_error("Unexpected argument extension type.");
7100       case CCValAssign::Full:
7101         break;
7102       case CCValAssign::ZExt:
7103         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7104         break;
7105       case CCValAssign::SExt:
7106         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7107         break;
7108       }
7109       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7110 
7111       continue;
7112     }
7113 
7114     if (VA.isMemLoc()) {
7115       SDValue PtrOff =
7116           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7117       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7118       MemOpChains.push_back(
7119           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7120 
7121       continue;
7122     }
7123 
7124     // Custom handling is used for GPR initializations for vararg float
7125     // arguments.
7126     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7127            VA.getValVT().isFloatingPoint() && VA.getLocVT().isInteger() &&
7128            "Unexpected register handling for calling convention.");
7129 
7130     SDValue ArgAsInt =
7131         DAG.getBitcast(MVT::getIntegerVT(VA.getValVT().getSizeInBits()), Arg);
7132 
7133     if (Arg.getValueType().getStoreSize() == VA.getLocVT().getStoreSize())
7134       // f32 in 32-bit GPR
7135       // f64 in 64-bit GPR
7136       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7137     else if (Arg.getValueType().getSizeInBits() < VA.getLocVT().getSizeInBits())
7138       // f32 in 64-bit GPR.
7139       RegsToPass.push_back(std::make_pair(
7140           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, VA.getLocVT())));
7141     else {
7142       // f64 in two 32-bit GPRs
7143       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7144       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7145              "Unexpected custom register for argument!");
7146       CCValAssign &GPR1 = VA;
7147       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7148                                      DAG.getConstant(32, dl, MVT::i8));
7149       RegsToPass.push_back(std::make_pair(
7150           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7151 
7152       if (I != E) {
7153         // If only 1 GPR was available, there will only be one custom GPR and
7154         // the argument will also pass in memory.
7155         CCValAssign &PeekArg = ArgLocs[I];
7156         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7157           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7158           CCValAssign &GPR2 = ArgLocs[I++];
7159           RegsToPass.push_back(std::make_pair(
7160               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7161         }
7162       }
7163     }
7164   }
7165 
7166   if (!MemOpChains.empty())
7167     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7168 
7169   // For indirect calls, we need to save the TOC base to the stack for
7170   // restoration after the call.
7171   if (CFlags.IsIndirect) {
7172     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7173     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7174     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7175     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7176     const unsigned TOCSaveOffset =
7177         Subtarget.getFrameLowering()->getTOCSaveOffset();
7178 
7179     setUsesTOCBasePtr(DAG);
7180     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7181     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7182     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7183     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7184     Chain = DAG.getStore(
7185         Val.getValue(1), dl, Val, AddPtr,
7186         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7187   }
7188 
7189   // Build a sequence of copy-to-reg nodes chained together with token chain
7190   // and flag operands which copy the outgoing args into the appropriate regs.
7191   SDValue InFlag;
7192   for (auto Reg : RegsToPass) {
7193     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7194     InFlag = Chain.getValue(1);
7195   }
7196 
7197   const int SPDiff = 0;
7198   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7199                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
7200 }
7201 
7202 bool
7203 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7204                                   MachineFunction &MF, bool isVarArg,
7205                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7206                                   LLVMContext &Context) const {
7207   SmallVector<CCValAssign, 16> RVLocs;
7208   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7209   return CCInfo.CheckReturn(
7210       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7211                 ? RetCC_PPC_Cold
7212                 : RetCC_PPC);
7213 }
7214 
7215 SDValue
7216 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7217                                bool isVarArg,
7218                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7219                                const SmallVectorImpl<SDValue> &OutVals,
7220                                const SDLoc &dl, SelectionDAG &DAG) const {
7221   SmallVector<CCValAssign, 16> RVLocs;
7222   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7223                  *DAG.getContext());
7224   CCInfo.AnalyzeReturn(Outs,
7225                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7226                            ? RetCC_PPC_Cold
7227                            : RetCC_PPC);
7228 
7229   SDValue Flag;
7230   SmallVector<SDValue, 4> RetOps(1, Chain);
7231 
7232   // Copy the result values into the output registers.
7233   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7234     CCValAssign &VA = RVLocs[i];
7235     assert(VA.isRegLoc() && "Can only return in registers!");
7236 
7237     SDValue Arg = OutVals[RealResIdx];
7238 
7239     switch (VA.getLocInfo()) {
7240     default: llvm_unreachable("Unknown loc info!");
7241     case CCValAssign::Full: break;
7242     case CCValAssign::AExt:
7243       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7244       break;
7245     case CCValAssign::ZExt:
7246       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7247       break;
7248     case CCValAssign::SExt:
7249       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7250       break;
7251     }
7252     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7253       bool isLittleEndian = Subtarget.isLittleEndian();
7254       // Legalize ret f64 -> ret 2 x i32.
7255       SDValue SVal =
7256           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7257                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7258       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7259       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7260       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7261                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7262       Flag = Chain.getValue(1);
7263       VA = RVLocs[++i]; // skip ahead to next loc
7264       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7265     } else
7266       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7267     Flag = Chain.getValue(1);
7268     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7269   }
7270 
7271   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7272   const MCPhysReg *I =
7273     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7274   if (I) {
7275     for (; *I; ++I) {
7276 
7277       if (PPC::G8RCRegClass.contains(*I))
7278         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7279       else if (PPC::F8RCRegClass.contains(*I))
7280         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7281       else if (PPC::CRRCRegClass.contains(*I))
7282         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7283       else if (PPC::VRRCRegClass.contains(*I))
7284         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7285       else
7286         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7287     }
7288   }
7289 
7290   RetOps[0] = Chain;  // Update chain.
7291 
7292   // Add the flag if we have it.
7293   if (Flag.getNode())
7294     RetOps.push_back(Flag);
7295 
7296   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7297 }
7298 
7299 SDValue
7300 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7301                                                 SelectionDAG &DAG) const {
7302   SDLoc dl(Op);
7303 
7304   // Get the correct type for integers.
7305   EVT IntVT = Op.getValueType();
7306 
7307   // Get the inputs.
7308   SDValue Chain = Op.getOperand(0);
7309   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7310   // Build a DYNAREAOFFSET node.
7311   SDValue Ops[2] = {Chain, FPSIdx};
7312   SDVTList VTs = DAG.getVTList(IntVT);
7313   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7314 }
7315 
7316 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7317                                              SelectionDAG &DAG) const {
7318   // When we pop the dynamic allocation we need to restore the SP link.
7319   SDLoc dl(Op);
7320 
7321   // Get the correct type for pointers.
7322   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7323 
7324   // Construct the stack pointer operand.
7325   bool isPPC64 = Subtarget.isPPC64();
7326   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7327   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7328 
7329   // Get the operands for the STACKRESTORE.
7330   SDValue Chain = Op.getOperand(0);
7331   SDValue SaveSP = Op.getOperand(1);
7332 
7333   // Load the old link SP.
7334   SDValue LoadLinkSP =
7335       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7336 
7337   // Restore the stack pointer.
7338   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7339 
7340   // Store the old link SP.
7341   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7342 }
7343 
7344 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7345   MachineFunction &MF = DAG.getMachineFunction();
7346   bool isPPC64 = Subtarget.isPPC64();
7347   EVT PtrVT = getPointerTy(MF.getDataLayout());
7348 
7349   // Get current frame pointer save index.  The users of this index will be
7350   // primarily DYNALLOC instructions.
7351   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7352   int RASI = FI->getReturnAddrSaveIndex();
7353 
7354   // If the frame pointer save index hasn't been defined yet.
7355   if (!RASI) {
7356     // Find out what the fix offset of the frame pointer save area.
7357     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7358     // Allocate the frame index for frame pointer save area.
7359     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7360     // Save the result.
7361     FI->setReturnAddrSaveIndex(RASI);
7362   }
7363   return DAG.getFrameIndex(RASI, PtrVT);
7364 }
7365 
7366 SDValue
7367 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7368   MachineFunction &MF = DAG.getMachineFunction();
7369   bool isPPC64 = Subtarget.isPPC64();
7370   EVT PtrVT = getPointerTy(MF.getDataLayout());
7371 
7372   // Get current frame pointer save index.  The users of this index will be
7373   // primarily DYNALLOC instructions.
7374   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7375   int FPSI = FI->getFramePointerSaveIndex();
7376 
7377   // If the frame pointer save index hasn't been defined yet.
7378   if (!FPSI) {
7379     // Find out what the fix offset of the frame pointer save area.
7380     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7381     // Allocate the frame index for frame pointer save area.
7382     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7383     // Save the result.
7384     FI->setFramePointerSaveIndex(FPSI);
7385   }
7386   return DAG.getFrameIndex(FPSI, PtrVT);
7387 }
7388 
7389 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7390                                                    SelectionDAG &DAG) const {
7391   // Get the inputs.
7392   SDValue Chain = Op.getOperand(0);
7393   SDValue Size  = Op.getOperand(1);
7394   SDLoc dl(Op);
7395 
7396   // Get the correct type for pointers.
7397   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7398   // Negate the size.
7399   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7400                                 DAG.getConstant(0, dl, PtrVT), Size);
7401   // Construct a node for the frame pointer save index.
7402   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7403   // Build a DYNALLOC node.
7404   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7405   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7406   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7407 }
7408 
7409 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7410                                                      SelectionDAG &DAG) const {
7411   MachineFunction &MF = DAG.getMachineFunction();
7412 
7413   bool isPPC64 = Subtarget.isPPC64();
7414   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7415 
7416   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7417   return DAG.getFrameIndex(FI, PtrVT);
7418 }
7419 
7420 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7421                                                SelectionDAG &DAG) const {
7422   SDLoc DL(Op);
7423   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7424                      DAG.getVTList(MVT::i32, MVT::Other),
7425                      Op.getOperand(0), Op.getOperand(1));
7426 }
7427 
7428 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7429                                                 SelectionDAG &DAG) const {
7430   SDLoc DL(Op);
7431   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7432                      Op.getOperand(0), Op.getOperand(1));
7433 }
7434 
7435 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7436   if (Op.getValueType().isVector())
7437     return LowerVectorLoad(Op, DAG);
7438 
7439   assert(Op.getValueType() == MVT::i1 &&
7440          "Custom lowering only for i1 loads");
7441 
7442   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7443 
7444   SDLoc dl(Op);
7445   LoadSDNode *LD = cast<LoadSDNode>(Op);
7446 
7447   SDValue Chain = LD->getChain();
7448   SDValue BasePtr = LD->getBasePtr();
7449   MachineMemOperand *MMO = LD->getMemOperand();
7450 
7451   SDValue NewLD =
7452       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7453                      BasePtr, MVT::i8, MMO);
7454   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7455 
7456   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7457   return DAG.getMergeValues(Ops, dl);
7458 }
7459 
7460 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7461   if (Op.getOperand(1).getValueType().isVector())
7462     return LowerVectorStore(Op, DAG);
7463 
7464   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7465          "Custom lowering only for i1 stores");
7466 
7467   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7468 
7469   SDLoc dl(Op);
7470   StoreSDNode *ST = cast<StoreSDNode>(Op);
7471 
7472   SDValue Chain = ST->getChain();
7473   SDValue BasePtr = ST->getBasePtr();
7474   SDValue Value = ST->getValue();
7475   MachineMemOperand *MMO = ST->getMemOperand();
7476 
7477   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7478                       Value);
7479   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7480 }
7481 
7482 // FIXME: Remove this once the ANDI glue bug is fixed:
7483 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7484   assert(Op.getValueType() == MVT::i1 &&
7485          "Custom lowering only for i1 results");
7486 
7487   SDLoc DL(Op);
7488   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7489 }
7490 
7491 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7492                                                SelectionDAG &DAG) const {
7493 
7494   // Implements a vector truncate that fits in a vector register as a shuffle.
7495   // We want to legalize vector truncates down to where the source fits in
7496   // a vector register (and target is therefore smaller than vector register
7497   // size).  At that point legalization will try to custom lower the sub-legal
7498   // result and get here - where we can contain the truncate as a single target
7499   // operation.
7500 
7501   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7502   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7503   //
7504   // We will implement it for big-endian ordering as this (where x denotes
7505   // undefined):
7506   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7507   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7508   //
7509   // The same operation in little-endian ordering will be:
7510   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7511   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7512 
7513   assert(Op.getValueType().isVector() && "Vector type expected.");
7514 
7515   SDLoc DL(Op);
7516   SDValue N1 = Op.getOperand(0);
7517   unsigned SrcSize = N1.getValueType().getSizeInBits();
7518   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7519   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7520 
7521   EVT TrgVT = Op.getValueType();
7522   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7523   EVT EltVT = TrgVT.getVectorElementType();
7524   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7525   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7526 
7527   // First list the elements we want to keep.
7528   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7529   SmallVector<int, 16> ShuffV;
7530   if (Subtarget.isLittleEndian())
7531     for (unsigned i = 0; i < TrgNumElts; ++i)
7532       ShuffV.push_back(i * SizeMult);
7533   else
7534     for (unsigned i = 1; i <= TrgNumElts; ++i)
7535       ShuffV.push_back(i * SizeMult - 1);
7536 
7537   // Populate the remaining elements with undefs.
7538   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7539     // ShuffV.push_back(i + WideNumElts);
7540     ShuffV.push_back(WideNumElts + 1);
7541 
7542   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7543   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7544 }
7545 
7546 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7547 /// possible.
7548 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7549   // Not FP? Not a fsel.
7550   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7551       !Op.getOperand(2).getValueType().isFloatingPoint())
7552     return Op;
7553 
7554   bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath;
7555   bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath;
7556   // We might be able to do better than this under some circumstances, but in
7557   // general, fsel-based lowering of select is a finite-math-only optimization.
7558   // For more information, see section F.3 of the 2.06 ISA specification.
7559   // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the
7560   // presence of infinities.
7561   if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs))
7562     return Op;
7563   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7564 
7565   EVT ResVT = Op.getValueType();
7566   EVT CmpVT = Op.getOperand(0).getValueType();
7567   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7568   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7569   SDLoc dl(Op);
7570 
7571   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7572     switch (CC) {
7573     default:
7574       // Not a min/max but with finite math, we may still be able to use fsel.
7575       if (HasNoInfs && HasNoNaNs)
7576         break;
7577       return Op;
7578     case ISD::SETOGT:
7579     case ISD::SETGT:
7580       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7581     case ISD::SETOLT:
7582     case ISD::SETLT:
7583       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7584     }
7585   }
7586 
7587   // TODO: Propagate flags from the select rather than global settings.
7588   SDNodeFlags Flags;
7589   Flags.setNoInfs(true);
7590   Flags.setNoNaNs(true);
7591 
7592   // If the RHS of the comparison is a 0.0, we don't need to do the
7593   // subtraction at all.
7594   SDValue Sel1;
7595   if (isFloatingPointZero(RHS))
7596     switch (CC) {
7597     default: break;       // SETUO etc aren't handled by fsel.
7598     case ISD::SETNE:
7599       std::swap(TV, FV);
7600       LLVM_FALLTHROUGH;
7601     case ISD::SETEQ:
7602       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7603         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7604       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7605       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7606         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7607       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7608                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7609     case ISD::SETULT:
7610     case ISD::SETLT:
7611       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7612       LLVM_FALLTHROUGH;
7613     case ISD::SETOGE:
7614     case ISD::SETGE:
7615       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7616         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7617       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7618     case ISD::SETUGT:
7619     case ISD::SETGT:
7620       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7621       LLVM_FALLTHROUGH;
7622     case ISD::SETOLE:
7623     case ISD::SETLE:
7624       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7625         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7626       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7627                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7628     }
7629 
7630   SDValue Cmp;
7631   switch (CC) {
7632   default: break;       // SETUO etc aren't handled by fsel.
7633   case ISD::SETNE:
7634     std::swap(TV, FV);
7635     LLVM_FALLTHROUGH;
7636   case ISD::SETEQ:
7637     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7638     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7639       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7640     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7641     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7642       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7643     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7644                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7645   case ISD::SETULT:
7646   case ISD::SETLT:
7647     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7648     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7649       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7650     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7651   case ISD::SETOGE:
7652   case ISD::SETGE:
7653     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7654     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7655       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7656     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7657   case ISD::SETUGT:
7658   case ISD::SETGT:
7659     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7660     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7661       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7662     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7663   case ISD::SETOLE:
7664   case ISD::SETLE:
7665     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7666     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7667       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7668     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7669   }
7670   return Op;
7671 }
7672 
7673 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7674                                                SelectionDAG &DAG,
7675                                                const SDLoc &dl) const {
7676   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7677   SDValue Src = Op.getOperand(0);
7678   if (Src.getValueType() == MVT::f32)
7679     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7680 
7681   SDValue Tmp;
7682   switch (Op.getSimpleValueType().SimpleTy) {
7683   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7684   case MVT::i32:
7685     Tmp = DAG.getNode(
7686         Op.getOpcode() == ISD::FP_TO_SINT
7687             ? PPCISD::FCTIWZ
7688             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7689         dl, MVT::f64, Src);
7690     break;
7691   case MVT::i64:
7692     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7693            "i64 FP_TO_UINT is supported only with FPCVT");
7694     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7695                                                         PPCISD::FCTIDUZ,
7696                       dl, MVT::f64, Src);
7697     break;
7698   }
7699 
7700   // Convert the FP value to an int value through memory.
7701   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7702     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7703   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7704   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7705   MachinePointerInfo MPI =
7706       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7707 
7708   // Emit a store to the stack slot.
7709   SDValue Chain;
7710   if (i32Stack) {
7711     MachineFunction &MF = DAG.getMachineFunction();
7712     MachineMemOperand *MMO =
7713       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7714     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7715     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7716               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7717   } else
7718     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7719 
7720   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7721   // add in a bias on big endian.
7722   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7723     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7724                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7725     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7726   }
7727 
7728   RLI.Chain = Chain;
7729   RLI.Ptr = FIPtr;
7730   RLI.MPI = MPI;
7731 }
7732 
7733 /// Custom lowers floating point to integer conversions to use
7734 /// the direct move instructions available in ISA 2.07 to avoid the
7735 /// need for load/store combinations.
7736 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7737                                                     SelectionDAG &DAG,
7738                                                     const SDLoc &dl) const {
7739   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7740   SDValue Src = Op.getOperand(0);
7741 
7742   if (Src.getValueType() == MVT::f32)
7743     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7744 
7745   SDValue Tmp;
7746   switch (Op.getSimpleValueType().SimpleTy) {
7747   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7748   case MVT::i32:
7749     Tmp = DAG.getNode(
7750         Op.getOpcode() == ISD::FP_TO_SINT
7751             ? PPCISD::FCTIWZ
7752             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7753         dl, MVT::f64, Src);
7754     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7755     break;
7756   case MVT::i64:
7757     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7758            "i64 FP_TO_UINT is supported only with FPCVT");
7759     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7760                                                         PPCISD::FCTIDUZ,
7761                       dl, MVT::f64, Src);
7762     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7763     break;
7764   }
7765   return Tmp;
7766 }
7767 
7768 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7769                                           const SDLoc &dl) const {
7770 
7771   // FP to INT conversions are legal for f128.
7772   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7773     return Op;
7774 
7775   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7776   // PPC (the libcall is not available).
7777   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7778     if (Op.getValueType() == MVT::i32) {
7779       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7780         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7781                                  MVT::f64, Op.getOperand(0),
7782                                  DAG.getIntPtrConstant(0, dl));
7783         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7784                                  MVT::f64, Op.getOperand(0),
7785                                  DAG.getIntPtrConstant(1, dl));
7786 
7787         // Add the two halves of the long double in round-to-zero mode.
7788         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7789 
7790         // Now use a smaller FP_TO_SINT.
7791         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7792       }
7793       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7794         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7795         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7796         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7797         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7798         // FIXME: generated code sucks.
7799         // TODO: Are there fast-math-flags to propagate to this FSUB?
7800         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7801                                    Op.getOperand(0), Tmp);
7802         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7803         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7804                            DAG.getConstant(0x80000000, dl, MVT::i32));
7805         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7806                                     Op.getOperand(0));
7807         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7808                                ISD::SETGE);
7809       }
7810     }
7811 
7812     return SDValue();
7813   }
7814 
7815   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7816     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7817 
7818   ReuseLoadInfo RLI;
7819   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7820 
7821   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7822                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7823 }
7824 
7825 // We're trying to insert a regular store, S, and then a load, L. If the
7826 // incoming value, O, is a load, we might just be able to have our load use the
7827 // address used by O. However, we don't know if anything else will store to
7828 // that address before we can load from it. To prevent this situation, we need
7829 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7830 // the same chain operand as O, we create a token factor from the chain results
7831 // of O and L, and we replace all uses of O's chain result with that token
7832 // factor (see spliceIntoChain below for this last part).
7833 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7834                                             ReuseLoadInfo &RLI,
7835                                             SelectionDAG &DAG,
7836                                             ISD::LoadExtType ET) const {
7837   SDLoc dl(Op);
7838   if (ET == ISD::NON_EXTLOAD &&
7839       (Op.getOpcode() == ISD::FP_TO_UINT ||
7840        Op.getOpcode() == ISD::FP_TO_SINT) &&
7841       isOperationLegalOrCustom(Op.getOpcode(),
7842                                Op.getOperand(0).getValueType())) {
7843 
7844     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7845     return true;
7846   }
7847 
7848   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7849   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7850       LD->isNonTemporal())
7851     return false;
7852   if (LD->getMemoryVT() != MemVT)
7853     return false;
7854 
7855   RLI.Ptr = LD->getBasePtr();
7856   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7857     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7858            "Non-pre-inc AM on PPC?");
7859     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7860                           LD->getOffset());
7861   }
7862 
7863   RLI.Chain = LD->getChain();
7864   RLI.MPI = LD->getPointerInfo();
7865   RLI.IsDereferenceable = LD->isDereferenceable();
7866   RLI.IsInvariant = LD->isInvariant();
7867   RLI.Alignment = LD->getAlignment();
7868   RLI.AAInfo = LD->getAAInfo();
7869   RLI.Ranges = LD->getRanges();
7870 
7871   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7872   return true;
7873 }
7874 
7875 // Given the head of the old chain, ResChain, insert a token factor containing
7876 // it and NewResChain, and make users of ResChain now be users of that token
7877 // factor.
7878 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7879 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7880                                         SDValue NewResChain,
7881                                         SelectionDAG &DAG) const {
7882   if (!ResChain)
7883     return;
7884 
7885   SDLoc dl(NewResChain);
7886 
7887   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7888                            NewResChain, DAG.getUNDEF(MVT::Other));
7889   assert(TF.getNode() != NewResChain.getNode() &&
7890          "A new TF really is required here");
7891 
7892   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7893   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7894 }
7895 
7896 /// Analyze profitability of direct move
7897 /// prefer float load to int load plus direct move
7898 /// when there is no integer use of int load
7899 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7900   SDNode *Origin = Op.getOperand(0).getNode();
7901   if (Origin->getOpcode() != ISD::LOAD)
7902     return true;
7903 
7904   // If there is no LXSIBZX/LXSIHZX, like Power8,
7905   // prefer direct move if the memory size is 1 or 2 bytes.
7906   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7907   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7908     return true;
7909 
7910   for (SDNode::use_iterator UI = Origin->use_begin(),
7911                             UE = Origin->use_end();
7912        UI != UE; ++UI) {
7913 
7914     // Only look at the users of the loaded value.
7915     if (UI.getUse().get().getResNo() != 0)
7916       continue;
7917 
7918     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7919         UI->getOpcode() != ISD::UINT_TO_FP)
7920       return true;
7921   }
7922 
7923   return false;
7924 }
7925 
7926 /// Custom lowers integer to floating point conversions to use
7927 /// the direct move instructions available in ISA 2.07 to avoid the
7928 /// need for load/store combinations.
7929 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7930                                                     SelectionDAG &DAG,
7931                                                     const SDLoc &dl) const {
7932   assert((Op.getValueType() == MVT::f32 ||
7933           Op.getValueType() == MVT::f64) &&
7934          "Invalid floating point type as target of conversion");
7935   assert(Subtarget.hasFPCVT() &&
7936          "Int to FP conversions with direct moves require FPCVT");
7937   SDValue FP;
7938   SDValue Src = Op.getOperand(0);
7939   bool SinglePrec = Op.getValueType() == MVT::f32;
7940   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7941   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7942   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7943                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7944 
7945   if (WordInt) {
7946     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7947                      dl, MVT::f64, Src);
7948     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7949   }
7950   else {
7951     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7952     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7953   }
7954 
7955   return FP;
7956 }
7957 
7958 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7959 
7960   EVT VecVT = Vec.getValueType();
7961   assert(VecVT.isVector() && "Expected a vector type.");
7962   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7963 
7964   EVT EltVT = VecVT.getVectorElementType();
7965   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7966   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7967 
7968   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7969   SmallVector<SDValue, 16> Ops(NumConcat);
7970   Ops[0] = Vec;
7971   SDValue UndefVec = DAG.getUNDEF(VecVT);
7972   for (unsigned i = 1; i < NumConcat; ++i)
7973     Ops[i] = UndefVec;
7974 
7975   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7976 }
7977 
7978 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7979                                                 const SDLoc &dl) const {
7980 
7981   unsigned Opc = Op.getOpcode();
7982   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7983          "Unexpected conversion type");
7984   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7985          "Supports conversions to v2f64/v4f32 only.");
7986 
7987   bool SignedConv = Opc == ISD::SINT_TO_FP;
7988   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7989 
7990   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7991   EVT WideVT = Wide.getValueType();
7992   unsigned WideNumElts = WideVT.getVectorNumElements();
7993   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7994 
7995   SmallVector<int, 16> ShuffV;
7996   for (unsigned i = 0; i < WideNumElts; ++i)
7997     ShuffV.push_back(i + WideNumElts);
7998 
7999   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8000   int SaveElts = FourEltRes ? 4 : 2;
8001   if (Subtarget.isLittleEndian())
8002     for (int i = 0; i < SaveElts; i++)
8003       ShuffV[i * Stride] = i;
8004   else
8005     for (int i = 1; i <= SaveElts; i++)
8006       ShuffV[i * Stride - 1] = i - 1;
8007 
8008   SDValue ShuffleSrc2 =
8009       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8010   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8011   unsigned ExtendOp =
8012       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
8013 
8014   SDValue Extend;
8015   if (!Subtarget.hasP9Altivec() && SignedConv) {
8016     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8017     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8018                          DAG.getValueType(Op.getOperand(0).getValueType()));
8019   } else
8020     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
8021 
8022   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8023 }
8024 
8025 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8026                                           SelectionDAG &DAG) const {
8027   SDLoc dl(Op);
8028 
8029   EVT InVT = Op.getOperand(0).getValueType();
8030   EVT OutVT = Op.getValueType();
8031   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8032       isOperationCustom(Op.getOpcode(), InVT))
8033     return LowerINT_TO_FPVector(Op, DAG, dl);
8034 
8035   // Conversions to f128 are legal.
8036   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8037     return Op;
8038 
8039   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8040     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8041       return SDValue();
8042 
8043     SDValue Value = Op.getOperand(0);
8044     // The values are now known to be -1 (false) or 1 (true). To convert this
8045     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8046     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8047     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8048 
8049     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8050 
8051     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8052 
8053     if (Op.getValueType() != MVT::v4f64)
8054       Value = DAG.getNode(ISD::FP_ROUND, dl,
8055                           Op.getValueType(), Value,
8056                           DAG.getIntPtrConstant(1, dl));
8057     return Value;
8058   }
8059 
8060   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8061   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8062     return SDValue();
8063 
8064   if (Op.getOperand(0).getValueType() == MVT::i1)
8065     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8066                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8067                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8068 
8069   // If we have direct moves, we can do all the conversion, skip the store/load
8070   // however, without FPCVT we can't do most conversions.
8071   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8072       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8073     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8074 
8075   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8076          "UINT_TO_FP is supported only with FPCVT");
8077 
8078   // If we have FCFIDS, then use it when converting to single-precision.
8079   // Otherwise, convert to double-precision and then round.
8080   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8081                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8082                                                             : PPCISD::FCFIDS)
8083                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8084                                                             : PPCISD::FCFID);
8085   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8086                   ? MVT::f32
8087                   : MVT::f64;
8088 
8089   if (Op.getOperand(0).getValueType() == MVT::i64) {
8090     SDValue SINT = Op.getOperand(0);
8091     // When converting to single-precision, we actually need to convert
8092     // to double-precision first and then round to single-precision.
8093     // To avoid double-rounding effects during that operation, we have
8094     // to prepare the input operand.  Bits that might be truncated when
8095     // converting to double-precision are replaced by a bit that won't
8096     // be lost at this stage, but is below the single-precision rounding
8097     // position.
8098     //
8099     // However, if -enable-unsafe-fp-math is in effect, accept double
8100     // rounding to avoid the extra overhead.
8101     if (Op.getValueType() == MVT::f32 &&
8102         !Subtarget.hasFPCVT() &&
8103         !DAG.getTarget().Options.UnsafeFPMath) {
8104 
8105       // Twiddle input to make sure the low 11 bits are zero.  (If this
8106       // is the case, we are guaranteed the value will fit into the 53 bit
8107       // mantissa of an IEEE double-precision value without rounding.)
8108       // If any of those low 11 bits were not zero originally, make sure
8109       // bit 12 (value 2048) is set instead, so that the final rounding
8110       // to single-precision gets the correct result.
8111       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8112                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8113       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8114                           Round, DAG.getConstant(2047, dl, MVT::i64));
8115       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8116       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8117                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8118 
8119       // However, we cannot use that value unconditionally: if the magnitude
8120       // of the input value is small, the bit-twiddling we did above might
8121       // end up visibly changing the output.  Fortunately, in that case, we
8122       // don't need to twiddle bits since the original input will convert
8123       // exactly to double-precision floating-point already.  Therefore,
8124       // construct a conditional to use the original value if the top 11
8125       // bits are all sign-bit copies, and use the rounded value computed
8126       // above otherwise.
8127       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8128                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8129       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8130                          Cond, DAG.getConstant(1, dl, MVT::i64));
8131       Cond = DAG.getSetCC(dl, MVT::i32,
8132                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8133 
8134       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8135     }
8136 
8137     ReuseLoadInfo RLI;
8138     SDValue Bits;
8139 
8140     MachineFunction &MF = DAG.getMachineFunction();
8141     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8142       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8143                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8144       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8145     } else if (Subtarget.hasLFIWAX() &&
8146                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8147       MachineMemOperand *MMO =
8148         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8149                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8150       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8151       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8152                                      DAG.getVTList(MVT::f64, MVT::Other),
8153                                      Ops, MVT::i32, MMO);
8154       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8155     } else if (Subtarget.hasFPCVT() &&
8156                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8157       MachineMemOperand *MMO =
8158         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8159                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8160       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8161       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8162                                      DAG.getVTList(MVT::f64, MVT::Other),
8163                                      Ops, MVT::i32, MMO);
8164       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8165     } else if (((Subtarget.hasLFIWAX() &&
8166                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8167                 (Subtarget.hasFPCVT() &&
8168                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8169                SINT.getOperand(0).getValueType() == MVT::i32) {
8170       MachineFrameInfo &MFI = MF.getFrameInfo();
8171       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8172 
8173       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8174       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8175 
8176       SDValue Store =
8177           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8178                        MachinePointerInfo::getFixedStack(
8179                            DAG.getMachineFunction(), FrameIdx));
8180 
8181       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8182              "Expected an i32 store");
8183 
8184       RLI.Ptr = FIdx;
8185       RLI.Chain = Store;
8186       RLI.MPI =
8187           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8188       RLI.Alignment = 4;
8189 
8190       MachineMemOperand *MMO =
8191         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8192                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8193       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8194       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8195                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8196                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8197                                      Ops, MVT::i32, MMO);
8198     } else
8199       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8200 
8201     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8202 
8203     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8204       FP = DAG.getNode(ISD::FP_ROUND, dl,
8205                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8206     return FP;
8207   }
8208 
8209   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8210          "Unhandled INT_TO_FP type in custom expander!");
8211   // Since we only generate this in 64-bit mode, we can take advantage of
8212   // 64-bit registers.  In particular, sign extend the input value into the
8213   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8214   // then lfd it and fcfid it.
8215   MachineFunction &MF = DAG.getMachineFunction();
8216   MachineFrameInfo &MFI = MF.getFrameInfo();
8217   EVT PtrVT = getPointerTy(MF.getDataLayout());
8218 
8219   SDValue Ld;
8220   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8221     ReuseLoadInfo RLI;
8222     bool ReusingLoad;
8223     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8224                                             DAG))) {
8225       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8226       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8227 
8228       SDValue Store =
8229           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8230                        MachinePointerInfo::getFixedStack(
8231                            DAG.getMachineFunction(), FrameIdx));
8232 
8233       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8234              "Expected an i32 store");
8235 
8236       RLI.Ptr = FIdx;
8237       RLI.Chain = Store;
8238       RLI.MPI =
8239           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8240       RLI.Alignment = 4;
8241     }
8242 
8243     MachineMemOperand *MMO =
8244       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8245                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8246     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8247     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8248                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8249                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8250                                  Ops, MVT::i32, MMO);
8251     if (ReusingLoad)
8252       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8253   } else {
8254     assert(Subtarget.isPPC64() &&
8255            "i32->FP without LFIWAX supported only on PPC64");
8256 
8257     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8258     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8259 
8260     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8261                                 Op.getOperand(0));
8262 
8263     // STD the extended value into the stack slot.
8264     SDValue Store = DAG.getStore(
8265         DAG.getEntryNode(), dl, Ext64, FIdx,
8266         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8267 
8268     // Load the value as a double.
8269     Ld = DAG.getLoad(
8270         MVT::f64, dl, Store, FIdx,
8271         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8272   }
8273 
8274   // FCFID it and return it.
8275   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8276   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8277     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8278                      DAG.getIntPtrConstant(0, dl));
8279   return FP;
8280 }
8281 
8282 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8283                                             SelectionDAG &DAG) const {
8284   SDLoc dl(Op);
8285   /*
8286    The rounding mode is in bits 30:31 of FPSR, and has the following
8287    settings:
8288      00 Round to nearest
8289      01 Round to 0
8290      10 Round to +inf
8291      11 Round to -inf
8292 
8293   FLT_ROUNDS, on the other hand, expects the following:
8294     -1 Undefined
8295      0 Round to 0
8296      1 Round to nearest
8297      2 Round to +inf
8298      3 Round to -inf
8299 
8300   To perform the conversion, we do:
8301     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8302   */
8303 
8304   MachineFunction &MF = DAG.getMachineFunction();
8305   EVT VT = Op.getValueType();
8306   EVT PtrVT = getPointerTy(MF.getDataLayout());
8307 
8308   // Save FP Control Word to register
8309   SDValue Chain = Op.getOperand(0);
8310   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8311   Chain = MFFS.getValue(1);
8312 
8313   // Save FP register to stack slot
8314   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8315   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8316   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8317 
8318   // Load FP Control Word from low 32 bits of stack slot.
8319   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8320   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8321   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8322   Chain = CWD.getValue(1);
8323 
8324   // Transform as necessary
8325   SDValue CWD1 =
8326     DAG.getNode(ISD::AND, dl, MVT::i32,
8327                 CWD, DAG.getConstant(3, dl, MVT::i32));
8328   SDValue CWD2 =
8329     DAG.getNode(ISD::SRL, dl, MVT::i32,
8330                 DAG.getNode(ISD::AND, dl, MVT::i32,
8331                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8332                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8333                             DAG.getConstant(3, dl, MVT::i32)),
8334                 DAG.getConstant(1, dl, MVT::i32));
8335 
8336   SDValue RetVal =
8337     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8338 
8339   RetVal =
8340       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8341                   dl, VT, RetVal);
8342 
8343   return DAG.getMergeValues({RetVal, Chain}, dl);
8344 }
8345 
8346 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8347   EVT VT = Op.getValueType();
8348   unsigned BitWidth = VT.getSizeInBits();
8349   SDLoc dl(Op);
8350   assert(Op.getNumOperands() == 3 &&
8351          VT == Op.getOperand(1).getValueType() &&
8352          "Unexpected SHL!");
8353 
8354   // Expand into a bunch of logical ops.  Note that these ops
8355   // depend on the PPC behavior for oversized shift amounts.
8356   SDValue Lo = Op.getOperand(0);
8357   SDValue Hi = Op.getOperand(1);
8358   SDValue Amt = Op.getOperand(2);
8359   EVT AmtVT = Amt.getValueType();
8360 
8361   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8362                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8363   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8364   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8365   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8366   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8367                              DAG.getConstant(-BitWidth, dl, AmtVT));
8368   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8369   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8370   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8371   SDValue OutOps[] = { OutLo, OutHi };
8372   return DAG.getMergeValues(OutOps, dl);
8373 }
8374 
8375 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8376   EVT VT = Op.getValueType();
8377   SDLoc dl(Op);
8378   unsigned BitWidth = VT.getSizeInBits();
8379   assert(Op.getNumOperands() == 3 &&
8380          VT == Op.getOperand(1).getValueType() &&
8381          "Unexpected SRL!");
8382 
8383   // Expand into a bunch of logical ops.  Note that these ops
8384   // depend on the PPC behavior for oversized shift amounts.
8385   SDValue Lo = Op.getOperand(0);
8386   SDValue Hi = Op.getOperand(1);
8387   SDValue Amt = Op.getOperand(2);
8388   EVT AmtVT = Amt.getValueType();
8389 
8390   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8391                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8392   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8393   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8394   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8395   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8396                              DAG.getConstant(-BitWidth, dl, AmtVT));
8397   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8398   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8399   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8400   SDValue OutOps[] = { OutLo, OutHi };
8401   return DAG.getMergeValues(OutOps, dl);
8402 }
8403 
8404 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8405   SDLoc dl(Op);
8406   EVT VT = Op.getValueType();
8407   unsigned BitWidth = VT.getSizeInBits();
8408   assert(Op.getNumOperands() == 3 &&
8409          VT == Op.getOperand(1).getValueType() &&
8410          "Unexpected SRA!");
8411 
8412   // Expand into a bunch of logical ops, followed by a select_cc.
8413   SDValue Lo = Op.getOperand(0);
8414   SDValue Hi = Op.getOperand(1);
8415   SDValue Amt = Op.getOperand(2);
8416   EVT AmtVT = Amt.getValueType();
8417 
8418   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8419                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8420   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8421   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8422   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8423   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8424                              DAG.getConstant(-BitWidth, dl, AmtVT));
8425   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8426   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8427   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8428                                   Tmp4, Tmp6, ISD::SETLE);
8429   SDValue OutOps[] = { OutLo, OutHi };
8430   return DAG.getMergeValues(OutOps, dl);
8431 }
8432 
8433 //===----------------------------------------------------------------------===//
8434 // Vector related lowering.
8435 //
8436 
8437 /// BuildSplatI - Build a canonical splati of Val with an element size of
8438 /// SplatSize.  Cast the result to VT.
8439 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8440                            SelectionDAG &DAG, const SDLoc &dl) {
8441   static const MVT VTys[] = { // canonical VT to use for each size.
8442     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8443   };
8444 
8445   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8446 
8447   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8448   if (Val == -1)
8449     SplatSize = 1;
8450 
8451   EVT CanonicalVT = VTys[SplatSize-1];
8452 
8453   // Build a canonical splat for this value.
8454   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8455 }
8456 
8457 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8458 /// specified intrinsic ID.
8459 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8460                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8461   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8462   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8463                      DAG.getConstant(IID, dl, MVT::i32), Op);
8464 }
8465 
8466 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8467 /// specified intrinsic ID.
8468 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8469                                 SelectionDAG &DAG, const SDLoc &dl,
8470                                 EVT DestVT = MVT::Other) {
8471   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8472   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8473                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8474 }
8475 
8476 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8477 /// specified intrinsic ID.
8478 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8479                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8480                                 EVT DestVT = MVT::Other) {
8481   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8482   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8483                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8484 }
8485 
8486 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8487 /// amount.  The result has the specified value type.
8488 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8489                            SelectionDAG &DAG, const SDLoc &dl) {
8490   // Force LHS/RHS to be the right type.
8491   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8492   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8493 
8494   int Ops[16];
8495   for (unsigned i = 0; i != 16; ++i)
8496     Ops[i] = i + Amt;
8497   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8498   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8499 }
8500 
8501 /// Do we have an efficient pattern in a .td file for this node?
8502 ///
8503 /// \param V - pointer to the BuildVectorSDNode being matched
8504 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8505 ///
8506 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8507 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8508 /// the opposite is true (expansion is beneficial) are:
8509 /// - The node builds a vector out of integers that are not 32 or 64-bits
8510 /// - The node builds a vector out of constants
8511 /// - The node is a "load-and-splat"
8512 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8513 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8514                                             bool HasDirectMove,
8515                                             bool HasP8Vector) {
8516   EVT VecVT = V->getValueType(0);
8517   bool RightType = VecVT == MVT::v2f64 ||
8518     (HasP8Vector && VecVT == MVT::v4f32) ||
8519     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8520   if (!RightType)
8521     return false;
8522 
8523   bool IsSplat = true;
8524   bool IsLoad = false;
8525   SDValue Op0 = V->getOperand(0);
8526 
8527   // This function is called in a block that confirms the node is not a constant
8528   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8529   // different constants.
8530   if (V->isConstant())
8531     return false;
8532   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8533     if (V->getOperand(i).isUndef())
8534       return false;
8535     // We want to expand nodes that represent load-and-splat even if the
8536     // loaded value is a floating point truncation or conversion to int.
8537     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8538         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8539          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8540         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8541          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8542         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8543          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8544       IsLoad = true;
8545     // If the operands are different or the input is not a load and has more
8546     // uses than just this BV node, then it isn't a splat.
8547     if (V->getOperand(i) != Op0 ||
8548         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8549       IsSplat = false;
8550   }
8551   return !(IsSplat && IsLoad);
8552 }
8553 
8554 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8555 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8556 
8557   SDLoc dl(Op);
8558   SDValue Op0 = Op->getOperand(0);
8559 
8560   if (!EnableQuadPrecision ||
8561       (Op.getValueType() != MVT::f128 ) ||
8562       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8563       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8564       (Op0.getOperand(1).getValueType() != MVT::i64))
8565     return SDValue();
8566 
8567   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8568                      Op0.getOperand(1));
8569 }
8570 
8571 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8572   const SDValue *InputLoad = &Op;
8573   if (InputLoad->getOpcode() == ISD::BITCAST)
8574     InputLoad = &InputLoad->getOperand(0);
8575   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8576     InputLoad = &InputLoad->getOperand(0);
8577   if (InputLoad->getOpcode() != ISD::LOAD)
8578     return nullptr;
8579   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8580   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8581 }
8582 
8583 // If this is a case we can't handle, return null and let the default
8584 // expansion code take care of it.  If we CAN select this case, and if it
8585 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8586 // this case more efficiently than a constant pool load, lower it to the
8587 // sequence of ops that should be used.
8588 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8589                                              SelectionDAG &DAG) const {
8590   SDLoc dl(Op);
8591   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8592   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8593 
8594   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8595     // We first build an i32 vector, load it into a QPX register,
8596     // then convert it to a floating-point vector and compare it
8597     // to a zero vector to get the boolean result.
8598     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8599     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8600     MachinePointerInfo PtrInfo =
8601         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8602     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8603     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8604 
8605     assert(BVN->getNumOperands() == 4 &&
8606       "BUILD_VECTOR for v4i1 does not have 4 operands");
8607 
8608     bool IsConst = true;
8609     for (unsigned i = 0; i < 4; ++i) {
8610       if (BVN->getOperand(i).isUndef()) continue;
8611       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8612         IsConst = false;
8613         break;
8614       }
8615     }
8616 
8617     if (IsConst) {
8618       Constant *One =
8619         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8620       Constant *NegOne =
8621         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8622 
8623       Constant *CV[4];
8624       for (unsigned i = 0; i < 4; ++i) {
8625         if (BVN->getOperand(i).isUndef())
8626           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8627         else if (isNullConstant(BVN->getOperand(i)))
8628           CV[i] = NegOne;
8629         else
8630           CV[i] = One;
8631       }
8632 
8633       Constant *CP = ConstantVector::get(CV);
8634       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8635                                           16 /* alignment */);
8636 
8637       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8638       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8639       return DAG.getMemIntrinsicNode(
8640           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8641           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8642     }
8643 
8644     SmallVector<SDValue, 4> Stores;
8645     for (unsigned i = 0; i < 4; ++i) {
8646       if (BVN->getOperand(i).isUndef()) continue;
8647 
8648       unsigned Offset = 4*i;
8649       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8650       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8651 
8652       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8653       if (StoreSize > 4) {
8654         Stores.push_back(
8655             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8656                               PtrInfo.getWithOffset(Offset), MVT::i32));
8657       } else {
8658         SDValue StoreValue = BVN->getOperand(i);
8659         if (StoreSize < 4)
8660           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8661 
8662         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8663                                       PtrInfo.getWithOffset(Offset)));
8664       }
8665     }
8666 
8667     SDValue StoreChain;
8668     if (!Stores.empty())
8669       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8670     else
8671       StoreChain = DAG.getEntryNode();
8672 
8673     // Now load from v4i32 into the QPX register; this will extend it to
8674     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8675     // is typed as v4f64 because the QPX register integer states are not
8676     // explicitly represented.
8677 
8678     SDValue Ops[] = {StoreChain,
8679                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8680                      FIdx};
8681     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8682 
8683     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8684       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8685     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8686       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8687       LoadedVect);
8688 
8689     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8690 
8691     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8692   }
8693 
8694   // All other QPX vectors are handled by generic code.
8695   if (Subtarget.hasQPX())
8696     return SDValue();
8697 
8698   // Check if this is a splat of a constant value.
8699   APInt APSplatBits, APSplatUndef;
8700   unsigned SplatBitSize;
8701   bool HasAnyUndefs;
8702   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8703                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8704       SplatBitSize > 32) {
8705 
8706     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
8707     // Handle load-and-splat patterns as we have instructions that will do this
8708     // in one go.
8709     if (InputLoad && DAG.isSplatValue(Op, true)) {
8710       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8711 
8712       // We have handling for 4 and 8 byte elements.
8713       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8714 
8715       // Checking for a single use of this load, we have to check for vector
8716       // width (128 bits) / ElementSize uses (since each operand of the
8717       // BUILD_VECTOR is a separate use of the value.
8718       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8719           ((Subtarget.hasVSX() && ElementSize == 64) ||
8720            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8721         SDValue Ops[] = {
8722           LD->getChain(),    // Chain
8723           LD->getBasePtr(),  // Ptr
8724           DAG.getValueType(Op.getValueType()) // VT
8725         };
8726         return
8727           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8728                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8729                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8730       }
8731     }
8732 
8733     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8734     // lowered to VSX instructions under certain conditions.
8735     // Without VSX, there is no pattern more efficient than expanding the node.
8736     if (Subtarget.hasVSX() &&
8737         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8738                                         Subtarget.hasP8Vector()))
8739       return Op;
8740     return SDValue();
8741   }
8742 
8743   unsigned SplatBits = APSplatBits.getZExtValue();
8744   unsigned SplatUndef = APSplatUndef.getZExtValue();
8745   unsigned SplatSize = SplatBitSize / 8;
8746 
8747   // First, handle single instruction cases.
8748 
8749   // All zeros?
8750   if (SplatBits == 0) {
8751     // Canonicalize all zero vectors to be v4i32.
8752     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8753       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8754       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8755     }
8756     return Op;
8757   }
8758 
8759   // We have XXSPLTIB for constant splats one byte wide
8760   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
8761   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
8762   if (Subtarget.hasP9Vector() && SplatSize == 1)
8763     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
8764 
8765   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8766   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8767                     (32-SplatBitSize));
8768   if (SextVal >= -16 && SextVal <= 15)
8769     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8770 
8771   // Two instruction sequences.
8772 
8773   // If this value is in the range [-32,30] and is even, use:
8774   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8775   // If this value is in the range [17,31] and is odd, use:
8776   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8777   // If this value is in the range [-31,-17] and is odd, use:
8778   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8779   // Note the last two are three-instruction sequences.
8780   if (SextVal >= -32 && SextVal <= 31) {
8781     // To avoid having these optimizations undone by constant folding,
8782     // we convert to a pseudo that will be expanded later into one of
8783     // the above forms.
8784     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8785     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8786               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8787     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8788     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8789     if (VT == Op.getValueType())
8790       return RetVal;
8791     else
8792       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8793   }
8794 
8795   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8796   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8797   // for fneg/fabs.
8798   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8799     // Make -1 and vspltisw -1:
8800     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8801 
8802     // Make the VSLW intrinsic, computing 0x8000_0000.
8803     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8804                                    OnesV, DAG, dl);
8805 
8806     // xor by OnesV to invert it.
8807     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8808     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8809   }
8810 
8811   // Check to see if this is a wide variety of vsplti*, binop self cases.
8812   static const signed char SplatCsts[] = {
8813     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8814     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8815   };
8816 
8817   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8818     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8819     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8820     int i = SplatCsts[idx];
8821 
8822     // Figure out what shift amount will be used by altivec if shifted by i in
8823     // this splat size.
8824     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8825 
8826     // vsplti + shl self.
8827     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8828       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8829       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8830         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8831         Intrinsic::ppc_altivec_vslw
8832       };
8833       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8834       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8835     }
8836 
8837     // vsplti + srl self.
8838     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8839       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8840       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8841         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8842         Intrinsic::ppc_altivec_vsrw
8843       };
8844       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8845       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8846     }
8847 
8848     // vsplti + sra self.
8849     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8850       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8851       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8852         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8853         Intrinsic::ppc_altivec_vsraw
8854       };
8855       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8856       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8857     }
8858 
8859     // vsplti + rol self.
8860     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8861                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8862       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8863       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8864         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8865         Intrinsic::ppc_altivec_vrlw
8866       };
8867       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8868       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8869     }
8870 
8871     // t = vsplti c, result = vsldoi t, t, 1
8872     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8873       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8874       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8875       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8876     }
8877     // t = vsplti c, result = vsldoi t, t, 2
8878     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8879       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8880       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8881       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8882     }
8883     // t = vsplti c, result = vsldoi t, t, 3
8884     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8885       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8886       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8887       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8888     }
8889   }
8890 
8891   return SDValue();
8892 }
8893 
8894 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8895 /// the specified operations to build the shuffle.
8896 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8897                                       SDValue RHS, SelectionDAG &DAG,
8898                                       const SDLoc &dl) {
8899   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8900   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8901   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8902 
8903   enum {
8904     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8905     OP_VMRGHW,
8906     OP_VMRGLW,
8907     OP_VSPLTISW0,
8908     OP_VSPLTISW1,
8909     OP_VSPLTISW2,
8910     OP_VSPLTISW3,
8911     OP_VSLDOI4,
8912     OP_VSLDOI8,
8913     OP_VSLDOI12
8914   };
8915 
8916   if (OpNum == OP_COPY) {
8917     if (LHSID == (1*9+2)*9+3) return LHS;
8918     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8919     return RHS;
8920   }
8921 
8922   SDValue OpLHS, OpRHS;
8923   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8924   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8925 
8926   int ShufIdxs[16];
8927   switch (OpNum) {
8928   default: llvm_unreachable("Unknown i32 permute!");
8929   case OP_VMRGHW:
8930     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8931     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8932     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8933     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8934     break;
8935   case OP_VMRGLW:
8936     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8937     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8938     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8939     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8940     break;
8941   case OP_VSPLTISW0:
8942     for (unsigned i = 0; i != 16; ++i)
8943       ShufIdxs[i] = (i&3)+0;
8944     break;
8945   case OP_VSPLTISW1:
8946     for (unsigned i = 0; i != 16; ++i)
8947       ShufIdxs[i] = (i&3)+4;
8948     break;
8949   case OP_VSPLTISW2:
8950     for (unsigned i = 0; i != 16; ++i)
8951       ShufIdxs[i] = (i&3)+8;
8952     break;
8953   case OP_VSPLTISW3:
8954     for (unsigned i = 0; i != 16; ++i)
8955       ShufIdxs[i] = (i&3)+12;
8956     break;
8957   case OP_VSLDOI4:
8958     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8959   case OP_VSLDOI8:
8960     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8961   case OP_VSLDOI12:
8962     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8963   }
8964   EVT VT = OpLHS.getValueType();
8965   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8966   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8967   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8968   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8969 }
8970 
8971 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8972 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8973 /// SDValue.
8974 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8975                                            SelectionDAG &DAG) const {
8976   const unsigned BytesInVector = 16;
8977   bool IsLE = Subtarget.isLittleEndian();
8978   SDLoc dl(N);
8979   SDValue V1 = N->getOperand(0);
8980   SDValue V2 = N->getOperand(1);
8981   unsigned ShiftElts = 0, InsertAtByte = 0;
8982   bool Swap = false;
8983 
8984   // Shifts required to get the byte we want at element 7.
8985   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8986                                    0, 15, 14, 13, 12, 11, 10, 9};
8987   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8988                                 1, 2,  3,  4,  5,  6,  7,  8};
8989 
8990   ArrayRef<int> Mask = N->getMask();
8991   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8992 
8993   // For each mask element, find out if we're just inserting something
8994   // from V2 into V1 or vice versa.
8995   // Possible permutations inserting an element from V2 into V1:
8996   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8997   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8998   //   ...
8999   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9000   // Inserting from V1 into V2 will be similar, except mask range will be
9001   // [16,31].
9002 
9003   bool FoundCandidate = false;
9004   // If both vector operands for the shuffle are the same vector, the mask
9005   // will contain only elements from the first one and the second one will be
9006   // undef.
9007   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9008   // Go through the mask of half-words to find an element that's being moved
9009   // from one vector to the other.
9010   for (unsigned i = 0; i < BytesInVector; ++i) {
9011     unsigned CurrentElement = Mask[i];
9012     // If 2nd operand is undefined, we should only look for element 7 in the
9013     // Mask.
9014     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9015       continue;
9016 
9017     bool OtherElementsInOrder = true;
9018     // Examine the other elements in the Mask to see if they're in original
9019     // order.
9020     for (unsigned j = 0; j < BytesInVector; ++j) {
9021       if (j == i)
9022         continue;
9023       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9024       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9025       // in which we always assume we're always picking from the 1st operand.
9026       int MaskOffset =
9027           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9028       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9029         OtherElementsInOrder = false;
9030         break;
9031       }
9032     }
9033     // If other elements are in original order, we record the number of shifts
9034     // we need to get the element we want into element 7. Also record which byte
9035     // in the vector we should insert into.
9036     if (OtherElementsInOrder) {
9037       // If 2nd operand is undefined, we assume no shifts and no swapping.
9038       if (V2.isUndef()) {
9039         ShiftElts = 0;
9040         Swap = false;
9041       } else {
9042         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9043         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9044                          : BigEndianShifts[CurrentElement & 0xF];
9045         Swap = CurrentElement < BytesInVector;
9046       }
9047       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9048       FoundCandidate = true;
9049       break;
9050     }
9051   }
9052 
9053   if (!FoundCandidate)
9054     return SDValue();
9055 
9056   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9057   // optionally with VECSHL if shift is required.
9058   if (Swap)
9059     std::swap(V1, V2);
9060   if (V2.isUndef())
9061     V2 = V1;
9062   if (ShiftElts) {
9063     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9064                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9065     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9066                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9067   }
9068   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9069                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9070 }
9071 
9072 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9073 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9074 /// SDValue.
9075 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9076                                            SelectionDAG &DAG) const {
9077   const unsigned NumHalfWords = 8;
9078   const unsigned BytesInVector = NumHalfWords * 2;
9079   // Check that the shuffle is on half-words.
9080   if (!isNByteElemShuffleMask(N, 2, 1))
9081     return SDValue();
9082 
9083   bool IsLE = Subtarget.isLittleEndian();
9084   SDLoc dl(N);
9085   SDValue V1 = N->getOperand(0);
9086   SDValue V2 = N->getOperand(1);
9087   unsigned ShiftElts = 0, InsertAtByte = 0;
9088   bool Swap = false;
9089 
9090   // Shifts required to get the half-word we want at element 3.
9091   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9092   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9093 
9094   uint32_t Mask = 0;
9095   uint32_t OriginalOrderLow = 0x1234567;
9096   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9097   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9098   // 32-bit space, only need 4-bit nibbles per element.
9099   for (unsigned i = 0; i < NumHalfWords; ++i) {
9100     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9101     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9102   }
9103 
9104   // For each mask element, find out if we're just inserting something
9105   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9106   // from V2 into V1:
9107   //   X, 1, 2, 3, 4, 5, 6, 7
9108   //   0, X, 2, 3, 4, 5, 6, 7
9109   //   0, 1, X, 3, 4, 5, 6, 7
9110   //   0, 1, 2, X, 4, 5, 6, 7
9111   //   0, 1, 2, 3, X, 5, 6, 7
9112   //   0, 1, 2, 3, 4, X, 6, 7
9113   //   0, 1, 2, 3, 4, 5, X, 7
9114   //   0, 1, 2, 3, 4, 5, 6, X
9115   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9116 
9117   bool FoundCandidate = false;
9118   // Go through the mask of half-words to find an element that's being moved
9119   // from one vector to the other.
9120   for (unsigned i = 0; i < NumHalfWords; ++i) {
9121     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9122     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9123     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9124     uint32_t TargetOrder = 0x0;
9125 
9126     // If both vector operands for the shuffle are the same vector, the mask
9127     // will contain only elements from the first one and the second one will be
9128     // undef.
9129     if (V2.isUndef()) {
9130       ShiftElts = 0;
9131       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9132       TargetOrder = OriginalOrderLow;
9133       Swap = false;
9134       // Skip if not the correct element or mask of other elements don't equal
9135       // to our expected order.
9136       if (MaskOneElt == VINSERTHSrcElem &&
9137           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9138         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9139         FoundCandidate = true;
9140         break;
9141       }
9142     } else { // If both operands are defined.
9143       // Target order is [8,15] if the current mask is between [0,7].
9144       TargetOrder =
9145           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9146       // Skip if mask of other elements don't equal our expected order.
9147       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9148         // We only need the last 3 bits for the number of shifts.
9149         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9150                          : BigEndianShifts[MaskOneElt & 0x7];
9151         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9152         Swap = MaskOneElt < NumHalfWords;
9153         FoundCandidate = true;
9154         break;
9155       }
9156     }
9157   }
9158 
9159   if (!FoundCandidate)
9160     return SDValue();
9161 
9162   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9163   // optionally with VECSHL if shift is required.
9164   if (Swap)
9165     std::swap(V1, V2);
9166   if (V2.isUndef())
9167     V2 = V1;
9168   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9169   if (ShiftElts) {
9170     // Double ShiftElts because we're left shifting on v16i8 type.
9171     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9172                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9173     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9174     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9175                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9176     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9177   }
9178   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9179   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9180                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9181   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9182 }
9183 
9184 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9185 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9186 /// return the code it can be lowered into.  Worst case, it can always be
9187 /// lowered into a vperm.
9188 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9189                                                SelectionDAG &DAG) const {
9190   SDLoc dl(Op);
9191   SDValue V1 = Op.getOperand(0);
9192   SDValue V2 = Op.getOperand(1);
9193   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9194   EVT VT = Op.getValueType();
9195   bool isLittleEndian = Subtarget.isLittleEndian();
9196 
9197   unsigned ShiftElts, InsertAtByte;
9198   bool Swap = false;
9199 
9200   // If this is a load-and-splat, we can do that with a single instruction
9201   // in some cases. However if the load has multiple uses, we don't want to
9202   // combine it because that will just produce multiple loads.
9203   const SDValue *InputLoad = getNormalLoadInput(V1);
9204   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9205       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9206       InputLoad->hasOneUse()) {
9207     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9208     int SplatIdx =
9209       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9210 
9211     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9212     // For 4-byte load-and-splat, we need Power9.
9213     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9214       uint64_t Offset = 0;
9215       if (IsFourByte)
9216         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9217       else
9218         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9219       SDValue BasePtr = LD->getBasePtr();
9220       if (Offset != 0)
9221         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9222                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9223       SDValue Ops[] = {
9224         LD->getChain(),    // Chain
9225         BasePtr,           // BasePtr
9226         DAG.getValueType(Op.getValueType()) // VT
9227       };
9228       SDVTList VTL =
9229         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9230       SDValue LdSplt =
9231         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9232                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9233       if (LdSplt.getValueType() != SVOp->getValueType(0))
9234         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9235       return LdSplt;
9236     }
9237   }
9238   if (Subtarget.hasP9Vector() &&
9239       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9240                            isLittleEndian)) {
9241     if (Swap)
9242       std::swap(V1, V2);
9243     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9244     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9245     if (ShiftElts) {
9246       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9247                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9248       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9249                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9250       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9251     }
9252     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9253                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9254     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9255   }
9256 
9257   if (Subtarget.hasP9Altivec()) {
9258     SDValue NewISDNode;
9259     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9260       return NewISDNode;
9261 
9262     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9263       return NewISDNode;
9264   }
9265 
9266   if (Subtarget.hasVSX() &&
9267       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9268     if (Swap)
9269       std::swap(V1, V2);
9270     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9271     SDValue Conv2 =
9272         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9273 
9274     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9275                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9276     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9277   }
9278 
9279   if (Subtarget.hasVSX() &&
9280     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9281     if (Swap)
9282       std::swap(V1, V2);
9283     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9284     SDValue Conv2 =
9285         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9286 
9287     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9288                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9289     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9290   }
9291 
9292   if (Subtarget.hasP9Vector()) {
9293      if (PPC::isXXBRHShuffleMask(SVOp)) {
9294       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9295       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9296       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9297     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9298       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9299       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9300       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9301     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9302       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9303       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9304       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9305     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9306       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9307       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9308       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9309     }
9310   }
9311 
9312   if (Subtarget.hasVSX()) {
9313     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9314       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9315 
9316       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9317       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9318                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9319       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9320     }
9321 
9322     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9323     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9324       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9325       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9326       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9327     }
9328   }
9329 
9330   if (Subtarget.hasQPX()) {
9331     if (VT.getVectorNumElements() != 4)
9332       return SDValue();
9333 
9334     if (V2.isUndef()) V2 = V1;
9335 
9336     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9337     if (AlignIdx != -1) {
9338       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9339                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9340     } else if (SVOp->isSplat()) {
9341       int SplatIdx = SVOp->getSplatIndex();
9342       if (SplatIdx >= 4) {
9343         std::swap(V1, V2);
9344         SplatIdx -= 4;
9345       }
9346 
9347       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9348                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9349     }
9350 
9351     // Lower this into a qvgpci/qvfperm pair.
9352 
9353     // Compute the qvgpci literal
9354     unsigned idx = 0;
9355     for (unsigned i = 0; i < 4; ++i) {
9356       int m = SVOp->getMaskElt(i);
9357       unsigned mm = m >= 0 ? (unsigned) m : i;
9358       idx |= mm << (3-i)*3;
9359     }
9360 
9361     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9362                              DAG.getConstant(idx, dl, MVT::i32));
9363     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9364   }
9365 
9366   // Cases that are handled by instructions that take permute immediates
9367   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9368   // selected by the instruction selector.
9369   if (V2.isUndef()) {
9370     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9371         PPC::isSplatShuffleMask(SVOp, 2) ||
9372         PPC::isSplatShuffleMask(SVOp, 4) ||
9373         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9374         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9375         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9376         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9377         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9378         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9379         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9380         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9381         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9382         (Subtarget.hasP8Altivec() && (
9383          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9384          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9385          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9386       return Op;
9387     }
9388   }
9389 
9390   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9391   // and produce a fixed permutation.  If any of these match, do not lower to
9392   // VPERM.
9393   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9394   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9395       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9396       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9397       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9398       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9399       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9400       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9401       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9402       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9403       (Subtarget.hasP8Altivec() && (
9404        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9405        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9406        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9407     return Op;
9408 
9409   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9410   // perfect shuffle table to emit an optimal matching sequence.
9411   ArrayRef<int> PermMask = SVOp->getMask();
9412 
9413   unsigned PFIndexes[4];
9414   bool isFourElementShuffle = true;
9415   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9416     unsigned EltNo = 8;   // Start out undef.
9417     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9418       if (PermMask[i*4+j] < 0)
9419         continue;   // Undef, ignore it.
9420 
9421       unsigned ByteSource = PermMask[i*4+j];
9422       if ((ByteSource & 3) != j) {
9423         isFourElementShuffle = false;
9424         break;
9425       }
9426 
9427       if (EltNo == 8) {
9428         EltNo = ByteSource/4;
9429       } else if (EltNo != ByteSource/4) {
9430         isFourElementShuffle = false;
9431         break;
9432       }
9433     }
9434     PFIndexes[i] = EltNo;
9435   }
9436 
9437   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9438   // perfect shuffle vector to determine if it is cost effective to do this as
9439   // discrete instructions, or whether we should use a vperm.
9440   // For now, we skip this for little endian until such time as we have a
9441   // little-endian perfect shuffle table.
9442   if (isFourElementShuffle && !isLittleEndian) {
9443     // Compute the index in the perfect shuffle table.
9444     unsigned PFTableIndex =
9445       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9446 
9447     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9448     unsigned Cost  = (PFEntry >> 30);
9449 
9450     // Determining when to avoid vperm is tricky.  Many things affect the cost
9451     // of vperm, particularly how many times the perm mask needs to be computed.
9452     // For example, if the perm mask can be hoisted out of a loop or is already
9453     // used (perhaps because there are multiple permutes with the same shuffle
9454     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9455     // the loop requires an extra register.
9456     //
9457     // As a compromise, we only emit discrete instructions if the shuffle can be
9458     // generated in 3 or fewer operations.  When we have loop information
9459     // available, if this block is within a loop, we should avoid using vperm
9460     // for 3-operation perms and use a constant pool load instead.
9461     if (Cost < 3)
9462       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9463   }
9464 
9465   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9466   // vector that will get spilled to the constant pool.
9467   if (V2.isUndef()) V2 = V1;
9468 
9469   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9470   // that it is in input element units, not in bytes.  Convert now.
9471 
9472   // For little endian, the order of the input vectors is reversed, and
9473   // the permutation mask is complemented with respect to 31.  This is
9474   // necessary to produce proper semantics with the big-endian-biased vperm
9475   // instruction.
9476   EVT EltVT = V1.getValueType().getVectorElementType();
9477   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9478 
9479   SmallVector<SDValue, 16> ResultMask;
9480   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9481     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9482 
9483     for (unsigned j = 0; j != BytesPerElement; ++j)
9484       if (isLittleEndian)
9485         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9486                                              dl, MVT::i32));
9487       else
9488         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9489                                              MVT::i32));
9490   }
9491 
9492   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9493   if (isLittleEndian)
9494     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9495                        V2, V1, VPermMask);
9496   else
9497     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9498                        V1, V2, VPermMask);
9499 }
9500 
9501 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9502 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9503 /// information about the intrinsic.
9504 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9505                                  bool &isDot, const PPCSubtarget &Subtarget) {
9506   unsigned IntrinsicID =
9507       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9508   CompareOpc = -1;
9509   isDot = false;
9510   switch (IntrinsicID) {
9511   default:
9512     return false;
9513   // Comparison predicates.
9514   case Intrinsic::ppc_altivec_vcmpbfp_p:
9515     CompareOpc = 966;
9516     isDot = true;
9517     break;
9518   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9519     CompareOpc = 198;
9520     isDot = true;
9521     break;
9522   case Intrinsic::ppc_altivec_vcmpequb_p:
9523     CompareOpc = 6;
9524     isDot = true;
9525     break;
9526   case Intrinsic::ppc_altivec_vcmpequh_p:
9527     CompareOpc = 70;
9528     isDot = true;
9529     break;
9530   case Intrinsic::ppc_altivec_vcmpequw_p:
9531     CompareOpc = 134;
9532     isDot = true;
9533     break;
9534   case Intrinsic::ppc_altivec_vcmpequd_p:
9535     if (Subtarget.hasP8Altivec()) {
9536       CompareOpc = 199;
9537       isDot = true;
9538     } else
9539       return false;
9540     break;
9541   case Intrinsic::ppc_altivec_vcmpneb_p:
9542   case Intrinsic::ppc_altivec_vcmpneh_p:
9543   case Intrinsic::ppc_altivec_vcmpnew_p:
9544   case Intrinsic::ppc_altivec_vcmpnezb_p:
9545   case Intrinsic::ppc_altivec_vcmpnezh_p:
9546   case Intrinsic::ppc_altivec_vcmpnezw_p:
9547     if (Subtarget.hasP9Altivec()) {
9548       switch (IntrinsicID) {
9549       default:
9550         llvm_unreachable("Unknown comparison intrinsic.");
9551       case Intrinsic::ppc_altivec_vcmpneb_p:
9552         CompareOpc = 7;
9553         break;
9554       case Intrinsic::ppc_altivec_vcmpneh_p:
9555         CompareOpc = 71;
9556         break;
9557       case Intrinsic::ppc_altivec_vcmpnew_p:
9558         CompareOpc = 135;
9559         break;
9560       case Intrinsic::ppc_altivec_vcmpnezb_p:
9561         CompareOpc = 263;
9562         break;
9563       case Intrinsic::ppc_altivec_vcmpnezh_p:
9564         CompareOpc = 327;
9565         break;
9566       case Intrinsic::ppc_altivec_vcmpnezw_p:
9567         CompareOpc = 391;
9568         break;
9569       }
9570       isDot = true;
9571     } else
9572       return false;
9573     break;
9574   case Intrinsic::ppc_altivec_vcmpgefp_p:
9575     CompareOpc = 454;
9576     isDot = true;
9577     break;
9578   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9579     CompareOpc = 710;
9580     isDot = true;
9581     break;
9582   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9583     CompareOpc = 774;
9584     isDot = true;
9585     break;
9586   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9587     CompareOpc = 838;
9588     isDot = true;
9589     break;
9590   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9591     CompareOpc = 902;
9592     isDot = true;
9593     break;
9594   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9595     if (Subtarget.hasP8Altivec()) {
9596       CompareOpc = 967;
9597       isDot = true;
9598     } else
9599       return false;
9600     break;
9601   case Intrinsic::ppc_altivec_vcmpgtub_p:
9602     CompareOpc = 518;
9603     isDot = true;
9604     break;
9605   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9606     CompareOpc = 582;
9607     isDot = true;
9608     break;
9609   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9610     CompareOpc = 646;
9611     isDot = true;
9612     break;
9613   case Intrinsic::ppc_altivec_vcmpgtud_p:
9614     if (Subtarget.hasP8Altivec()) {
9615       CompareOpc = 711;
9616       isDot = true;
9617     } else
9618       return false;
9619     break;
9620 
9621   // VSX predicate comparisons use the same infrastructure
9622   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9623   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9624   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9625   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9626   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9627   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9628     if (Subtarget.hasVSX()) {
9629       switch (IntrinsicID) {
9630       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9631         CompareOpc = 99;
9632         break;
9633       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9634         CompareOpc = 115;
9635         break;
9636       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9637         CompareOpc = 107;
9638         break;
9639       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9640         CompareOpc = 67;
9641         break;
9642       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9643         CompareOpc = 83;
9644         break;
9645       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9646         CompareOpc = 75;
9647         break;
9648       }
9649       isDot = true;
9650     } else
9651       return false;
9652     break;
9653 
9654   // Normal Comparisons.
9655   case Intrinsic::ppc_altivec_vcmpbfp:
9656     CompareOpc = 966;
9657     break;
9658   case Intrinsic::ppc_altivec_vcmpeqfp:
9659     CompareOpc = 198;
9660     break;
9661   case Intrinsic::ppc_altivec_vcmpequb:
9662     CompareOpc = 6;
9663     break;
9664   case Intrinsic::ppc_altivec_vcmpequh:
9665     CompareOpc = 70;
9666     break;
9667   case Intrinsic::ppc_altivec_vcmpequw:
9668     CompareOpc = 134;
9669     break;
9670   case Intrinsic::ppc_altivec_vcmpequd:
9671     if (Subtarget.hasP8Altivec())
9672       CompareOpc = 199;
9673     else
9674       return false;
9675     break;
9676   case Intrinsic::ppc_altivec_vcmpneb:
9677   case Intrinsic::ppc_altivec_vcmpneh:
9678   case Intrinsic::ppc_altivec_vcmpnew:
9679   case Intrinsic::ppc_altivec_vcmpnezb:
9680   case Intrinsic::ppc_altivec_vcmpnezh:
9681   case Intrinsic::ppc_altivec_vcmpnezw:
9682     if (Subtarget.hasP9Altivec())
9683       switch (IntrinsicID) {
9684       default:
9685         llvm_unreachable("Unknown comparison intrinsic.");
9686       case Intrinsic::ppc_altivec_vcmpneb:
9687         CompareOpc = 7;
9688         break;
9689       case Intrinsic::ppc_altivec_vcmpneh:
9690         CompareOpc = 71;
9691         break;
9692       case Intrinsic::ppc_altivec_vcmpnew:
9693         CompareOpc = 135;
9694         break;
9695       case Intrinsic::ppc_altivec_vcmpnezb:
9696         CompareOpc = 263;
9697         break;
9698       case Intrinsic::ppc_altivec_vcmpnezh:
9699         CompareOpc = 327;
9700         break;
9701       case Intrinsic::ppc_altivec_vcmpnezw:
9702         CompareOpc = 391;
9703         break;
9704       }
9705     else
9706       return false;
9707     break;
9708   case Intrinsic::ppc_altivec_vcmpgefp:
9709     CompareOpc = 454;
9710     break;
9711   case Intrinsic::ppc_altivec_vcmpgtfp:
9712     CompareOpc = 710;
9713     break;
9714   case Intrinsic::ppc_altivec_vcmpgtsb:
9715     CompareOpc = 774;
9716     break;
9717   case Intrinsic::ppc_altivec_vcmpgtsh:
9718     CompareOpc = 838;
9719     break;
9720   case Intrinsic::ppc_altivec_vcmpgtsw:
9721     CompareOpc = 902;
9722     break;
9723   case Intrinsic::ppc_altivec_vcmpgtsd:
9724     if (Subtarget.hasP8Altivec())
9725       CompareOpc = 967;
9726     else
9727       return false;
9728     break;
9729   case Intrinsic::ppc_altivec_vcmpgtub:
9730     CompareOpc = 518;
9731     break;
9732   case Intrinsic::ppc_altivec_vcmpgtuh:
9733     CompareOpc = 582;
9734     break;
9735   case Intrinsic::ppc_altivec_vcmpgtuw:
9736     CompareOpc = 646;
9737     break;
9738   case Intrinsic::ppc_altivec_vcmpgtud:
9739     if (Subtarget.hasP8Altivec())
9740       CompareOpc = 711;
9741     else
9742       return false;
9743     break;
9744   }
9745   return true;
9746 }
9747 
9748 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9749 /// lower, do it, otherwise return null.
9750 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9751                                                    SelectionDAG &DAG) const {
9752   unsigned IntrinsicID =
9753     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9754 
9755   SDLoc dl(Op);
9756 
9757   if (IntrinsicID == Intrinsic::thread_pointer) {
9758     // Reads the thread pointer register, used for __builtin_thread_pointer.
9759     if (Subtarget.isPPC64())
9760       return DAG.getRegister(PPC::X13, MVT::i64);
9761     return DAG.getRegister(PPC::R2, MVT::i32);
9762   }
9763 
9764   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9765   // opcode number of the comparison.
9766   int CompareOpc;
9767   bool isDot;
9768   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9769     return SDValue();    // Don't custom lower most intrinsics.
9770 
9771   // If this is a non-dot comparison, make the VCMP node and we are done.
9772   if (!isDot) {
9773     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9774                               Op.getOperand(1), Op.getOperand(2),
9775                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9776     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9777   }
9778 
9779   // Create the PPCISD altivec 'dot' comparison node.
9780   SDValue Ops[] = {
9781     Op.getOperand(2),  // LHS
9782     Op.getOperand(3),  // RHS
9783     DAG.getConstant(CompareOpc, dl, MVT::i32)
9784   };
9785   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9786   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9787 
9788   // Now that we have the comparison, emit a copy from the CR to a GPR.
9789   // This is flagged to the above dot comparison.
9790   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9791                                 DAG.getRegister(PPC::CR6, MVT::i32),
9792                                 CompNode.getValue(1));
9793 
9794   // Unpack the result based on how the target uses it.
9795   unsigned BitNo;   // Bit # of CR6.
9796   bool InvertBit;   // Invert result?
9797   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9798   default:  // Can't happen, don't crash on invalid number though.
9799   case 0:   // Return the value of the EQ bit of CR6.
9800     BitNo = 0; InvertBit = false;
9801     break;
9802   case 1:   // Return the inverted value of the EQ bit of CR6.
9803     BitNo = 0; InvertBit = true;
9804     break;
9805   case 2:   // Return the value of the LT bit of CR6.
9806     BitNo = 2; InvertBit = false;
9807     break;
9808   case 3:   // Return the inverted value of the LT bit of CR6.
9809     BitNo = 2; InvertBit = true;
9810     break;
9811   }
9812 
9813   // Shift the bit into the low position.
9814   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9815                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9816   // Isolate the bit.
9817   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9818                       DAG.getConstant(1, dl, MVT::i32));
9819 
9820   // If we are supposed to, toggle the bit.
9821   if (InvertBit)
9822     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9823                         DAG.getConstant(1, dl, MVT::i32));
9824   return Flags;
9825 }
9826 
9827 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9828                                                SelectionDAG &DAG) const {
9829   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9830   // the beginning of the argument list.
9831   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9832   SDLoc DL(Op);
9833   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9834   case Intrinsic::ppc_cfence: {
9835     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9836     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9837     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9838                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9839                                                   Op.getOperand(ArgStart + 1)),
9840                                       Op.getOperand(0)),
9841                    0);
9842   }
9843   default:
9844     break;
9845   }
9846   return SDValue();
9847 }
9848 
9849 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9850   // Check for a DIV with the same operands as this REM.
9851   for (auto UI : Op.getOperand(1)->uses()) {
9852     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9853         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9854       if (UI->getOperand(0) == Op.getOperand(0) &&
9855           UI->getOperand(1) == Op.getOperand(1))
9856         return SDValue();
9857   }
9858   return Op;
9859 }
9860 
9861 // Lower scalar BSWAP64 to xxbrd.
9862 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9863   SDLoc dl(Op);
9864   // MTVSRDD
9865   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9866                    Op.getOperand(0));
9867   // XXBRD
9868   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
9869   // MFVSRD
9870   int VectorIndex = 0;
9871   if (Subtarget.isLittleEndian())
9872     VectorIndex = 1;
9873   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9874                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9875   return Op;
9876 }
9877 
9878 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9879 // compared to a value that is atomically loaded (atomic loads zero-extend).
9880 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9881                                                 SelectionDAG &DAG) const {
9882   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9883          "Expecting an atomic compare-and-swap here.");
9884   SDLoc dl(Op);
9885   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9886   EVT MemVT = AtomicNode->getMemoryVT();
9887   if (MemVT.getSizeInBits() >= 32)
9888     return Op;
9889 
9890   SDValue CmpOp = Op.getOperand(2);
9891   // If this is already correctly zero-extended, leave it alone.
9892   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9893   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9894     return Op;
9895 
9896   // Clear the high bits of the compare operand.
9897   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9898   SDValue NewCmpOp =
9899     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9900                 DAG.getConstant(MaskVal, dl, MVT::i32));
9901 
9902   // Replace the existing compare operand with the properly zero-extended one.
9903   SmallVector<SDValue, 4> Ops;
9904   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9905     Ops.push_back(AtomicNode->getOperand(i));
9906   Ops[2] = NewCmpOp;
9907   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9908   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9909   auto NodeTy =
9910     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9911   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9912 }
9913 
9914 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9915                                                  SelectionDAG &DAG) const {
9916   SDLoc dl(Op);
9917   // Create a stack slot that is 16-byte aligned.
9918   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9919   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9920   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9921   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9922 
9923   // Store the input value into Value#0 of the stack slot.
9924   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9925                                MachinePointerInfo());
9926   // Load it out.
9927   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9928 }
9929 
9930 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9931                                                   SelectionDAG &DAG) const {
9932   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9933          "Should only be called for ISD::INSERT_VECTOR_ELT");
9934 
9935   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9936   // We have legal lowering for constant indices but not for variable ones.
9937   if (!C)
9938     return SDValue();
9939 
9940   EVT VT = Op.getValueType();
9941   SDLoc dl(Op);
9942   SDValue V1 = Op.getOperand(0);
9943   SDValue V2 = Op.getOperand(1);
9944   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9945   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9946     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9947     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9948     unsigned InsertAtElement = C->getZExtValue();
9949     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9950     if (Subtarget.isLittleEndian()) {
9951       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9952     }
9953     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9954                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9955   }
9956   return Op;
9957 }
9958 
9959 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9960                                                    SelectionDAG &DAG) const {
9961   SDLoc dl(Op);
9962   SDNode *N = Op.getNode();
9963 
9964   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9965          "Unknown extract_vector_elt type");
9966 
9967   SDValue Value = N->getOperand(0);
9968 
9969   // The first part of this is like the store lowering except that we don't
9970   // need to track the chain.
9971 
9972   // The values are now known to be -1 (false) or 1 (true). To convert this
9973   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9974   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9975   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9976 
9977   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9978   // understand how to form the extending load.
9979   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9980 
9981   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9982 
9983   // Now convert to an integer and store.
9984   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9985     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9986     Value);
9987 
9988   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9989   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9990   MachinePointerInfo PtrInfo =
9991       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9992   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9993   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9994 
9995   SDValue StoreChain = DAG.getEntryNode();
9996   SDValue Ops[] = {StoreChain,
9997                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9998                    Value, FIdx};
9999   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10000 
10001   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10002     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10003 
10004   // Extract the value requested.
10005   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10006   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10007   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10008 
10009   SDValue IntVal =
10010       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10011 
10012   if (!Subtarget.useCRBits())
10013     return IntVal;
10014 
10015   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10016 }
10017 
10018 /// Lowering for QPX v4i1 loads
10019 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10020                                            SelectionDAG &DAG) const {
10021   SDLoc dl(Op);
10022   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10023   SDValue LoadChain = LN->getChain();
10024   SDValue BasePtr = LN->getBasePtr();
10025 
10026   if (Op.getValueType() == MVT::v4f64 ||
10027       Op.getValueType() == MVT::v4f32) {
10028     EVT MemVT = LN->getMemoryVT();
10029     unsigned Alignment = LN->getAlignment();
10030 
10031     // If this load is properly aligned, then it is legal.
10032     if (Alignment >= MemVT.getStoreSize())
10033       return Op;
10034 
10035     EVT ScalarVT = Op.getValueType().getScalarType(),
10036         ScalarMemVT = MemVT.getScalarType();
10037     unsigned Stride = ScalarMemVT.getStoreSize();
10038 
10039     SDValue Vals[4], LoadChains[4];
10040     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10041       SDValue Load;
10042       if (ScalarVT != ScalarMemVT)
10043         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10044                               BasePtr,
10045                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10046                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10047                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10048       else
10049         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10050                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10051                            MinAlign(Alignment, Idx * Stride),
10052                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10053 
10054       if (Idx == 0 && LN->isIndexed()) {
10055         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10056                "Unknown addressing mode on vector load");
10057         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10058                                   LN->getAddressingMode());
10059       }
10060 
10061       Vals[Idx] = Load;
10062       LoadChains[Idx] = Load.getValue(1);
10063 
10064       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10065                             DAG.getConstant(Stride, dl,
10066                                             BasePtr.getValueType()));
10067     }
10068 
10069     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10070     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10071 
10072     if (LN->isIndexed()) {
10073       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10074       return DAG.getMergeValues(RetOps, dl);
10075     }
10076 
10077     SDValue RetOps[] = { Value, TF };
10078     return DAG.getMergeValues(RetOps, dl);
10079   }
10080 
10081   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10082   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10083 
10084   // To lower v4i1 from a byte array, we load the byte elements of the
10085   // vector and then reuse the BUILD_VECTOR logic.
10086 
10087   SDValue VectElmts[4], VectElmtChains[4];
10088   for (unsigned i = 0; i < 4; ++i) {
10089     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10090     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10091 
10092     VectElmts[i] = DAG.getExtLoad(
10093         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10094         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10095         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10096     VectElmtChains[i] = VectElmts[i].getValue(1);
10097   }
10098 
10099   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10100   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10101 
10102   SDValue RVals[] = { Value, LoadChain };
10103   return DAG.getMergeValues(RVals, dl);
10104 }
10105 
10106 /// Lowering for QPX v4i1 stores
10107 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10108                                             SelectionDAG &DAG) const {
10109   SDLoc dl(Op);
10110   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10111   SDValue StoreChain = SN->getChain();
10112   SDValue BasePtr = SN->getBasePtr();
10113   SDValue Value = SN->getValue();
10114 
10115   if (Value.getValueType() == MVT::v4f64 ||
10116       Value.getValueType() == MVT::v4f32) {
10117     EVT MemVT = SN->getMemoryVT();
10118     unsigned Alignment = SN->getAlignment();
10119 
10120     // If this store is properly aligned, then it is legal.
10121     if (Alignment >= MemVT.getStoreSize())
10122       return Op;
10123 
10124     EVT ScalarVT = Value.getValueType().getScalarType(),
10125         ScalarMemVT = MemVT.getScalarType();
10126     unsigned Stride = ScalarMemVT.getStoreSize();
10127 
10128     SDValue Stores[4];
10129     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10130       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10131                                DAG.getVectorIdxConstant(Idx, dl));
10132       SDValue Store;
10133       if (ScalarVT != ScalarMemVT)
10134         Store =
10135             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10136                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10137                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10138                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10139       else
10140         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10141                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10142                              MinAlign(Alignment, Idx * Stride),
10143                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10144 
10145       if (Idx == 0 && SN->isIndexed()) {
10146         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10147                "Unknown addressing mode on vector store");
10148         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10149                                     SN->getAddressingMode());
10150       }
10151 
10152       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10153                             DAG.getConstant(Stride, dl,
10154                                             BasePtr.getValueType()));
10155       Stores[Idx] = Store;
10156     }
10157 
10158     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10159 
10160     if (SN->isIndexed()) {
10161       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10162       return DAG.getMergeValues(RetOps, dl);
10163     }
10164 
10165     return TF;
10166   }
10167 
10168   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10169   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10170 
10171   // The values are now known to be -1 (false) or 1 (true). To convert this
10172   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10173   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10174   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10175 
10176   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10177   // understand how to form the extending load.
10178   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10179 
10180   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10181 
10182   // Now convert to an integer and store.
10183   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10184     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10185     Value);
10186 
10187   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10188   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10189   MachinePointerInfo PtrInfo =
10190       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10191   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10192   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10193 
10194   SDValue Ops[] = {StoreChain,
10195                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10196                    Value, FIdx};
10197   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10198 
10199   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10200     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10201 
10202   // Move data into the byte array.
10203   SDValue Loads[4], LoadChains[4];
10204   for (unsigned i = 0; i < 4; ++i) {
10205     unsigned Offset = 4*i;
10206     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10207     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10208 
10209     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10210                            PtrInfo.getWithOffset(Offset));
10211     LoadChains[i] = Loads[i].getValue(1);
10212   }
10213 
10214   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10215 
10216   SDValue Stores[4];
10217   for (unsigned i = 0; i < 4; ++i) {
10218     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10219     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10220 
10221     Stores[i] = DAG.getTruncStore(
10222         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10223         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10224         SN->getAAInfo());
10225   }
10226 
10227   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10228 
10229   return StoreChain;
10230 }
10231 
10232 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10233   SDLoc dl(Op);
10234   if (Op.getValueType() == MVT::v4i32) {
10235     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10236 
10237     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10238     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10239 
10240     SDValue RHSSwap =   // = vrlw RHS, 16
10241       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10242 
10243     // Shrinkify inputs to v8i16.
10244     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10245     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10246     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10247 
10248     // Low parts multiplied together, generating 32-bit results (we ignore the
10249     // top parts).
10250     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10251                                         LHS, RHS, DAG, dl, MVT::v4i32);
10252 
10253     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10254                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10255     // Shift the high parts up 16 bits.
10256     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10257                               Neg16, DAG, dl);
10258     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10259   } else if (Op.getValueType() == MVT::v8i16) {
10260     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10261 
10262     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
10263 
10264     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
10265                             LHS, RHS, Zero, DAG, dl);
10266   } else if (Op.getValueType() == MVT::v16i8) {
10267     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10268     bool isLittleEndian = Subtarget.isLittleEndian();
10269 
10270     // Multiply the even 8-bit parts, producing 16-bit sums.
10271     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10272                                            LHS, RHS, DAG, dl, MVT::v8i16);
10273     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10274 
10275     // Multiply the odd 8-bit parts, producing 16-bit sums.
10276     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10277                                           LHS, RHS, DAG, dl, MVT::v8i16);
10278     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10279 
10280     // Merge the results together.  Because vmuleub and vmuloub are
10281     // instructions with a big-endian bias, we must reverse the
10282     // element numbering and reverse the meaning of "odd" and "even"
10283     // when generating little endian code.
10284     int Ops[16];
10285     for (unsigned i = 0; i != 8; ++i) {
10286       if (isLittleEndian) {
10287         Ops[i*2  ] = 2*i;
10288         Ops[i*2+1] = 2*i+16;
10289       } else {
10290         Ops[i*2  ] = 2*i+1;
10291         Ops[i*2+1] = 2*i+1+16;
10292       }
10293     }
10294     if (isLittleEndian)
10295       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10296     else
10297       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10298   } else {
10299     llvm_unreachable("Unknown mul to lower!");
10300   }
10301 }
10302 
10303 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10304 
10305   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10306 
10307   EVT VT = Op.getValueType();
10308   assert(VT.isVector() &&
10309          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10310   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10311           VT == MVT::v16i8) &&
10312          "Unexpected vector element type!");
10313   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10314          "Current subtarget doesn't support smax v2i64!");
10315 
10316   // For vector abs, it can be lowered to:
10317   // abs x
10318   // ==>
10319   // y = -x
10320   // smax(x, y)
10321 
10322   SDLoc dl(Op);
10323   SDValue X = Op.getOperand(0);
10324   SDValue Zero = DAG.getConstant(0, dl, VT);
10325   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10326 
10327   // SMAX patch https://reviews.llvm.org/D47332
10328   // hasn't landed yet, so use intrinsic first here.
10329   // TODO: Should use SMAX directly once SMAX patch landed
10330   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10331   if (VT == MVT::v2i64)
10332     BifID = Intrinsic::ppc_altivec_vmaxsd;
10333   else if (VT == MVT::v8i16)
10334     BifID = Intrinsic::ppc_altivec_vmaxsh;
10335   else if (VT == MVT::v16i8)
10336     BifID = Intrinsic::ppc_altivec_vmaxsb;
10337 
10338   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10339 }
10340 
10341 // Custom lowering for fpext vf32 to v2f64
10342 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10343 
10344   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10345          "Should only be called for ISD::FP_EXTEND");
10346 
10347   // We only want to custom lower an extend from v2f32 to v2f64.
10348   if (Op.getValueType() != MVT::v2f64 ||
10349       Op.getOperand(0).getValueType() != MVT::v2f32)
10350     return SDValue();
10351 
10352   SDLoc dl(Op);
10353   SDValue Op0 = Op.getOperand(0);
10354 
10355   switch (Op0.getOpcode()) {
10356   default:
10357     return SDValue();
10358   case ISD::EXTRACT_SUBVECTOR: {
10359     assert(Op0.getNumOperands() == 2 &&
10360            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10361            "Node should have 2 operands with second one being a constant!");
10362 
10363     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10364       return SDValue();
10365 
10366     // Custom lower is only done for high or low doubleword.
10367     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10368     if (Idx % 2 != 0)
10369       return SDValue();
10370 
10371     // Since input is v4f32, at this point Idx is either 0 or 2.
10372     // Shift to get the doubleword position we want.
10373     int DWord = Idx >> 1;
10374 
10375     // High and low word positions are different on little endian.
10376     if (Subtarget.isLittleEndian())
10377       DWord ^= 0x1;
10378 
10379     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10380                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10381   }
10382   case ISD::FADD:
10383   case ISD::FMUL:
10384   case ISD::FSUB: {
10385     SDValue NewLoad[2];
10386     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10387       // Ensure both input are loads.
10388       SDValue LdOp = Op0.getOperand(i);
10389       if (LdOp.getOpcode() != ISD::LOAD)
10390         return SDValue();
10391       // Generate new load node.
10392       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10393       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10394       NewLoad[i] = DAG.getMemIntrinsicNode(
10395           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10396           LD->getMemoryVT(), LD->getMemOperand());
10397     }
10398     SDValue NewOp =
10399         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10400                     NewLoad[1], Op0.getNode()->getFlags());
10401     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10402                        DAG.getConstant(0, dl, MVT::i32));
10403   }
10404   case ISD::LOAD: {
10405     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10406     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10407     SDValue NewLd = DAG.getMemIntrinsicNode(
10408         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10409         LD->getMemoryVT(), LD->getMemOperand());
10410     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10411                        DAG.getConstant(0, dl, MVT::i32));
10412   }
10413   }
10414   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10415 }
10416 
10417 /// LowerOperation - Provide custom lowering hooks for some operations.
10418 ///
10419 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10420   switch (Op.getOpcode()) {
10421   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10422   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10423   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10424   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10425   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10426   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10427   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10428   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10429   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10430 
10431   // Variable argument lowering.
10432   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10433   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10434   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10435 
10436   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10437   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10438   case ISD::GET_DYNAMIC_AREA_OFFSET:
10439     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10440 
10441   // Exception handling lowering.
10442   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10443   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10444   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10445 
10446   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10447   case ISD::STORE:              return LowerSTORE(Op, DAG);
10448   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10449   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10450   case ISD::FP_TO_UINT:
10451   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10452   case ISD::UINT_TO_FP:
10453   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10454   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10455 
10456   // Lower 64-bit shifts.
10457   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10458   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10459   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10460 
10461   // Vector-related lowering.
10462   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10463   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10464   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10465   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10466   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10467   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10468   case ISD::MUL:                return LowerMUL(Op, DAG);
10469   case ISD::ABS:                return LowerABS(Op, DAG);
10470   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10471 
10472   // For counter-based loop handling.
10473   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10474 
10475   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10476 
10477   // Frame & Return address.
10478   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10479   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10480 
10481   case ISD::INTRINSIC_VOID:
10482     return LowerINTRINSIC_VOID(Op, DAG);
10483   case ISD::SREM:
10484   case ISD::UREM:
10485     return LowerREM(Op, DAG);
10486   case ISD::BSWAP:
10487     return LowerBSWAP(Op, DAG);
10488   case ISD::ATOMIC_CMP_SWAP:
10489     return LowerATOMIC_CMP_SWAP(Op, DAG);
10490   }
10491 }
10492 
10493 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10494                                            SmallVectorImpl<SDValue>&Results,
10495                                            SelectionDAG &DAG) const {
10496   SDLoc dl(N);
10497   switch (N->getOpcode()) {
10498   default:
10499     llvm_unreachable("Do not know how to custom type legalize this operation!");
10500   case ISD::READCYCLECOUNTER: {
10501     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10502     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10503 
10504     Results.push_back(
10505         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10506     Results.push_back(RTB.getValue(2));
10507     break;
10508   }
10509   case ISD::INTRINSIC_W_CHAIN: {
10510     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10511         Intrinsic::loop_decrement)
10512       break;
10513 
10514     assert(N->getValueType(0) == MVT::i1 &&
10515            "Unexpected result type for CTR decrement intrinsic");
10516     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10517                                  N->getValueType(0));
10518     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10519     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10520                                  N->getOperand(1));
10521 
10522     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10523     Results.push_back(NewInt.getValue(1));
10524     break;
10525   }
10526   case ISD::VAARG: {
10527     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10528       return;
10529 
10530     EVT VT = N->getValueType(0);
10531 
10532     if (VT == MVT::i64) {
10533       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10534 
10535       Results.push_back(NewNode);
10536       Results.push_back(NewNode.getValue(1));
10537     }
10538     return;
10539   }
10540   case ISD::FP_TO_SINT:
10541   case ISD::FP_TO_UINT:
10542     // LowerFP_TO_INT() can only handle f32 and f64.
10543     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10544       return;
10545     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10546     return;
10547   case ISD::TRUNCATE: {
10548     EVT TrgVT = N->getValueType(0);
10549     EVT OpVT = N->getOperand(0).getValueType();
10550     if (TrgVT.isVector() &&
10551         isOperationCustom(N->getOpcode(), TrgVT) &&
10552         OpVT.getSizeInBits() <= 128 &&
10553         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10554       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10555     return;
10556   }
10557   case ISD::BITCAST:
10558     // Don't handle bitcast here.
10559     return;
10560   }
10561 }
10562 
10563 //===----------------------------------------------------------------------===//
10564 //  Other Lowering Code
10565 //===----------------------------------------------------------------------===//
10566 
10567 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10568   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10569   Function *Func = Intrinsic::getDeclaration(M, Id);
10570   return Builder.CreateCall(Func, {});
10571 }
10572 
10573 // The mappings for emitLeading/TrailingFence is taken from
10574 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10575 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10576                                                  Instruction *Inst,
10577                                                  AtomicOrdering Ord) const {
10578   if (Ord == AtomicOrdering::SequentiallyConsistent)
10579     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10580   if (isReleaseOrStronger(Ord))
10581     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10582   return nullptr;
10583 }
10584 
10585 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10586                                                   Instruction *Inst,
10587                                                   AtomicOrdering Ord) const {
10588   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10589     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10590     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10591     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10592     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10593       return Builder.CreateCall(
10594           Intrinsic::getDeclaration(
10595               Builder.GetInsertBlock()->getParent()->getParent(),
10596               Intrinsic::ppc_cfence, {Inst->getType()}),
10597           {Inst});
10598     // FIXME: Can use isync for rmw operation.
10599     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10600   }
10601   return nullptr;
10602 }
10603 
10604 MachineBasicBlock *
10605 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10606                                     unsigned AtomicSize,
10607                                     unsigned BinOpcode,
10608                                     unsigned CmpOpcode,
10609                                     unsigned CmpPred) const {
10610   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10611   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10612 
10613   auto LoadMnemonic = PPC::LDARX;
10614   auto StoreMnemonic = PPC::STDCX;
10615   switch (AtomicSize) {
10616   default:
10617     llvm_unreachable("Unexpected size of atomic entity");
10618   case 1:
10619     LoadMnemonic = PPC::LBARX;
10620     StoreMnemonic = PPC::STBCX;
10621     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10622     break;
10623   case 2:
10624     LoadMnemonic = PPC::LHARX;
10625     StoreMnemonic = PPC::STHCX;
10626     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10627     break;
10628   case 4:
10629     LoadMnemonic = PPC::LWARX;
10630     StoreMnemonic = PPC::STWCX;
10631     break;
10632   case 8:
10633     LoadMnemonic = PPC::LDARX;
10634     StoreMnemonic = PPC::STDCX;
10635     break;
10636   }
10637 
10638   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10639   MachineFunction *F = BB->getParent();
10640   MachineFunction::iterator It = ++BB->getIterator();
10641 
10642   Register dest = MI.getOperand(0).getReg();
10643   Register ptrA = MI.getOperand(1).getReg();
10644   Register ptrB = MI.getOperand(2).getReg();
10645   Register incr = MI.getOperand(3).getReg();
10646   DebugLoc dl = MI.getDebugLoc();
10647 
10648   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10649   MachineBasicBlock *loop2MBB =
10650     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10651   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10652   F->insert(It, loopMBB);
10653   if (CmpOpcode)
10654     F->insert(It, loop2MBB);
10655   F->insert(It, exitMBB);
10656   exitMBB->splice(exitMBB->begin(), BB,
10657                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10658   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10659 
10660   MachineRegisterInfo &RegInfo = F->getRegInfo();
10661   Register TmpReg = (!BinOpcode) ? incr :
10662     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10663                                            : &PPC::GPRCRegClass);
10664 
10665   //  thisMBB:
10666   //   ...
10667   //   fallthrough --> loopMBB
10668   BB->addSuccessor(loopMBB);
10669 
10670   //  loopMBB:
10671   //   l[wd]arx dest, ptr
10672   //   add r0, dest, incr
10673   //   st[wd]cx. r0, ptr
10674   //   bne- loopMBB
10675   //   fallthrough --> exitMBB
10676 
10677   // For max/min...
10678   //  loopMBB:
10679   //   l[wd]arx dest, ptr
10680   //   cmpl?[wd] incr, dest
10681   //   bgt exitMBB
10682   //  loop2MBB:
10683   //   st[wd]cx. dest, ptr
10684   //   bne- loopMBB
10685   //   fallthrough --> exitMBB
10686 
10687   BB = loopMBB;
10688   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10689     .addReg(ptrA).addReg(ptrB);
10690   if (BinOpcode)
10691     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10692   if (CmpOpcode) {
10693     // Signed comparisons of byte or halfword values must be sign-extended.
10694     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10695       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10696       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10697               ExtReg).addReg(dest);
10698       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10699         .addReg(incr).addReg(ExtReg);
10700     } else
10701       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10702         .addReg(incr).addReg(dest);
10703 
10704     BuildMI(BB, dl, TII->get(PPC::BCC))
10705       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10706     BB->addSuccessor(loop2MBB);
10707     BB->addSuccessor(exitMBB);
10708     BB = loop2MBB;
10709   }
10710   BuildMI(BB, dl, TII->get(StoreMnemonic))
10711     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10712   BuildMI(BB, dl, TII->get(PPC::BCC))
10713     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10714   BB->addSuccessor(loopMBB);
10715   BB->addSuccessor(exitMBB);
10716 
10717   //  exitMBB:
10718   //   ...
10719   BB = exitMBB;
10720   return BB;
10721 }
10722 
10723 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10724     MachineInstr &MI, MachineBasicBlock *BB,
10725     bool is8bit, // operation
10726     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10727   // If we support part-word atomic mnemonics, just use them
10728   if (Subtarget.hasPartwordAtomics())
10729     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10730                             CmpPred);
10731 
10732   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10733   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10734   // In 64 bit mode we have to use 64 bits for addresses, even though the
10735   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10736   // registers without caring whether they're 32 or 64, but here we're
10737   // doing actual arithmetic on the addresses.
10738   bool is64bit = Subtarget.isPPC64();
10739   bool isLittleEndian = Subtarget.isLittleEndian();
10740   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10741 
10742   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10743   MachineFunction *F = BB->getParent();
10744   MachineFunction::iterator It = ++BB->getIterator();
10745 
10746   Register dest = MI.getOperand(0).getReg();
10747   Register ptrA = MI.getOperand(1).getReg();
10748   Register ptrB = MI.getOperand(2).getReg();
10749   Register incr = MI.getOperand(3).getReg();
10750   DebugLoc dl = MI.getDebugLoc();
10751 
10752   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10753   MachineBasicBlock *loop2MBB =
10754       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10755   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10756   F->insert(It, loopMBB);
10757   if (CmpOpcode)
10758     F->insert(It, loop2MBB);
10759   F->insert(It, exitMBB);
10760   exitMBB->splice(exitMBB->begin(), BB,
10761                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10762   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10763 
10764   MachineRegisterInfo &RegInfo = F->getRegInfo();
10765   const TargetRegisterClass *RC =
10766       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10767   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10768 
10769   Register PtrReg = RegInfo.createVirtualRegister(RC);
10770   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10771   Register ShiftReg =
10772       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10773   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10774   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10775   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10776   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10777   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10778   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10779   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10780   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10781   Register Ptr1Reg;
10782   Register TmpReg =
10783       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10784 
10785   //  thisMBB:
10786   //   ...
10787   //   fallthrough --> loopMBB
10788   BB->addSuccessor(loopMBB);
10789 
10790   // The 4-byte load must be aligned, while a char or short may be
10791   // anywhere in the word.  Hence all this nasty bookkeeping code.
10792   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10793   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10794   //   xori shift, shift1, 24 [16]
10795   //   rlwinm ptr, ptr1, 0, 0, 29
10796   //   slw incr2, incr, shift
10797   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10798   //   slw mask, mask2, shift
10799   //  loopMBB:
10800   //   lwarx tmpDest, ptr
10801   //   add tmp, tmpDest, incr2
10802   //   andc tmp2, tmpDest, mask
10803   //   and tmp3, tmp, mask
10804   //   or tmp4, tmp3, tmp2
10805   //   stwcx. tmp4, ptr
10806   //   bne- loopMBB
10807   //   fallthrough --> exitMBB
10808   //   srw dest, tmpDest, shift
10809   if (ptrA != ZeroReg) {
10810     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10811     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10812         .addReg(ptrA)
10813         .addReg(ptrB);
10814   } else {
10815     Ptr1Reg = ptrB;
10816   }
10817   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10818   // mode.
10819   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10820       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10821       .addImm(3)
10822       .addImm(27)
10823       .addImm(is8bit ? 28 : 27);
10824   if (!isLittleEndian)
10825     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10826         .addReg(Shift1Reg)
10827         .addImm(is8bit ? 24 : 16);
10828   if (is64bit)
10829     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10830         .addReg(Ptr1Reg)
10831         .addImm(0)
10832         .addImm(61);
10833   else
10834     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10835         .addReg(Ptr1Reg)
10836         .addImm(0)
10837         .addImm(0)
10838         .addImm(29);
10839   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10840   if (is8bit)
10841     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10842   else {
10843     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10844     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10845         .addReg(Mask3Reg)
10846         .addImm(65535);
10847   }
10848   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10849       .addReg(Mask2Reg)
10850       .addReg(ShiftReg);
10851 
10852   BB = loopMBB;
10853   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10854       .addReg(ZeroReg)
10855       .addReg(PtrReg);
10856   if (BinOpcode)
10857     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10858         .addReg(Incr2Reg)
10859         .addReg(TmpDestReg);
10860   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10861       .addReg(TmpDestReg)
10862       .addReg(MaskReg);
10863   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10864   if (CmpOpcode) {
10865     // For unsigned comparisons, we can directly compare the shifted values.
10866     // For signed comparisons we shift and sign extend.
10867     Register SReg = RegInfo.createVirtualRegister(GPRC);
10868     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10869         .addReg(TmpDestReg)
10870         .addReg(MaskReg);
10871     unsigned ValueReg = SReg;
10872     unsigned CmpReg = Incr2Reg;
10873     if (CmpOpcode == PPC::CMPW) {
10874       ValueReg = RegInfo.createVirtualRegister(GPRC);
10875       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10876           .addReg(SReg)
10877           .addReg(ShiftReg);
10878       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10879       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10880           .addReg(ValueReg);
10881       ValueReg = ValueSReg;
10882       CmpReg = incr;
10883     }
10884     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10885         .addReg(CmpReg)
10886         .addReg(ValueReg);
10887     BuildMI(BB, dl, TII->get(PPC::BCC))
10888         .addImm(CmpPred)
10889         .addReg(PPC::CR0)
10890         .addMBB(exitMBB);
10891     BB->addSuccessor(loop2MBB);
10892     BB->addSuccessor(exitMBB);
10893     BB = loop2MBB;
10894   }
10895   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10896   BuildMI(BB, dl, TII->get(PPC::STWCX))
10897       .addReg(Tmp4Reg)
10898       .addReg(ZeroReg)
10899       .addReg(PtrReg);
10900   BuildMI(BB, dl, TII->get(PPC::BCC))
10901       .addImm(PPC::PRED_NE)
10902       .addReg(PPC::CR0)
10903       .addMBB(loopMBB);
10904   BB->addSuccessor(loopMBB);
10905   BB->addSuccessor(exitMBB);
10906 
10907   //  exitMBB:
10908   //   ...
10909   BB = exitMBB;
10910   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10911       .addReg(TmpDestReg)
10912       .addReg(ShiftReg);
10913   return BB;
10914 }
10915 
10916 llvm::MachineBasicBlock *
10917 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10918                                     MachineBasicBlock *MBB) const {
10919   DebugLoc DL = MI.getDebugLoc();
10920   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10921   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10922 
10923   MachineFunction *MF = MBB->getParent();
10924   MachineRegisterInfo &MRI = MF->getRegInfo();
10925 
10926   const BasicBlock *BB = MBB->getBasicBlock();
10927   MachineFunction::iterator I = ++MBB->getIterator();
10928 
10929   Register DstReg = MI.getOperand(0).getReg();
10930   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10931   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10932   Register mainDstReg = MRI.createVirtualRegister(RC);
10933   Register restoreDstReg = MRI.createVirtualRegister(RC);
10934 
10935   MVT PVT = getPointerTy(MF->getDataLayout());
10936   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10937          "Invalid Pointer Size!");
10938   // For v = setjmp(buf), we generate
10939   //
10940   // thisMBB:
10941   //  SjLjSetup mainMBB
10942   //  bl mainMBB
10943   //  v_restore = 1
10944   //  b sinkMBB
10945   //
10946   // mainMBB:
10947   //  buf[LabelOffset] = LR
10948   //  v_main = 0
10949   //
10950   // sinkMBB:
10951   //  v = phi(main, restore)
10952   //
10953 
10954   MachineBasicBlock *thisMBB = MBB;
10955   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10956   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10957   MF->insert(I, mainMBB);
10958   MF->insert(I, sinkMBB);
10959 
10960   MachineInstrBuilder MIB;
10961 
10962   // Transfer the remainder of BB and its successor edges to sinkMBB.
10963   sinkMBB->splice(sinkMBB->begin(), MBB,
10964                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10965   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10966 
10967   // Note that the structure of the jmp_buf used here is not compatible
10968   // with that used by libc, and is not designed to be. Specifically, it
10969   // stores only those 'reserved' registers that LLVM does not otherwise
10970   // understand how to spill. Also, by convention, by the time this
10971   // intrinsic is called, Clang has already stored the frame address in the
10972   // first slot of the buffer and stack address in the third. Following the
10973   // X86 target code, we'll store the jump address in the second slot. We also
10974   // need to save the TOC pointer (R2) to handle jumps between shared
10975   // libraries, and that will be stored in the fourth slot. The thread
10976   // identifier (R13) is not affected.
10977 
10978   // thisMBB:
10979   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10980   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10981   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10982 
10983   // Prepare IP either in reg.
10984   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10985   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10986   Register BufReg = MI.getOperand(1).getReg();
10987 
10988   if (Subtarget.is64BitELFABI()) {
10989     setUsesTOCBasePtr(*MBB->getParent());
10990     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10991               .addReg(PPC::X2)
10992               .addImm(TOCOffset)
10993               .addReg(BufReg)
10994               .cloneMemRefs(MI);
10995   }
10996 
10997   // Naked functions never have a base pointer, and so we use r1. For all
10998   // other functions, this decision must be delayed until during PEI.
10999   unsigned BaseReg;
11000   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11001     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11002   else
11003     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11004 
11005   MIB = BuildMI(*thisMBB, MI, DL,
11006                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11007             .addReg(BaseReg)
11008             .addImm(BPOffset)
11009             .addReg(BufReg)
11010             .cloneMemRefs(MI);
11011 
11012   // Setup
11013   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11014   MIB.addRegMask(TRI->getNoPreservedMask());
11015 
11016   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11017 
11018   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11019           .addMBB(mainMBB);
11020   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11021 
11022   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11023   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11024 
11025   // mainMBB:
11026   //  mainDstReg = 0
11027   MIB =
11028       BuildMI(mainMBB, DL,
11029               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11030 
11031   // Store IP
11032   if (Subtarget.isPPC64()) {
11033     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11034             .addReg(LabelReg)
11035             .addImm(LabelOffset)
11036             .addReg(BufReg);
11037   } else {
11038     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11039             .addReg(LabelReg)
11040             .addImm(LabelOffset)
11041             .addReg(BufReg);
11042   }
11043   MIB.cloneMemRefs(MI);
11044 
11045   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11046   mainMBB->addSuccessor(sinkMBB);
11047 
11048   // sinkMBB:
11049   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11050           TII->get(PPC::PHI), DstReg)
11051     .addReg(mainDstReg).addMBB(mainMBB)
11052     .addReg(restoreDstReg).addMBB(thisMBB);
11053 
11054   MI.eraseFromParent();
11055   return sinkMBB;
11056 }
11057 
11058 MachineBasicBlock *
11059 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11060                                      MachineBasicBlock *MBB) const {
11061   DebugLoc DL = MI.getDebugLoc();
11062   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11063 
11064   MachineFunction *MF = MBB->getParent();
11065   MachineRegisterInfo &MRI = MF->getRegInfo();
11066 
11067   MVT PVT = getPointerTy(MF->getDataLayout());
11068   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11069          "Invalid Pointer Size!");
11070 
11071   const TargetRegisterClass *RC =
11072     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11073   Register Tmp = MRI.createVirtualRegister(RC);
11074   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11075   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11076   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11077   unsigned BP =
11078       (PVT == MVT::i64)
11079           ? PPC::X30
11080           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11081                                                               : PPC::R30);
11082 
11083   MachineInstrBuilder MIB;
11084 
11085   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11086   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11087   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11088   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11089 
11090   Register BufReg = MI.getOperand(0).getReg();
11091 
11092   // Reload FP (the jumped-to function may not have had a
11093   // frame pointer, and if so, then its r31 will be restored
11094   // as necessary).
11095   if (PVT == MVT::i64) {
11096     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11097             .addImm(0)
11098             .addReg(BufReg);
11099   } else {
11100     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11101             .addImm(0)
11102             .addReg(BufReg);
11103   }
11104   MIB.cloneMemRefs(MI);
11105 
11106   // Reload IP
11107   if (PVT == MVT::i64) {
11108     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11109             .addImm(LabelOffset)
11110             .addReg(BufReg);
11111   } else {
11112     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11113             .addImm(LabelOffset)
11114             .addReg(BufReg);
11115   }
11116   MIB.cloneMemRefs(MI);
11117 
11118   // Reload SP
11119   if (PVT == MVT::i64) {
11120     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11121             .addImm(SPOffset)
11122             .addReg(BufReg);
11123   } else {
11124     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11125             .addImm(SPOffset)
11126             .addReg(BufReg);
11127   }
11128   MIB.cloneMemRefs(MI);
11129 
11130   // Reload BP
11131   if (PVT == MVT::i64) {
11132     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11133             .addImm(BPOffset)
11134             .addReg(BufReg);
11135   } else {
11136     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11137             .addImm(BPOffset)
11138             .addReg(BufReg);
11139   }
11140   MIB.cloneMemRefs(MI);
11141 
11142   // Reload TOC
11143   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11144     setUsesTOCBasePtr(*MBB->getParent());
11145     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11146               .addImm(TOCOffset)
11147               .addReg(BufReg)
11148               .cloneMemRefs(MI);
11149   }
11150 
11151   // Jump
11152   BuildMI(*MBB, MI, DL,
11153           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11154   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11155 
11156   MI.eraseFromParent();
11157   return MBB;
11158 }
11159 
11160 MachineBasicBlock *
11161 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11162                                                MachineBasicBlock *BB) const {
11163   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11164       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11165     if (Subtarget.is64BitELFABI() &&
11166         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11167       // Call lowering should have added an r2 operand to indicate a dependence
11168       // on the TOC base pointer value. It can't however, because there is no
11169       // way to mark the dependence as implicit there, and so the stackmap code
11170       // will confuse it with a regular operand. Instead, add the dependence
11171       // here.
11172       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11173     }
11174 
11175     return emitPatchPoint(MI, BB);
11176   }
11177 
11178   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11179       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11180     return emitEHSjLjSetJmp(MI, BB);
11181   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11182              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11183     return emitEHSjLjLongJmp(MI, BB);
11184   }
11185 
11186   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11187 
11188   // To "insert" these instructions we actually have to insert their
11189   // control-flow patterns.
11190   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11191   MachineFunction::iterator It = ++BB->getIterator();
11192 
11193   MachineFunction *F = BB->getParent();
11194 
11195   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11196       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11197       MI.getOpcode() == PPC::SELECT_I8) {
11198     SmallVector<MachineOperand, 2> Cond;
11199     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11200         MI.getOpcode() == PPC::SELECT_CC_I8)
11201       Cond.push_back(MI.getOperand(4));
11202     else
11203       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11204     Cond.push_back(MI.getOperand(1));
11205 
11206     DebugLoc dl = MI.getDebugLoc();
11207     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11208                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11209   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11210              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11211              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11212              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11213              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11214              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11215              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11216              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11217              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11218              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11219              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11220              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11221              MI.getOpcode() == PPC::SELECT_F4 ||
11222              MI.getOpcode() == PPC::SELECT_F8 ||
11223              MI.getOpcode() == PPC::SELECT_F16 ||
11224              MI.getOpcode() == PPC::SELECT_QFRC ||
11225              MI.getOpcode() == PPC::SELECT_QSRC ||
11226              MI.getOpcode() == PPC::SELECT_QBRC ||
11227              MI.getOpcode() == PPC::SELECT_SPE ||
11228              MI.getOpcode() == PPC::SELECT_SPE4 ||
11229              MI.getOpcode() == PPC::SELECT_VRRC ||
11230              MI.getOpcode() == PPC::SELECT_VSFRC ||
11231              MI.getOpcode() == PPC::SELECT_VSSRC ||
11232              MI.getOpcode() == PPC::SELECT_VSRC) {
11233     // The incoming instruction knows the destination vreg to set, the
11234     // condition code register to branch on, the true/false values to
11235     // select between, and a branch opcode to use.
11236 
11237     //  thisMBB:
11238     //  ...
11239     //   TrueVal = ...
11240     //   cmpTY ccX, r1, r2
11241     //   bCC copy1MBB
11242     //   fallthrough --> copy0MBB
11243     MachineBasicBlock *thisMBB = BB;
11244     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11245     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11246     DebugLoc dl = MI.getDebugLoc();
11247     F->insert(It, copy0MBB);
11248     F->insert(It, sinkMBB);
11249 
11250     // Transfer the remainder of BB and its successor edges to sinkMBB.
11251     sinkMBB->splice(sinkMBB->begin(), BB,
11252                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11253     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11254 
11255     // Next, add the true and fallthrough blocks as its successors.
11256     BB->addSuccessor(copy0MBB);
11257     BB->addSuccessor(sinkMBB);
11258 
11259     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11260         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11261         MI.getOpcode() == PPC::SELECT_F16 ||
11262         MI.getOpcode() == PPC::SELECT_SPE4 ||
11263         MI.getOpcode() == PPC::SELECT_SPE ||
11264         MI.getOpcode() == PPC::SELECT_QFRC ||
11265         MI.getOpcode() == PPC::SELECT_QSRC ||
11266         MI.getOpcode() == PPC::SELECT_QBRC ||
11267         MI.getOpcode() == PPC::SELECT_VRRC ||
11268         MI.getOpcode() == PPC::SELECT_VSFRC ||
11269         MI.getOpcode() == PPC::SELECT_VSSRC ||
11270         MI.getOpcode() == PPC::SELECT_VSRC) {
11271       BuildMI(BB, dl, TII->get(PPC::BC))
11272           .addReg(MI.getOperand(1).getReg())
11273           .addMBB(sinkMBB);
11274     } else {
11275       unsigned SelectPred = MI.getOperand(4).getImm();
11276       BuildMI(BB, dl, TII->get(PPC::BCC))
11277           .addImm(SelectPred)
11278           .addReg(MI.getOperand(1).getReg())
11279           .addMBB(sinkMBB);
11280     }
11281 
11282     //  copy0MBB:
11283     //   %FalseValue = ...
11284     //   # fallthrough to sinkMBB
11285     BB = copy0MBB;
11286 
11287     // Update machine-CFG edges
11288     BB->addSuccessor(sinkMBB);
11289 
11290     //  sinkMBB:
11291     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11292     //  ...
11293     BB = sinkMBB;
11294     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11295         .addReg(MI.getOperand(3).getReg())
11296         .addMBB(copy0MBB)
11297         .addReg(MI.getOperand(2).getReg())
11298         .addMBB(thisMBB);
11299   } else if (MI.getOpcode() == PPC::ReadTB) {
11300     // To read the 64-bit time-base register on a 32-bit target, we read the
11301     // two halves. Should the counter have wrapped while it was being read, we
11302     // need to try again.
11303     // ...
11304     // readLoop:
11305     // mfspr Rx,TBU # load from TBU
11306     // mfspr Ry,TB  # load from TB
11307     // mfspr Rz,TBU # load from TBU
11308     // cmpw crX,Rx,Rz # check if 'old'='new'
11309     // bne readLoop   # branch if they're not equal
11310     // ...
11311 
11312     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11313     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11314     DebugLoc dl = MI.getDebugLoc();
11315     F->insert(It, readMBB);
11316     F->insert(It, sinkMBB);
11317 
11318     // Transfer the remainder of BB and its successor edges to sinkMBB.
11319     sinkMBB->splice(sinkMBB->begin(), BB,
11320                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11321     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11322 
11323     BB->addSuccessor(readMBB);
11324     BB = readMBB;
11325 
11326     MachineRegisterInfo &RegInfo = F->getRegInfo();
11327     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11328     Register LoReg = MI.getOperand(0).getReg();
11329     Register HiReg = MI.getOperand(1).getReg();
11330 
11331     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11332     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11333     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11334 
11335     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11336 
11337     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11338         .addReg(HiReg)
11339         .addReg(ReadAgainReg);
11340     BuildMI(BB, dl, TII->get(PPC::BCC))
11341         .addImm(PPC::PRED_NE)
11342         .addReg(CmpReg)
11343         .addMBB(readMBB);
11344 
11345     BB->addSuccessor(readMBB);
11346     BB->addSuccessor(sinkMBB);
11347   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11348     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11349   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11350     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11351   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11352     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11353   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11354     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11355 
11356   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11357     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11358   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11359     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11360   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11361     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11362   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11363     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11364 
11365   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11366     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11367   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11368     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11369   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11370     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11371   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11372     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11373 
11374   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11375     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11376   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11377     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11378   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11379     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11380   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11381     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11382 
11383   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11384     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11385   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11386     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11387   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11388     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11389   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11390     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11391 
11392   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11393     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11394   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11395     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11396   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11397     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11398   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11399     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11400 
11401   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11402     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11403   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11404     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11405   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11406     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11407   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11408     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11409 
11410   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11411     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11412   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11413     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11414   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11415     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11416   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11417     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11418 
11419   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11420     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11421   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11422     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11423   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11424     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11425   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11426     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11427 
11428   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11429     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11430   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11431     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11432   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11433     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11434   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11435     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11436 
11437   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11438     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11439   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11440     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11441   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11442     BB = EmitAtomicBinary(MI, BB, 4, 0);
11443   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11444     BB = EmitAtomicBinary(MI, BB, 8, 0);
11445   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11446            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11447            (Subtarget.hasPartwordAtomics() &&
11448             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11449            (Subtarget.hasPartwordAtomics() &&
11450             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11451     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11452 
11453     auto LoadMnemonic = PPC::LDARX;
11454     auto StoreMnemonic = PPC::STDCX;
11455     switch (MI.getOpcode()) {
11456     default:
11457       llvm_unreachable("Compare and swap of unknown size");
11458     case PPC::ATOMIC_CMP_SWAP_I8:
11459       LoadMnemonic = PPC::LBARX;
11460       StoreMnemonic = PPC::STBCX;
11461       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11462       break;
11463     case PPC::ATOMIC_CMP_SWAP_I16:
11464       LoadMnemonic = PPC::LHARX;
11465       StoreMnemonic = PPC::STHCX;
11466       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11467       break;
11468     case PPC::ATOMIC_CMP_SWAP_I32:
11469       LoadMnemonic = PPC::LWARX;
11470       StoreMnemonic = PPC::STWCX;
11471       break;
11472     case PPC::ATOMIC_CMP_SWAP_I64:
11473       LoadMnemonic = PPC::LDARX;
11474       StoreMnemonic = PPC::STDCX;
11475       break;
11476     }
11477     Register dest = MI.getOperand(0).getReg();
11478     Register ptrA = MI.getOperand(1).getReg();
11479     Register ptrB = MI.getOperand(2).getReg();
11480     Register oldval = MI.getOperand(3).getReg();
11481     Register newval = MI.getOperand(4).getReg();
11482     DebugLoc dl = MI.getDebugLoc();
11483 
11484     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11485     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11486     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11487     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11488     F->insert(It, loop1MBB);
11489     F->insert(It, loop2MBB);
11490     F->insert(It, midMBB);
11491     F->insert(It, exitMBB);
11492     exitMBB->splice(exitMBB->begin(), BB,
11493                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11494     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11495 
11496     //  thisMBB:
11497     //   ...
11498     //   fallthrough --> loopMBB
11499     BB->addSuccessor(loop1MBB);
11500 
11501     // loop1MBB:
11502     //   l[bhwd]arx dest, ptr
11503     //   cmp[wd] dest, oldval
11504     //   bne- midMBB
11505     // loop2MBB:
11506     //   st[bhwd]cx. newval, ptr
11507     //   bne- loopMBB
11508     //   b exitBB
11509     // midMBB:
11510     //   st[bhwd]cx. dest, ptr
11511     // exitBB:
11512     BB = loop1MBB;
11513     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11514     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11515         .addReg(oldval)
11516         .addReg(dest);
11517     BuildMI(BB, dl, TII->get(PPC::BCC))
11518         .addImm(PPC::PRED_NE)
11519         .addReg(PPC::CR0)
11520         .addMBB(midMBB);
11521     BB->addSuccessor(loop2MBB);
11522     BB->addSuccessor(midMBB);
11523 
11524     BB = loop2MBB;
11525     BuildMI(BB, dl, TII->get(StoreMnemonic))
11526         .addReg(newval)
11527         .addReg(ptrA)
11528         .addReg(ptrB);
11529     BuildMI(BB, dl, TII->get(PPC::BCC))
11530         .addImm(PPC::PRED_NE)
11531         .addReg(PPC::CR0)
11532         .addMBB(loop1MBB);
11533     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11534     BB->addSuccessor(loop1MBB);
11535     BB->addSuccessor(exitMBB);
11536 
11537     BB = midMBB;
11538     BuildMI(BB, dl, TII->get(StoreMnemonic))
11539         .addReg(dest)
11540         .addReg(ptrA)
11541         .addReg(ptrB);
11542     BB->addSuccessor(exitMBB);
11543 
11544     //  exitMBB:
11545     //   ...
11546     BB = exitMBB;
11547   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11548              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11549     // We must use 64-bit registers for addresses when targeting 64-bit,
11550     // since we're actually doing arithmetic on them.  Other registers
11551     // can be 32-bit.
11552     bool is64bit = Subtarget.isPPC64();
11553     bool isLittleEndian = Subtarget.isLittleEndian();
11554     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11555 
11556     Register dest = MI.getOperand(0).getReg();
11557     Register ptrA = MI.getOperand(1).getReg();
11558     Register ptrB = MI.getOperand(2).getReg();
11559     Register oldval = MI.getOperand(3).getReg();
11560     Register newval = MI.getOperand(4).getReg();
11561     DebugLoc dl = MI.getDebugLoc();
11562 
11563     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11564     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11565     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11566     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11567     F->insert(It, loop1MBB);
11568     F->insert(It, loop2MBB);
11569     F->insert(It, midMBB);
11570     F->insert(It, exitMBB);
11571     exitMBB->splice(exitMBB->begin(), BB,
11572                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11573     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11574 
11575     MachineRegisterInfo &RegInfo = F->getRegInfo();
11576     const TargetRegisterClass *RC =
11577         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11578     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11579 
11580     Register PtrReg = RegInfo.createVirtualRegister(RC);
11581     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11582     Register ShiftReg =
11583         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11584     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11585     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11586     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11587     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11588     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11589     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11590     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11591     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11592     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11593     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11594     Register Ptr1Reg;
11595     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11596     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11597     //  thisMBB:
11598     //   ...
11599     //   fallthrough --> loopMBB
11600     BB->addSuccessor(loop1MBB);
11601 
11602     // The 4-byte load must be aligned, while a char or short may be
11603     // anywhere in the word.  Hence all this nasty bookkeeping code.
11604     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11605     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11606     //   xori shift, shift1, 24 [16]
11607     //   rlwinm ptr, ptr1, 0, 0, 29
11608     //   slw newval2, newval, shift
11609     //   slw oldval2, oldval,shift
11610     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11611     //   slw mask, mask2, shift
11612     //   and newval3, newval2, mask
11613     //   and oldval3, oldval2, mask
11614     // loop1MBB:
11615     //   lwarx tmpDest, ptr
11616     //   and tmp, tmpDest, mask
11617     //   cmpw tmp, oldval3
11618     //   bne- midMBB
11619     // loop2MBB:
11620     //   andc tmp2, tmpDest, mask
11621     //   or tmp4, tmp2, newval3
11622     //   stwcx. tmp4, ptr
11623     //   bne- loop1MBB
11624     //   b exitBB
11625     // midMBB:
11626     //   stwcx. tmpDest, ptr
11627     // exitBB:
11628     //   srw dest, tmpDest, shift
11629     if (ptrA != ZeroReg) {
11630       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11631       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11632           .addReg(ptrA)
11633           .addReg(ptrB);
11634     } else {
11635       Ptr1Reg = ptrB;
11636     }
11637 
11638     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11639     // mode.
11640     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11641         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11642         .addImm(3)
11643         .addImm(27)
11644         .addImm(is8bit ? 28 : 27);
11645     if (!isLittleEndian)
11646       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11647           .addReg(Shift1Reg)
11648           .addImm(is8bit ? 24 : 16);
11649     if (is64bit)
11650       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11651           .addReg(Ptr1Reg)
11652           .addImm(0)
11653           .addImm(61);
11654     else
11655       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11656           .addReg(Ptr1Reg)
11657           .addImm(0)
11658           .addImm(0)
11659           .addImm(29);
11660     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11661         .addReg(newval)
11662         .addReg(ShiftReg);
11663     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11664         .addReg(oldval)
11665         .addReg(ShiftReg);
11666     if (is8bit)
11667       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11668     else {
11669       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11670       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11671           .addReg(Mask3Reg)
11672           .addImm(65535);
11673     }
11674     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11675         .addReg(Mask2Reg)
11676         .addReg(ShiftReg);
11677     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11678         .addReg(NewVal2Reg)
11679         .addReg(MaskReg);
11680     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11681         .addReg(OldVal2Reg)
11682         .addReg(MaskReg);
11683 
11684     BB = loop1MBB;
11685     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11686         .addReg(ZeroReg)
11687         .addReg(PtrReg);
11688     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11689         .addReg(TmpDestReg)
11690         .addReg(MaskReg);
11691     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11692         .addReg(TmpReg)
11693         .addReg(OldVal3Reg);
11694     BuildMI(BB, dl, TII->get(PPC::BCC))
11695         .addImm(PPC::PRED_NE)
11696         .addReg(PPC::CR0)
11697         .addMBB(midMBB);
11698     BB->addSuccessor(loop2MBB);
11699     BB->addSuccessor(midMBB);
11700 
11701     BB = loop2MBB;
11702     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11703         .addReg(TmpDestReg)
11704         .addReg(MaskReg);
11705     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11706         .addReg(Tmp2Reg)
11707         .addReg(NewVal3Reg);
11708     BuildMI(BB, dl, TII->get(PPC::STWCX))
11709         .addReg(Tmp4Reg)
11710         .addReg(ZeroReg)
11711         .addReg(PtrReg);
11712     BuildMI(BB, dl, TII->get(PPC::BCC))
11713         .addImm(PPC::PRED_NE)
11714         .addReg(PPC::CR0)
11715         .addMBB(loop1MBB);
11716     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11717     BB->addSuccessor(loop1MBB);
11718     BB->addSuccessor(exitMBB);
11719 
11720     BB = midMBB;
11721     BuildMI(BB, dl, TII->get(PPC::STWCX))
11722         .addReg(TmpDestReg)
11723         .addReg(ZeroReg)
11724         .addReg(PtrReg);
11725     BB->addSuccessor(exitMBB);
11726 
11727     //  exitMBB:
11728     //   ...
11729     BB = exitMBB;
11730     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11731         .addReg(TmpReg)
11732         .addReg(ShiftReg);
11733   } else if (MI.getOpcode() == PPC::FADDrtz) {
11734     // This pseudo performs an FADD with rounding mode temporarily forced
11735     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11736     // is not modeled at the SelectionDAG level.
11737     Register Dest = MI.getOperand(0).getReg();
11738     Register Src1 = MI.getOperand(1).getReg();
11739     Register Src2 = MI.getOperand(2).getReg();
11740     DebugLoc dl = MI.getDebugLoc();
11741 
11742     MachineRegisterInfo &RegInfo = F->getRegInfo();
11743     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11744 
11745     // Save FPSCR value.
11746     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11747 
11748     // Set rounding mode to round-to-zero.
11749     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11750     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11751 
11752     // Perform addition.
11753     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11754 
11755     // Restore FPSCR value.
11756     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11757   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11758              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
11759              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11760              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
11761     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11762                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
11763                           ? PPC::ANDI8_rec
11764                           : PPC::ANDI_rec;
11765     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11766                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
11767 
11768     MachineRegisterInfo &RegInfo = F->getRegInfo();
11769     Register Dest = RegInfo.createVirtualRegister(
11770         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11771 
11772     DebugLoc Dl = MI.getDebugLoc();
11773     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
11774         .addReg(MI.getOperand(1).getReg())
11775         .addImm(1);
11776     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11777             MI.getOperand(0).getReg())
11778         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
11779   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11780     DebugLoc Dl = MI.getDebugLoc();
11781     MachineRegisterInfo &RegInfo = F->getRegInfo();
11782     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11783     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11784     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11785             MI.getOperand(0).getReg())
11786         .addReg(CRReg);
11787   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11788     DebugLoc Dl = MI.getDebugLoc();
11789     unsigned Imm = MI.getOperand(1).getImm();
11790     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11791     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11792             MI.getOperand(0).getReg())
11793         .addReg(PPC::CR0EQ);
11794   } else if (MI.getOpcode() == PPC::SETRNDi) {
11795     DebugLoc dl = MI.getDebugLoc();
11796     Register OldFPSCRReg = MI.getOperand(0).getReg();
11797 
11798     // Save FPSCR value.
11799     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11800 
11801     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11802     // the following settings:
11803     //   00 Round to nearest
11804     //   01 Round to 0
11805     //   10 Round to +inf
11806     //   11 Round to -inf
11807 
11808     // When the operand is immediate, using the two least significant bits of
11809     // the immediate to set the bits 62:63 of FPSCR.
11810     unsigned Mode = MI.getOperand(1).getImm();
11811     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11812       .addImm(31);
11813 
11814     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11815       .addImm(30);
11816   } else if (MI.getOpcode() == PPC::SETRND) {
11817     DebugLoc dl = MI.getDebugLoc();
11818 
11819     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11820     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11821     // If the target doesn't have DirectMove, we should use stack to do the
11822     // conversion, because the target doesn't have the instructions like mtvsrd
11823     // or mfvsrd to do this conversion directly.
11824     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11825       if (Subtarget.hasDirectMove()) {
11826         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11827           .addReg(SrcReg);
11828       } else {
11829         // Use stack to do the register copy.
11830         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11831         MachineRegisterInfo &RegInfo = F->getRegInfo();
11832         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11833         if (RC == &PPC::F8RCRegClass) {
11834           // Copy register from F8RCRegClass to G8RCRegclass.
11835           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11836                  "Unsupported RegClass.");
11837 
11838           StoreOp = PPC::STFD;
11839           LoadOp = PPC::LD;
11840         } else {
11841           // Copy register from G8RCRegClass to F8RCRegclass.
11842           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11843                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11844                  "Unsupported RegClass.");
11845         }
11846 
11847         MachineFrameInfo &MFI = F->getFrameInfo();
11848         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11849 
11850         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11851           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11852           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11853           MFI.getObjectAlignment(FrameIdx));
11854 
11855         // Store the SrcReg into the stack.
11856         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11857           .addReg(SrcReg)
11858           .addImm(0)
11859           .addFrameIndex(FrameIdx)
11860           .addMemOperand(MMOStore);
11861 
11862         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11863           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11864           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11865           MFI.getObjectAlignment(FrameIdx));
11866 
11867         // Load from the stack where SrcReg is stored, and save to DestReg,
11868         // so we have done the RegClass conversion from RegClass::SrcReg to
11869         // RegClass::DestReg.
11870         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11871           .addImm(0)
11872           .addFrameIndex(FrameIdx)
11873           .addMemOperand(MMOLoad);
11874       }
11875     };
11876 
11877     Register OldFPSCRReg = MI.getOperand(0).getReg();
11878 
11879     // Save FPSCR value.
11880     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11881 
11882     // When the operand is gprc register, use two least significant bits of the
11883     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11884     //
11885     // copy OldFPSCRTmpReg, OldFPSCRReg
11886     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11887     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11888     // copy NewFPSCRReg, NewFPSCRTmpReg
11889     // mtfsf 255, NewFPSCRReg
11890     MachineOperand SrcOp = MI.getOperand(1);
11891     MachineRegisterInfo &RegInfo = F->getRegInfo();
11892     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11893 
11894     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11895 
11896     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11897     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11898 
11899     // The first operand of INSERT_SUBREG should be a register which has
11900     // subregisters, we only care about its RegClass, so we should use an
11901     // IMPLICIT_DEF register.
11902     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11903     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11904       .addReg(ImDefReg)
11905       .add(SrcOp)
11906       .addImm(1);
11907 
11908     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11909     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11910       .addReg(OldFPSCRTmpReg)
11911       .addReg(ExtSrcReg)
11912       .addImm(0)
11913       .addImm(62);
11914 
11915     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11916     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11917 
11918     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11919     // bits of FPSCR.
11920     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11921       .addImm(255)
11922       .addReg(NewFPSCRReg)
11923       .addImm(0)
11924       .addImm(0);
11925   } else {
11926     llvm_unreachable("Unexpected instr type to insert");
11927   }
11928 
11929   MI.eraseFromParent(); // The pseudo instruction is gone now.
11930   return BB;
11931 }
11932 
11933 //===----------------------------------------------------------------------===//
11934 // Target Optimization Hooks
11935 //===----------------------------------------------------------------------===//
11936 
11937 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11938   // For the estimates, convergence is quadratic, so we essentially double the
11939   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11940   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11941   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11942   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11943   if (VT.getScalarType() == MVT::f64)
11944     RefinementSteps++;
11945   return RefinementSteps;
11946 }
11947 
11948 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11949                                            int Enabled, int &RefinementSteps,
11950                                            bool &UseOneConstNR,
11951                                            bool Reciprocal) const {
11952   EVT VT = Operand.getValueType();
11953   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11954       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11955       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11956       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11957       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11958       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11959     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11960       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11961 
11962     // The Newton-Raphson computation with a single constant does not provide
11963     // enough accuracy on some CPUs.
11964     UseOneConstNR = !Subtarget.needsTwoConstNR();
11965     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11966   }
11967   return SDValue();
11968 }
11969 
11970 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11971                                             int Enabled,
11972                                             int &RefinementSteps) const {
11973   EVT VT = Operand.getValueType();
11974   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11975       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11976       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11977       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11978       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11979       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11980     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11981       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11982     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11983   }
11984   return SDValue();
11985 }
11986 
11987 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11988   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11989   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11990   // enabled for division), this functionality is redundant with the default
11991   // combiner logic (once the division -> reciprocal/multiply transformation
11992   // has taken place). As a result, this matters more for older cores than for
11993   // newer ones.
11994 
11995   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11996   // reciprocal if there are two or more FDIVs (for embedded cores with only
11997   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11998   switch (Subtarget.getCPUDirective()) {
11999   default:
12000     return 3;
12001   case PPC::DIR_440:
12002   case PPC::DIR_A2:
12003   case PPC::DIR_E500:
12004   case PPC::DIR_E500mc:
12005   case PPC::DIR_E5500:
12006     return 2;
12007   }
12008 }
12009 
12010 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12011 // collapsed, and so we need to look through chains of them.
12012 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12013                                      int64_t& Offset, SelectionDAG &DAG) {
12014   if (DAG.isBaseWithConstantOffset(Loc)) {
12015     Base = Loc.getOperand(0);
12016     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12017 
12018     // The base might itself be a base plus an offset, and if so, accumulate
12019     // that as well.
12020     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12021   }
12022 }
12023 
12024 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12025                             unsigned Bytes, int Dist,
12026                             SelectionDAG &DAG) {
12027   if (VT.getSizeInBits() / 8 != Bytes)
12028     return false;
12029 
12030   SDValue BaseLoc = Base->getBasePtr();
12031   if (Loc.getOpcode() == ISD::FrameIndex) {
12032     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12033       return false;
12034     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12035     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12036     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12037     int FS  = MFI.getObjectSize(FI);
12038     int BFS = MFI.getObjectSize(BFI);
12039     if (FS != BFS || FS != (int)Bytes) return false;
12040     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12041   }
12042 
12043   SDValue Base1 = Loc, Base2 = BaseLoc;
12044   int64_t Offset1 = 0, Offset2 = 0;
12045   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12046   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12047   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12048     return true;
12049 
12050   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12051   const GlobalValue *GV1 = nullptr;
12052   const GlobalValue *GV2 = nullptr;
12053   Offset1 = 0;
12054   Offset2 = 0;
12055   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12056   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12057   if (isGA1 && isGA2 && GV1 == GV2)
12058     return Offset1 == (Offset2 + Dist*Bytes);
12059   return false;
12060 }
12061 
12062 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12063 // not enforce equality of the chain operands.
12064 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12065                             unsigned Bytes, int Dist,
12066                             SelectionDAG &DAG) {
12067   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12068     EVT VT = LS->getMemoryVT();
12069     SDValue Loc = LS->getBasePtr();
12070     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12071   }
12072 
12073   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12074     EVT VT;
12075     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12076     default: return false;
12077     case Intrinsic::ppc_qpx_qvlfd:
12078     case Intrinsic::ppc_qpx_qvlfda:
12079       VT = MVT::v4f64;
12080       break;
12081     case Intrinsic::ppc_qpx_qvlfs:
12082     case Intrinsic::ppc_qpx_qvlfsa:
12083       VT = MVT::v4f32;
12084       break;
12085     case Intrinsic::ppc_qpx_qvlfcd:
12086     case Intrinsic::ppc_qpx_qvlfcda:
12087       VT = MVT::v2f64;
12088       break;
12089     case Intrinsic::ppc_qpx_qvlfcs:
12090     case Intrinsic::ppc_qpx_qvlfcsa:
12091       VT = MVT::v2f32;
12092       break;
12093     case Intrinsic::ppc_qpx_qvlfiwa:
12094     case Intrinsic::ppc_qpx_qvlfiwz:
12095     case Intrinsic::ppc_altivec_lvx:
12096     case Intrinsic::ppc_altivec_lvxl:
12097     case Intrinsic::ppc_vsx_lxvw4x:
12098     case Intrinsic::ppc_vsx_lxvw4x_be:
12099       VT = MVT::v4i32;
12100       break;
12101     case Intrinsic::ppc_vsx_lxvd2x:
12102     case Intrinsic::ppc_vsx_lxvd2x_be:
12103       VT = MVT::v2f64;
12104       break;
12105     case Intrinsic::ppc_altivec_lvebx:
12106       VT = MVT::i8;
12107       break;
12108     case Intrinsic::ppc_altivec_lvehx:
12109       VT = MVT::i16;
12110       break;
12111     case Intrinsic::ppc_altivec_lvewx:
12112       VT = MVT::i32;
12113       break;
12114     }
12115 
12116     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12117   }
12118 
12119   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12120     EVT VT;
12121     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12122     default: return false;
12123     case Intrinsic::ppc_qpx_qvstfd:
12124     case Intrinsic::ppc_qpx_qvstfda:
12125       VT = MVT::v4f64;
12126       break;
12127     case Intrinsic::ppc_qpx_qvstfs:
12128     case Intrinsic::ppc_qpx_qvstfsa:
12129       VT = MVT::v4f32;
12130       break;
12131     case Intrinsic::ppc_qpx_qvstfcd:
12132     case Intrinsic::ppc_qpx_qvstfcda:
12133       VT = MVT::v2f64;
12134       break;
12135     case Intrinsic::ppc_qpx_qvstfcs:
12136     case Intrinsic::ppc_qpx_qvstfcsa:
12137       VT = MVT::v2f32;
12138       break;
12139     case Intrinsic::ppc_qpx_qvstfiw:
12140     case Intrinsic::ppc_qpx_qvstfiwa:
12141     case Intrinsic::ppc_altivec_stvx:
12142     case Intrinsic::ppc_altivec_stvxl:
12143     case Intrinsic::ppc_vsx_stxvw4x:
12144       VT = MVT::v4i32;
12145       break;
12146     case Intrinsic::ppc_vsx_stxvd2x:
12147       VT = MVT::v2f64;
12148       break;
12149     case Intrinsic::ppc_vsx_stxvw4x_be:
12150       VT = MVT::v4i32;
12151       break;
12152     case Intrinsic::ppc_vsx_stxvd2x_be:
12153       VT = MVT::v2f64;
12154       break;
12155     case Intrinsic::ppc_altivec_stvebx:
12156       VT = MVT::i8;
12157       break;
12158     case Intrinsic::ppc_altivec_stvehx:
12159       VT = MVT::i16;
12160       break;
12161     case Intrinsic::ppc_altivec_stvewx:
12162       VT = MVT::i32;
12163       break;
12164     }
12165 
12166     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12167   }
12168 
12169   return false;
12170 }
12171 
12172 // Return true is there is a nearyby consecutive load to the one provided
12173 // (regardless of alignment). We search up and down the chain, looking though
12174 // token factors and other loads (but nothing else). As a result, a true result
12175 // indicates that it is safe to create a new consecutive load adjacent to the
12176 // load provided.
12177 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12178   SDValue Chain = LD->getChain();
12179   EVT VT = LD->getMemoryVT();
12180 
12181   SmallSet<SDNode *, 16> LoadRoots;
12182   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12183   SmallSet<SDNode *, 16> Visited;
12184 
12185   // First, search up the chain, branching to follow all token-factor operands.
12186   // If we find a consecutive load, then we're done, otherwise, record all
12187   // nodes just above the top-level loads and token factors.
12188   while (!Queue.empty()) {
12189     SDNode *ChainNext = Queue.pop_back_val();
12190     if (!Visited.insert(ChainNext).second)
12191       continue;
12192 
12193     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12194       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12195         return true;
12196 
12197       if (!Visited.count(ChainLD->getChain().getNode()))
12198         Queue.push_back(ChainLD->getChain().getNode());
12199     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12200       for (const SDUse &O : ChainNext->ops())
12201         if (!Visited.count(O.getNode()))
12202           Queue.push_back(O.getNode());
12203     } else
12204       LoadRoots.insert(ChainNext);
12205   }
12206 
12207   // Second, search down the chain, starting from the top-level nodes recorded
12208   // in the first phase. These top-level nodes are the nodes just above all
12209   // loads and token factors. Starting with their uses, recursively look though
12210   // all loads (just the chain uses) and token factors to find a consecutive
12211   // load.
12212   Visited.clear();
12213   Queue.clear();
12214 
12215   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12216        IE = LoadRoots.end(); I != IE; ++I) {
12217     Queue.push_back(*I);
12218 
12219     while (!Queue.empty()) {
12220       SDNode *LoadRoot = Queue.pop_back_val();
12221       if (!Visited.insert(LoadRoot).second)
12222         continue;
12223 
12224       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12225         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12226           return true;
12227 
12228       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12229            UE = LoadRoot->use_end(); UI != UE; ++UI)
12230         if (((isa<MemSDNode>(*UI) &&
12231             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12232             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12233           Queue.push_back(*UI);
12234     }
12235   }
12236 
12237   return false;
12238 }
12239 
12240 /// This function is called when we have proved that a SETCC node can be replaced
12241 /// by subtraction (and other supporting instructions) so that the result of
12242 /// comparison is kept in a GPR instead of CR. This function is purely for
12243 /// codegen purposes and has some flags to guide the codegen process.
12244 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12245                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12246   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12247 
12248   // Zero extend the operands to the largest legal integer. Originally, they
12249   // must be of a strictly smaller size.
12250   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12251                          DAG.getConstant(Size, DL, MVT::i32));
12252   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12253                          DAG.getConstant(Size, DL, MVT::i32));
12254 
12255   // Swap if needed. Depends on the condition code.
12256   if (Swap)
12257     std::swap(Op0, Op1);
12258 
12259   // Subtract extended integers.
12260   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12261 
12262   // Move the sign bit to the least significant position and zero out the rest.
12263   // Now the least significant bit carries the result of original comparison.
12264   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12265                              DAG.getConstant(Size - 1, DL, MVT::i32));
12266   auto Final = Shifted;
12267 
12268   // Complement the result if needed. Based on the condition code.
12269   if (Complement)
12270     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12271                         DAG.getConstant(1, DL, MVT::i64));
12272 
12273   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12274 }
12275 
12276 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12277                                                   DAGCombinerInfo &DCI) const {
12278   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12279 
12280   SelectionDAG &DAG = DCI.DAG;
12281   SDLoc DL(N);
12282 
12283   // Size of integers being compared has a critical role in the following
12284   // analysis, so we prefer to do this when all types are legal.
12285   if (!DCI.isAfterLegalizeDAG())
12286     return SDValue();
12287 
12288   // If all users of SETCC extend its value to a legal integer type
12289   // then we replace SETCC with a subtraction
12290   for (SDNode::use_iterator UI = N->use_begin(),
12291        UE = N->use_end(); UI != UE; ++UI) {
12292     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12293       return SDValue();
12294   }
12295 
12296   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12297   auto OpSize = N->getOperand(0).getValueSizeInBits();
12298 
12299   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12300 
12301   if (OpSize < Size) {
12302     switch (CC) {
12303     default: break;
12304     case ISD::SETULT:
12305       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12306     case ISD::SETULE:
12307       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12308     case ISD::SETUGT:
12309       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12310     case ISD::SETUGE:
12311       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12312     }
12313   }
12314 
12315   return SDValue();
12316 }
12317 
12318 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12319                                                   DAGCombinerInfo &DCI) const {
12320   SelectionDAG &DAG = DCI.DAG;
12321   SDLoc dl(N);
12322 
12323   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12324   // If we're tracking CR bits, we need to be careful that we don't have:
12325   //   trunc(binary-ops(zext(x), zext(y)))
12326   // or
12327   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12328   // such that we're unnecessarily moving things into GPRs when it would be
12329   // better to keep them in CR bits.
12330 
12331   // Note that trunc here can be an actual i1 trunc, or can be the effective
12332   // truncation that comes from a setcc or select_cc.
12333   if (N->getOpcode() == ISD::TRUNCATE &&
12334       N->getValueType(0) != MVT::i1)
12335     return SDValue();
12336 
12337   if (N->getOperand(0).getValueType() != MVT::i32 &&
12338       N->getOperand(0).getValueType() != MVT::i64)
12339     return SDValue();
12340 
12341   if (N->getOpcode() == ISD::SETCC ||
12342       N->getOpcode() == ISD::SELECT_CC) {
12343     // If we're looking at a comparison, then we need to make sure that the
12344     // high bits (all except for the first) don't matter the result.
12345     ISD::CondCode CC =
12346       cast<CondCodeSDNode>(N->getOperand(
12347         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12348     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12349 
12350     if (ISD::isSignedIntSetCC(CC)) {
12351       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12352           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12353         return SDValue();
12354     } else if (ISD::isUnsignedIntSetCC(CC)) {
12355       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12356                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12357           !DAG.MaskedValueIsZero(N->getOperand(1),
12358                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12359         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12360                                              : SDValue());
12361     } else {
12362       // This is neither a signed nor an unsigned comparison, just make sure
12363       // that the high bits are equal.
12364       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12365       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12366 
12367       // We don't really care about what is known about the first bit (if
12368       // anything), so clear it in all masks prior to comparing them.
12369       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12370       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12371 
12372       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12373         return SDValue();
12374     }
12375   }
12376 
12377   // We now know that the higher-order bits are irrelevant, we just need to
12378   // make sure that all of the intermediate operations are bit operations, and
12379   // all inputs are extensions.
12380   if (N->getOperand(0).getOpcode() != ISD::AND &&
12381       N->getOperand(0).getOpcode() != ISD::OR  &&
12382       N->getOperand(0).getOpcode() != ISD::XOR &&
12383       N->getOperand(0).getOpcode() != ISD::SELECT &&
12384       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12385       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12386       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12387       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12388       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12389     return SDValue();
12390 
12391   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12392       N->getOperand(1).getOpcode() != ISD::AND &&
12393       N->getOperand(1).getOpcode() != ISD::OR  &&
12394       N->getOperand(1).getOpcode() != ISD::XOR &&
12395       N->getOperand(1).getOpcode() != ISD::SELECT &&
12396       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12397       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12398       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12399       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12400       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12401     return SDValue();
12402 
12403   SmallVector<SDValue, 4> Inputs;
12404   SmallVector<SDValue, 8> BinOps, PromOps;
12405   SmallPtrSet<SDNode *, 16> Visited;
12406 
12407   for (unsigned i = 0; i < 2; ++i) {
12408     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12409           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12410           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12411           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12412         isa<ConstantSDNode>(N->getOperand(i)))
12413       Inputs.push_back(N->getOperand(i));
12414     else
12415       BinOps.push_back(N->getOperand(i));
12416 
12417     if (N->getOpcode() == ISD::TRUNCATE)
12418       break;
12419   }
12420 
12421   // Visit all inputs, collect all binary operations (and, or, xor and
12422   // select) that are all fed by extensions.
12423   while (!BinOps.empty()) {
12424     SDValue BinOp = BinOps.back();
12425     BinOps.pop_back();
12426 
12427     if (!Visited.insert(BinOp.getNode()).second)
12428       continue;
12429 
12430     PromOps.push_back(BinOp);
12431 
12432     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12433       // The condition of the select is not promoted.
12434       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12435         continue;
12436       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12437         continue;
12438 
12439       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12440             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12441             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12442            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12443           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12444         Inputs.push_back(BinOp.getOperand(i));
12445       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12446                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12447                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12448                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12449                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12450                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12451                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12452                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12453                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12454         BinOps.push_back(BinOp.getOperand(i));
12455       } else {
12456         // We have an input that is not an extension or another binary
12457         // operation; we'll abort this transformation.
12458         return SDValue();
12459       }
12460     }
12461   }
12462 
12463   // Make sure that this is a self-contained cluster of operations (which
12464   // is not quite the same thing as saying that everything has only one
12465   // use).
12466   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12467     if (isa<ConstantSDNode>(Inputs[i]))
12468       continue;
12469 
12470     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12471                               UE = Inputs[i].getNode()->use_end();
12472          UI != UE; ++UI) {
12473       SDNode *User = *UI;
12474       if (User != N && !Visited.count(User))
12475         return SDValue();
12476 
12477       // Make sure that we're not going to promote the non-output-value
12478       // operand(s) or SELECT or SELECT_CC.
12479       // FIXME: Although we could sometimes handle this, and it does occur in
12480       // practice that one of the condition inputs to the select is also one of
12481       // the outputs, we currently can't deal with this.
12482       if (User->getOpcode() == ISD::SELECT) {
12483         if (User->getOperand(0) == Inputs[i])
12484           return SDValue();
12485       } else if (User->getOpcode() == ISD::SELECT_CC) {
12486         if (User->getOperand(0) == Inputs[i] ||
12487             User->getOperand(1) == Inputs[i])
12488           return SDValue();
12489       }
12490     }
12491   }
12492 
12493   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12494     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12495                               UE = PromOps[i].getNode()->use_end();
12496          UI != UE; ++UI) {
12497       SDNode *User = *UI;
12498       if (User != N && !Visited.count(User))
12499         return SDValue();
12500 
12501       // Make sure that we're not going to promote the non-output-value
12502       // operand(s) or SELECT or SELECT_CC.
12503       // FIXME: Although we could sometimes handle this, and it does occur in
12504       // practice that one of the condition inputs to the select is also one of
12505       // the outputs, we currently can't deal with this.
12506       if (User->getOpcode() == ISD::SELECT) {
12507         if (User->getOperand(0) == PromOps[i])
12508           return SDValue();
12509       } else if (User->getOpcode() == ISD::SELECT_CC) {
12510         if (User->getOperand(0) == PromOps[i] ||
12511             User->getOperand(1) == PromOps[i])
12512           return SDValue();
12513       }
12514     }
12515   }
12516 
12517   // Replace all inputs with the extension operand.
12518   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12519     // Constants may have users outside the cluster of to-be-promoted nodes,
12520     // and so we need to replace those as we do the promotions.
12521     if (isa<ConstantSDNode>(Inputs[i]))
12522       continue;
12523     else
12524       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12525   }
12526 
12527   std::list<HandleSDNode> PromOpHandles;
12528   for (auto &PromOp : PromOps)
12529     PromOpHandles.emplace_back(PromOp);
12530 
12531   // Replace all operations (these are all the same, but have a different
12532   // (i1) return type). DAG.getNode will validate that the types of
12533   // a binary operator match, so go through the list in reverse so that
12534   // we've likely promoted both operands first. Any intermediate truncations or
12535   // extensions disappear.
12536   while (!PromOpHandles.empty()) {
12537     SDValue PromOp = PromOpHandles.back().getValue();
12538     PromOpHandles.pop_back();
12539 
12540     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12541         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12542         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12543         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12544       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12545           PromOp.getOperand(0).getValueType() != MVT::i1) {
12546         // The operand is not yet ready (see comment below).
12547         PromOpHandles.emplace_front(PromOp);
12548         continue;
12549       }
12550 
12551       SDValue RepValue = PromOp.getOperand(0);
12552       if (isa<ConstantSDNode>(RepValue))
12553         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12554 
12555       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12556       continue;
12557     }
12558 
12559     unsigned C;
12560     switch (PromOp.getOpcode()) {
12561     default:             C = 0; break;
12562     case ISD::SELECT:    C = 1; break;
12563     case ISD::SELECT_CC: C = 2; break;
12564     }
12565 
12566     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12567          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12568         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12569          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12570       // The to-be-promoted operands of this node have not yet been
12571       // promoted (this should be rare because we're going through the
12572       // list backward, but if one of the operands has several users in
12573       // this cluster of to-be-promoted nodes, it is possible).
12574       PromOpHandles.emplace_front(PromOp);
12575       continue;
12576     }
12577 
12578     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12579                                 PromOp.getNode()->op_end());
12580 
12581     // If there are any constant inputs, make sure they're replaced now.
12582     for (unsigned i = 0; i < 2; ++i)
12583       if (isa<ConstantSDNode>(Ops[C+i]))
12584         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12585 
12586     DAG.ReplaceAllUsesOfValueWith(PromOp,
12587       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12588   }
12589 
12590   // Now we're left with the initial truncation itself.
12591   if (N->getOpcode() == ISD::TRUNCATE)
12592     return N->getOperand(0);
12593 
12594   // Otherwise, this is a comparison. The operands to be compared have just
12595   // changed type (to i1), but everything else is the same.
12596   return SDValue(N, 0);
12597 }
12598 
12599 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12600                                                   DAGCombinerInfo &DCI) const {
12601   SelectionDAG &DAG = DCI.DAG;
12602   SDLoc dl(N);
12603 
12604   // If we're tracking CR bits, we need to be careful that we don't have:
12605   //   zext(binary-ops(trunc(x), trunc(y)))
12606   // or
12607   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12608   // such that we're unnecessarily moving things into CR bits that can more
12609   // efficiently stay in GPRs. Note that if we're not certain that the high
12610   // bits are set as required by the final extension, we still may need to do
12611   // some masking to get the proper behavior.
12612 
12613   // This same functionality is important on PPC64 when dealing with
12614   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12615   // the return values of functions. Because it is so similar, it is handled
12616   // here as well.
12617 
12618   if (N->getValueType(0) != MVT::i32 &&
12619       N->getValueType(0) != MVT::i64)
12620     return SDValue();
12621 
12622   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12623         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12624     return SDValue();
12625 
12626   if (N->getOperand(0).getOpcode() != ISD::AND &&
12627       N->getOperand(0).getOpcode() != ISD::OR  &&
12628       N->getOperand(0).getOpcode() != ISD::XOR &&
12629       N->getOperand(0).getOpcode() != ISD::SELECT &&
12630       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12631     return SDValue();
12632 
12633   SmallVector<SDValue, 4> Inputs;
12634   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12635   SmallPtrSet<SDNode *, 16> Visited;
12636 
12637   // Visit all inputs, collect all binary operations (and, or, xor and
12638   // select) that are all fed by truncations.
12639   while (!BinOps.empty()) {
12640     SDValue BinOp = BinOps.back();
12641     BinOps.pop_back();
12642 
12643     if (!Visited.insert(BinOp.getNode()).second)
12644       continue;
12645 
12646     PromOps.push_back(BinOp);
12647 
12648     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12649       // The condition of the select is not promoted.
12650       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12651         continue;
12652       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12653         continue;
12654 
12655       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12656           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12657         Inputs.push_back(BinOp.getOperand(i));
12658       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12659                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12660                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12661                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12662                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12663         BinOps.push_back(BinOp.getOperand(i));
12664       } else {
12665         // We have an input that is not a truncation or another binary
12666         // operation; we'll abort this transformation.
12667         return SDValue();
12668       }
12669     }
12670   }
12671 
12672   // The operands of a select that must be truncated when the select is
12673   // promoted because the operand is actually part of the to-be-promoted set.
12674   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12675 
12676   // Make sure that this is a self-contained cluster of operations (which
12677   // is not quite the same thing as saying that everything has only one
12678   // use).
12679   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12680     if (isa<ConstantSDNode>(Inputs[i]))
12681       continue;
12682 
12683     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12684                               UE = Inputs[i].getNode()->use_end();
12685          UI != UE; ++UI) {
12686       SDNode *User = *UI;
12687       if (User != N && !Visited.count(User))
12688         return SDValue();
12689 
12690       // If we're going to promote the non-output-value operand(s) or SELECT or
12691       // SELECT_CC, record them for truncation.
12692       if (User->getOpcode() == ISD::SELECT) {
12693         if (User->getOperand(0) == Inputs[i])
12694           SelectTruncOp[0].insert(std::make_pair(User,
12695                                     User->getOperand(0).getValueType()));
12696       } else if (User->getOpcode() == ISD::SELECT_CC) {
12697         if (User->getOperand(0) == Inputs[i])
12698           SelectTruncOp[0].insert(std::make_pair(User,
12699                                     User->getOperand(0).getValueType()));
12700         if (User->getOperand(1) == Inputs[i])
12701           SelectTruncOp[1].insert(std::make_pair(User,
12702                                     User->getOperand(1).getValueType()));
12703       }
12704     }
12705   }
12706 
12707   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12708     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12709                               UE = PromOps[i].getNode()->use_end();
12710          UI != UE; ++UI) {
12711       SDNode *User = *UI;
12712       if (User != N && !Visited.count(User))
12713         return SDValue();
12714 
12715       // If we're going to promote the non-output-value operand(s) or SELECT or
12716       // SELECT_CC, record them for truncation.
12717       if (User->getOpcode() == ISD::SELECT) {
12718         if (User->getOperand(0) == PromOps[i])
12719           SelectTruncOp[0].insert(std::make_pair(User,
12720                                     User->getOperand(0).getValueType()));
12721       } else if (User->getOpcode() == ISD::SELECT_CC) {
12722         if (User->getOperand(0) == PromOps[i])
12723           SelectTruncOp[0].insert(std::make_pair(User,
12724                                     User->getOperand(0).getValueType()));
12725         if (User->getOperand(1) == PromOps[i])
12726           SelectTruncOp[1].insert(std::make_pair(User,
12727                                     User->getOperand(1).getValueType()));
12728       }
12729     }
12730   }
12731 
12732   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12733   bool ReallyNeedsExt = false;
12734   if (N->getOpcode() != ISD::ANY_EXTEND) {
12735     // If all of the inputs are not already sign/zero extended, then
12736     // we'll still need to do that at the end.
12737     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12738       if (isa<ConstantSDNode>(Inputs[i]))
12739         continue;
12740 
12741       unsigned OpBits =
12742         Inputs[i].getOperand(0).getValueSizeInBits();
12743       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12744 
12745       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12746            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12747                                   APInt::getHighBitsSet(OpBits,
12748                                                         OpBits-PromBits))) ||
12749           (N->getOpcode() == ISD::SIGN_EXTEND &&
12750            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12751              (OpBits-(PromBits-1)))) {
12752         ReallyNeedsExt = true;
12753         break;
12754       }
12755     }
12756   }
12757 
12758   // Replace all inputs, either with the truncation operand, or a
12759   // truncation or extension to the final output type.
12760   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12761     // Constant inputs need to be replaced with the to-be-promoted nodes that
12762     // use them because they might have users outside of the cluster of
12763     // promoted nodes.
12764     if (isa<ConstantSDNode>(Inputs[i]))
12765       continue;
12766 
12767     SDValue InSrc = Inputs[i].getOperand(0);
12768     if (Inputs[i].getValueType() == N->getValueType(0))
12769       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12770     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12771       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12772         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12773     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12774       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12775         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12776     else
12777       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12778         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12779   }
12780 
12781   std::list<HandleSDNode> PromOpHandles;
12782   for (auto &PromOp : PromOps)
12783     PromOpHandles.emplace_back(PromOp);
12784 
12785   // Replace all operations (these are all the same, but have a different
12786   // (promoted) return type). DAG.getNode will validate that the types of
12787   // a binary operator match, so go through the list in reverse so that
12788   // we've likely promoted both operands first.
12789   while (!PromOpHandles.empty()) {
12790     SDValue PromOp = PromOpHandles.back().getValue();
12791     PromOpHandles.pop_back();
12792 
12793     unsigned C;
12794     switch (PromOp.getOpcode()) {
12795     default:             C = 0; break;
12796     case ISD::SELECT:    C = 1; break;
12797     case ISD::SELECT_CC: C = 2; break;
12798     }
12799 
12800     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12801          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12802         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12803          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12804       // The to-be-promoted operands of this node have not yet been
12805       // promoted (this should be rare because we're going through the
12806       // list backward, but if one of the operands has several users in
12807       // this cluster of to-be-promoted nodes, it is possible).
12808       PromOpHandles.emplace_front(PromOp);
12809       continue;
12810     }
12811 
12812     // For SELECT and SELECT_CC nodes, we do a similar check for any
12813     // to-be-promoted comparison inputs.
12814     if (PromOp.getOpcode() == ISD::SELECT ||
12815         PromOp.getOpcode() == ISD::SELECT_CC) {
12816       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12817            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12818           (SelectTruncOp[1].count(PromOp.getNode()) &&
12819            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12820         PromOpHandles.emplace_front(PromOp);
12821         continue;
12822       }
12823     }
12824 
12825     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12826                                 PromOp.getNode()->op_end());
12827 
12828     // If this node has constant inputs, then they'll need to be promoted here.
12829     for (unsigned i = 0; i < 2; ++i) {
12830       if (!isa<ConstantSDNode>(Ops[C+i]))
12831         continue;
12832       if (Ops[C+i].getValueType() == N->getValueType(0))
12833         continue;
12834 
12835       if (N->getOpcode() == ISD::SIGN_EXTEND)
12836         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12837       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12838         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12839       else
12840         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12841     }
12842 
12843     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12844     // truncate them again to the original value type.
12845     if (PromOp.getOpcode() == ISD::SELECT ||
12846         PromOp.getOpcode() == ISD::SELECT_CC) {
12847       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12848       if (SI0 != SelectTruncOp[0].end())
12849         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12850       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12851       if (SI1 != SelectTruncOp[1].end())
12852         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12853     }
12854 
12855     DAG.ReplaceAllUsesOfValueWith(PromOp,
12856       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12857   }
12858 
12859   // Now we're left with the initial extension itself.
12860   if (!ReallyNeedsExt)
12861     return N->getOperand(0);
12862 
12863   // To zero extend, just mask off everything except for the first bit (in the
12864   // i1 case).
12865   if (N->getOpcode() == ISD::ZERO_EXTEND)
12866     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12867                        DAG.getConstant(APInt::getLowBitsSet(
12868                                          N->getValueSizeInBits(0), PromBits),
12869                                        dl, N->getValueType(0)));
12870 
12871   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12872          "Invalid extension type");
12873   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12874   SDValue ShiftCst =
12875       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12876   return DAG.getNode(
12877       ISD::SRA, dl, N->getValueType(0),
12878       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12879       ShiftCst);
12880 }
12881 
12882 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12883                                         DAGCombinerInfo &DCI) const {
12884   assert(N->getOpcode() == ISD::SETCC &&
12885          "Should be called with a SETCC node");
12886 
12887   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12888   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12889     SDValue LHS = N->getOperand(0);
12890     SDValue RHS = N->getOperand(1);
12891 
12892     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12893     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12894         LHS.hasOneUse())
12895       std::swap(LHS, RHS);
12896 
12897     // x == 0-y --> x+y == 0
12898     // x != 0-y --> x+y != 0
12899     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12900         RHS.hasOneUse()) {
12901       SDLoc DL(N);
12902       SelectionDAG &DAG = DCI.DAG;
12903       EVT VT = N->getValueType(0);
12904       EVT OpVT = LHS.getValueType();
12905       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12906       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12907     }
12908   }
12909 
12910   return DAGCombineTruncBoolExt(N, DCI);
12911 }
12912 
12913 // Is this an extending load from an f32 to an f64?
12914 static bool isFPExtLoad(SDValue Op) {
12915   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12916     return LD->getExtensionType() == ISD::EXTLOAD &&
12917       Op.getValueType() == MVT::f64;
12918   return false;
12919 }
12920 
12921 /// Reduces the number of fp-to-int conversion when building a vector.
12922 ///
12923 /// If this vector is built out of floating to integer conversions,
12924 /// transform it to a vector built out of floating point values followed by a
12925 /// single floating to integer conversion of the vector.
12926 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12927 /// becomes (fptosi (build_vector ($A, $B, ...)))
12928 SDValue PPCTargetLowering::
12929 combineElementTruncationToVectorTruncation(SDNode *N,
12930                                            DAGCombinerInfo &DCI) const {
12931   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12932          "Should be called with a BUILD_VECTOR node");
12933 
12934   SelectionDAG &DAG = DCI.DAG;
12935   SDLoc dl(N);
12936 
12937   SDValue FirstInput = N->getOperand(0);
12938   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12939          "The input operand must be an fp-to-int conversion.");
12940 
12941   // This combine happens after legalization so the fp_to_[su]i nodes are
12942   // already converted to PPCSISD nodes.
12943   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12944   if (FirstConversion == PPCISD::FCTIDZ ||
12945       FirstConversion == PPCISD::FCTIDUZ ||
12946       FirstConversion == PPCISD::FCTIWZ ||
12947       FirstConversion == PPCISD::FCTIWUZ) {
12948     bool IsSplat = true;
12949     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12950       FirstConversion == PPCISD::FCTIWUZ;
12951     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12952     SmallVector<SDValue, 4> Ops;
12953     EVT TargetVT = N->getValueType(0);
12954     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12955       SDValue NextOp = N->getOperand(i);
12956       if (NextOp.getOpcode() != PPCISD::MFVSR)
12957         return SDValue();
12958       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12959       if (NextConversion != FirstConversion)
12960         return SDValue();
12961       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12962       // This is not valid if the input was originally double precision. It is
12963       // also not profitable to do unless this is an extending load in which
12964       // case doing this combine will allow us to combine consecutive loads.
12965       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12966         return SDValue();
12967       if (N->getOperand(i) != FirstInput)
12968         IsSplat = false;
12969     }
12970 
12971     // If this is a splat, we leave it as-is since there will be only a single
12972     // fp-to-int conversion followed by a splat of the integer. This is better
12973     // for 32-bit and smaller ints and neutral for 64-bit ints.
12974     if (IsSplat)
12975       return SDValue();
12976 
12977     // Now that we know we have the right type of node, get its operands
12978     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12979       SDValue In = N->getOperand(i).getOperand(0);
12980       if (Is32Bit) {
12981         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12982         // here, we know that all inputs are extending loads so this is safe).
12983         if (In.isUndef())
12984           Ops.push_back(DAG.getUNDEF(SrcVT));
12985         else {
12986           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12987                                       MVT::f32, In.getOperand(0),
12988                                       DAG.getIntPtrConstant(1, dl));
12989           Ops.push_back(Trunc);
12990         }
12991       } else
12992         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12993     }
12994 
12995     unsigned Opcode;
12996     if (FirstConversion == PPCISD::FCTIDZ ||
12997         FirstConversion == PPCISD::FCTIWZ)
12998       Opcode = ISD::FP_TO_SINT;
12999     else
13000       Opcode = ISD::FP_TO_UINT;
13001 
13002     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13003     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13004     return DAG.getNode(Opcode, dl, TargetVT, BV);
13005   }
13006   return SDValue();
13007 }
13008 
13009 /// Reduce the number of loads when building a vector.
13010 ///
13011 /// Building a vector out of multiple loads can be converted to a load
13012 /// of the vector type if the loads are consecutive. If the loads are
13013 /// consecutive but in descending order, a shuffle is added at the end
13014 /// to reorder the vector.
13015 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13016   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13017          "Should be called with a BUILD_VECTOR node");
13018 
13019   SDLoc dl(N);
13020 
13021   // Return early for non byte-sized type, as they can't be consecutive.
13022   if (!N->getValueType(0).getVectorElementType().isByteSized())
13023     return SDValue();
13024 
13025   bool InputsAreConsecutiveLoads = true;
13026   bool InputsAreReverseConsecutive = true;
13027   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13028   SDValue FirstInput = N->getOperand(0);
13029   bool IsRoundOfExtLoad = false;
13030 
13031   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13032       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13033     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13034     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13035   }
13036   // Not a build vector of (possibly fp_rounded) loads.
13037   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13038       N->getNumOperands() == 1)
13039     return SDValue();
13040 
13041   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13042     // If any inputs are fp_round(extload), they all must be.
13043     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13044       return SDValue();
13045 
13046     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13047       N->getOperand(i);
13048     if (NextInput.getOpcode() != ISD::LOAD)
13049       return SDValue();
13050 
13051     SDValue PreviousInput =
13052       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13053     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13054     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13055 
13056     // If any inputs are fp_round(extload), they all must be.
13057     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13058       return SDValue();
13059 
13060     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13061       InputsAreConsecutiveLoads = false;
13062     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13063       InputsAreReverseConsecutive = false;
13064 
13065     // Exit early if the loads are neither consecutive nor reverse consecutive.
13066     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13067       return SDValue();
13068   }
13069 
13070   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13071          "The loads cannot be both consecutive and reverse consecutive.");
13072 
13073   SDValue FirstLoadOp =
13074     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13075   SDValue LastLoadOp =
13076     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13077                        N->getOperand(N->getNumOperands()-1);
13078 
13079   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13080   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13081   if (InputsAreConsecutiveLoads) {
13082     assert(LD1 && "Input needs to be a LoadSDNode.");
13083     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13084                        LD1->getBasePtr(), LD1->getPointerInfo(),
13085                        LD1->getAlignment());
13086   }
13087   if (InputsAreReverseConsecutive) {
13088     assert(LDL && "Input needs to be a LoadSDNode.");
13089     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13090                                LDL->getBasePtr(), LDL->getPointerInfo(),
13091                                LDL->getAlignment());
13092     SmallVector<int, 16> Ops;
13093     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13094       Ops.push_back(i);
13095 
13096     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13097                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13098   }
13099   return SDValue();
13100 }
13101 
13102 // This function adds the required vector_shuffle needed to get
13103 // the elements of the vector extract in the correct position
13104 // as specified by the CorrectElems encoding.
13105 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13106                                       SDValue Input, uint64_t Elems,
13107                                       uint64_t CorrectElems) {
13108   SDLoc dl(N);
13109 
13110   unsigned NumElems = Input.getValueType().getVectorNumElements();
13111   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13112 
13113   // Knowing the element indices being extracted from the original
13114   // vector and the order in which they're being inserted, just put
13115   // them at element indices required for the instruction.
13116   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13117     if (DAG.getDataLayout().isLittleEndian())
13118       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13119     else
13120       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13121     CorrectElems = CorrectElems >> 8;
13122     Elems = Elems >> 8;
13123   }
13124 
13125   SDValue Shuffle =
13126       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13127                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13128 
13129   EVT Ty = N->getValueType(0);
13130   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
13131   return BV;
13132 }
13133 
13134 // Look for build vector patterns where input operands come from sign
13135 // extended vector_extract elements of specific indices. If the correct indices
13136 // aren't used, add a vector shuffle to fix up the indices and create a new
13137 // PPCISD:SExtVElems node which selects the vector sign extend instructions
13138 // during instruction selection.
13139 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13140   // This array encodes the indices that the vector sign extend instructions
13141   // extract from when extending from one type to another for both BE and LE.
13142   // The right nibble of each byte corresponds to the LE incides.
13143   // and the left nibble of each byte corresponds to the BE incides.
13144   // For example: 0x3074B8FC  byte->word
13145   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13146   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13147   // For example: 0x000070F8  byte->double word
13148   // For LE: the allowed indices are: 0x0,0x8
13149   // For BE: the allowed indices are: 0x7,0xF
13150   uint64_t TargetElems[] = {
13151       0x3074B8FC, // b->w
13152       0x000070F8, // b->d
13153       0x10325476, // h->w
13154       0x00003074, // h->d
13155       0x00001032, // w->d
13156   };
13157 
13158   uint64_t Elems = 0;
13159   int Index;
13160   SDValue Input;
13161 
13162   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13163     if (!Op)
13164       return false;
13165     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13166         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13167       return false;
13168 
13169     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13170     // of the right width.
13171     SDValue Extract = Op.getOperand(0);
13172     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13173       Extract = Extract.getOperand(0);
13174     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13175       return false;
13176 
13177     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13178     if (!ExtOp)
13179       return false;
13180 
13181     Index = ExtOp->getZExtValue();
13182     if (Input && Input != Extract.getOperand(0))
13183       return false;
13184 
13185     if (!Input)
13186       Input = Extract.getOperand(0);
13187 
13188     Elems = Elems << 8;
13189     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13190     Elems |= Index;
13191 
13192     return true;
13193   };
13194 
13195   // If the build vector operands aren't sign extended vector extracts,
13196   // of the same input vector, then return.
13197   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13198     if (!isSExtOfVecExtract(N->getOperand(i))) {
13199       return SDValue();
13200     }
13201   }
13202 
13203   // If the vector extract indicies are not correct, add the appropriate
13204   // vector_shuffle.
13205   int TgtElemArrayIdx;
13206   int InputSize = Input.getValueType().getScalarSizeInBits();
13207   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13208   if (InputSize + OutputSize == 40)
13209     TgtElemArrayIdx = 0;
13210   else if (InputSize + OutputSize == 72)
13211     TgtElemArrayIdx = 1;
13212   else if (InputSize + OutputSize == 48)
13213     TgtElemArrayIdx = 2;
13214   else if (InputSize + OutputSize == 80)
13215     TgtElemArrayIdx = 3;
13216   else if (InputSize + OutputSize == 96)
13217     TgtElemArrayIdx = 4;
13218   else
13219     return SDValue();
13220 
13221   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13222   CorrectElems = DAG.getDataLayout().isLittleEndian()
13223                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13224                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13225   if (Elems != CorrectElems) {
13226     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13227   }
13228 
13229   // Regular lowering will catch cases where a shuffle is not needed.
13230   return SDValue();
13231 }
13232 
13233 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13234                                                  DAGCombinerInfo &DCI) const {
13235   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13236          "Should be called with a BUILD_VECTOR node");
13237 
13238   SelectionDAG &DAG = DCI.DAG;
13239   SDLoc dl(N);
13240 
13241   if (!Subtarget.hasVSX())
13242     return SDValue();
13243 
13244   // The target independent DAG combiner will leave a build_vector of
13245   // float-to-int conversions intact. We can generate MUCH better code for
13246   // a float-to-int conversion of a vector of floats.
13247   SDValue FirstInput = N->getOperand(0);
13248   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13249     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13250     if (Reduced)
13251       return Reduced;
13252   }
13253 
13254   // If we're building a vector out of consecutive loads, just load that
13255   // vector type.
13256   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13257   if (Reduced)
13258     return Reduced;
13259 
13260   // If we're building a vector out of extended elements from another vector
13261   // we have P9 vector integer extend instructions. The code assumes legal
13262   // input types (i.e. it can't handle things like v4i16) so do not run before
13263   // legalization.
13264   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13265     Reduced = combineBVOfVecSExt(N, DAG);
13266     if (Reduced)
13267       return Reduced;
13268   }
13269 
13270 
13271   if (N->getValueType(0) != MVT::v2f64)
13272     return SDValue();
13273 
13274   // Looking for:
13275   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13276   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13277       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13278     return SDValue();
13279   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13280       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13281     return SDValue();
13282   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13283     return SDValue();
13284 
13285   SDValue Ext1 = FirstInput.getOperand(0);
13286   SDValue Ext2 = N->getOperand(1).getOperand(0);
13287   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13288      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13289     return SDValue();
13290 
13291   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13292   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13293   if (!Ext1Op || !Ext2Op)
13294     return SDValue();
13295   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13296       Ext1.getOperand(0) != Ext2.getOperand(0))
13297     return SDValue();
13298 
13299   int FirstElem = Ext1Op->getZExtValue();
13300   int SecondElem = Ext2Op->getZExtValue();
13301   int SubvecIdx;
13302   if (FirstElem == 0 && SecondElem == 1)
13303     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13304   else if (FirstElem == 2 && SecondElem == 3)
13305     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13306   else
13307     return SDValue();
13308 
13309   SDValue SrcVec = Ext1.getOperand(0);
13310   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13311     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13312   return DAG.getNode(NodeType, dl, MVT::v2f64,
13313                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13314 }
13315 
13316 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13317                                               DAGCombinerInfo &DCI) const {
13318   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13319           N->getOpcode() == ISD::UINT_TO_FP) &&
13320          "Need an int -> FP conversion node here");
13321 
13322   if (useSoftFloat() || !Subtarget.has64BitSupport())
13323     return SDValue();
13324 
13325   SelectionDAG &DAG = DCI.DAG;
13326   SDLoc dl(N);
13327   SDValue Op(N, 0);
13328 
13329   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13330   // from the hardware.
13331   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13332     return SDValue();
13333   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13334       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13335     return SDValue();
13336 
13337   SDValue FirstOperand(Op.getOperand(0));
13338   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13339     (FirstOperand.getValueType() == MVT::i8 ||
13340      FirstOperand.getValueType() == MVT::i16);
13341   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13342     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13343     bool DstDouble = Op.getValueType() == MVT::f64;
13344     unsigned ConvOp = Signed ?
13345       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13346       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13347     SDValue WidthConst =
13348       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13349                             dl, false);
13350     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13351     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13352     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13353                                          DAG.getVTList(MVT::f64, MVT::Other),
13354                                          Ops, MVT::i8, LDN->getMemOperand());
13355 
13356     // For signed conversion, we need to sign-extend the value in the VSR
13357     if (Signed) {
13358       SDValue ExtOps[] = { Ld, WidthConst };
13359       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13360       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13361     } else
13362       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13363   }
13364 
13365 
13366   // For i32 intermediate values, unfortunately, the conversion functions
13367   // leave the upper 32 bits of the value are undefined. Within the set of
13368   // scalar instructions, we have no method for zero- or sign-extending the
13369   // value. Thus, we cannot handle i32 intermediate values here.
13370   if (Op.getOperand(0).getValueType() == MVT::i32)
13371     return SDValue();
13372 
13373   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13374          "UINT_TO_FP is supported only with FPCVT");
13375 
13376   // If we have FCFIDS, then use it when converting to single-precision.
13377   // Otherwise, convert to double-precision and then round.
13378   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13379                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13380                                                             : PPCISD::FCFIDS)
13381                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13382                                                             : PPCISD::FCFID);
13383   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13384                   ? MVT::f32
13385                   : MVT::f64;
13386 
13387   // If we're converting from a float, to an int, and back to a float again,
13388   // then we don't need the store/load pair at all.
13389   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13390        Subtarget.hasFPCVT()) ||
13391       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13392     SDValue Src = Op.getOperand(0).getOperand(0);
13393     if (Src.getValueType() == MVT::f32) {
13394       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13395       DCI.AddToWorklist(Src.getNode());
13396     } else if (Src.getValueType() != MVT::f64) {
13397       // Make sure that we don't pick up a ppc_fp128 source value.
13398       return SDValue();
13399     }
13400 
13401     unsigned FCTOp =
13402       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13403                                                         PPCISD::FCTIDUZ;
13404 
13405     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13406     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13407 
13408     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13409       FP = DAG.getNode(ISD::FP_ROUND, dl,
13410                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13411       DCI.AddToWorklist(FP.getNode());
13412     }
13413 
13414     return FP;
13415   }
13416 
13417   return SDValue();
13418 }
13419 
13420 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13421 // builtins) into loads with swaps.
13422 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13423                                               DAGCombinerInfo &DCI) const {
13424   SelectionDAG &DAG = DCI.DAG;
13425   SDLoc dl(N);
13426   SDValue Chain;
13427   SDValue Base;
13428   MachineMemOperand *MMO;
13429 
13430   switch (N->getOpcode()) {
13431   default:
13432     llvm_unreachable("Unexpected opcode for little endian VSX load");
13433   case ISD::LOAD: {
13434     LoadSDNode *LD = cast<LoadSDNode>(N);
13435     Chain = LD->getChain();
13436     Base = LD->getBasePtr();
13437     MMO = LD->getMemOperand();
13438     // If the MMO suggests this isn't a load of a full vector, leave
13439     // things alone.  For a built-in, we have to make the change for
13440     // correctness, so if there is a size problem that will be a bug.
13441     if (MMO->getSize() < 16)
13442       return SDValue();
13443     break;
13444   }
13445   case ISD::INTRINSIC_W_CHAIN: {
13446     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13447     Chain = Intrin->getChain();
13448     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13449     // us what we want. Get operand 2 instead.
13450     Base = Intrin->getOperand(2);
13451     MMO = Intrin->getMemOperand();
13452     break;
13453   }
13454   }
13455 
13456   MVT VecTy = N->getValueType(0).getSimpleVT();
13457 
13458   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13459   // aligned and the type is a vector with elements up to 4 bytes
13460   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13461       && VecTy.getScalarSizeInBits() <= 32 ) {
13462     return SDValue();
13463   }
13464 
13465   SDValue LoadOps[] = { Chain, Base };
13466   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13467                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13468                                          LoadOps, MVT::v2f64, MMO);
13469 
13470   DCI.AddToWorklist(Load.getNode());
13471   Chain = Load.getValue(1);
13472   SDValue Swap = DAG.getNode(
13473       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13474   DCI.AddToWorklist(Swap.getNode());
13475 
13476   // Add a bitcast if the resulting load type doesn't match v2f64.
13477   if (VecTy != MVT::v2f64) {
13478     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13479     DCI.AddToWorklist(N.getNode());
13480     // Package {bitcast value, swap's chain} to match Load's shape.
13481     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13482                        N, Swap.getValue(1));
13483   }
13484 
13485   return Swap;
13486 }
13487 
13488 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13489 // builtins) into stores with swaps.
13490 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13491                                                DAGCombinerInfo &DCI) const {
13492   SelectionDAG &DAG = DCI.DAG;
13493   SDLoc dl(N);
13494   SDValue Chain;
13495   SDValue Base;
13496   unsigned SrcOpnd;
13497   MachineMemOperand *MMO;
13498 
13499   switch (N->getOpcode()) {
13500   default:
13501     llvm_unreachable("Unexpected opcode for little endian VSX store");
13502   case ISD::STORE: {
13503     StoreSDNode *ST = cast<StoreSDNode>(N);
13504     Chain = ST->getChain();
13505     Base = ST->getBasePtr();
13506     MMO = ST->getMemOperand();
13507     SrcOpnd = 1;
13508     // If the MMO suggests this isn't a store of a full vector, leave
13509     // things alone.  For a built-in, we have to make the change for
13510     // correctness, so if there is a size problem that will be a bug.
13511     if (MMO->getSize() < 16)
13512       return SDValue();
13513     break;
13514   }
13515   case ISD::INTRINSIC_VOID: {
13516     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13517     Chain = Intrin->getChain();
13518     // Intrin->getBasePtr() oddly does not get what we want.
13519     Base = Intrin->getOperand(3);
13520     MMO = Intrin->getMemOperand();
13521     SrcOpnd = 2;
13522     break;
13523   }
13524   }
13525 
13526   SDValue Src = N->getOperand(SrcOpnd);
13527   MVT VecTy = Src.getValueType().getSimpleVT();
13528 
13529   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13530   // aligned and the type is a vector with elements up to 4 bytes
13531   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13532       && VecTy.getScalarSizeInBits() <= 32 ) {
13533     return SDValue();
13534   }
13535 
13536   // All stores are done as v2f64 and possible bit cast.
13537   if (VecTy != MVT::v2f64) {
13538     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13539     DCI.AddToWorklist(Src.getNode());
13540   }
13541 
13542   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13543                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13544   DCI.AddToWorklist(Swap.getNode());
13545   Chain = Swap.getValue(1);
13546   SDValue StoreOps[] = { Chain, Swap, Base };
13547   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13548                                           DAG.getVTList(MVT::Other),
13549                                           StoreOps, VecTy, MMO);
13550   DCI.AddToWorklist(Store.getNode());
13551   return Store;
13552 }
13553 
13554 // Handle DAG combine for STORE (FP_TO_INT F).
13555 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13556                                                DAGCombinerInfo &DCI) const {
13557 
13558   SelectionDAG &DAG = DCI.DAG;
13559   SDLoc dl(N);
13560   unsigned Opcode = N->getOperand(1).getOpcode();
13561 
13562   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13563          && "Not a FP_TO_INT Instruction!");
13564 
13565   SDValue Val = N->getOperand(1).getOperand(0);
13566   EVT Op1VT = N->getOperand(1).getValueType();
13567   EVT ResVT = Val.getValueType();
13568 
13569   // Floating point types smaller than 32 bits are not legal on Power.
13570   if (ResVT.getScalarSizeInBits() < 32)
13571     return SDValue();
13572 
13573   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13574   bool ValidTypeForStoreFltAsInt =
13575         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13576          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13577 
13578   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13579       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13580     return SDValue();
13581 
13582   // Extend f32 values to f64
13583   if (ResVT.getScalarSizeInBits() == 32) {
13584     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13585     DCI.AddToWorklist(Val.getNode());
13586   }
13587 
13588   // Set signed or unsigned conversion opcode.
13589   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13590                           PPCISD::FP_TO_SINT_IN_VSR :
13591                           PPCISD::FP_TO_UINT_IN_VSR;
13592 
13593   Val = DAG.getNode(ConvOpcode,
13594                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13595   DCI.AddToWorklist(Val.getNode());
13596 
13597   // Set number of bytes being converted.
13598   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13599   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13600                     DAG.getIntPtrConstant(ByteSize, dl, false),
13601                     DAG.getValueType(Op1VT) };
13602 
13603   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13604           DAG.getVTList(MVT::Other), Ops,
13605           cast<StoreSDNode>(N)->getMemoryVT(),
13606           cast<StoreSDNode>(N)->getMemOperand());
13607 
13608   DCI.AddToWorklist(Val.getNode());
13609   return Val;
13610 }
13611 
13612 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13613                                                 LSBaseSDNode *LSBase,
13614                                                 DAGCombinerInfo &DCI) const {
13615   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13616         "Not a reverse memop pattern!");
13617 
13618   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13619     auto Mask = SVN->getMask();
13620     int i = 0;
13621     auto I = Mask.rbegin();
13622     auto E = Mask.rend();
13623 
13624     for (; I != E; ++I) {
13625       if (*I != i)
13626         return false;
13627       i++;
13628     }
13629     return true;
13630   };
13631 
13632   SelectionDAG &DAG = DCI.DAG;
13633   EVT VT = SVN->getValueType(0);
13634 
13635   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13636     return SDValue();
13637 
13638   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13639   // See comment in PPCVSXSwapRemoval.cpp.
13640   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13641   if (!Subtarget.hasP9Vector())
13642     return SDValue();
13643 
13644   if(!IsElementReverse(SVN))
13645     return SDValue();
13646 
13647   if (LSBase->getOpcode() == ISD::LOAD) {
13648     SDLoc dl(SVN);
13649     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13650     return DAG.getMemIntrinsicNode(
13651         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13652         LSBase->getMemoryVT(), LSBase->getMemOperand());
13653   }
13654 
13655   if (LSBase->getOpcode() == ISD::STORE) {
13656     SDLoc dl(LSBase);
13657     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13658                           LSBase->getBasePtr()};
13659     return DAG.getMemIntrinsicNode(
13660         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13661         LSBase->getMemoryVT(), LSBase->getMemOperand());
13662   }
13663 
13664   llvm_unreachable("Expected a load or store node here");
13665 }
13666 
13667 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13668                                              DAGCombinerInfo &DCI) const {
13669   SelectionDAG &DAG = DCI.DAG;
13670   SDLoc dl(N);
13671   switch (N->getOpcode()) {
13672   default: break;
13673   case ISD::ADD:
13674     return combineADD(N, DCI);
13675   case ISD::SHL:
13676     return combineSHL(N, DCI);
13677   case ISD::SRA:
13678     return combineSRA(N, DCI);
13679   case ISD::SRL:
13680     return combineSRL(N, DCI);
13681   case ISD::MUL:
13682     return combineMUL(N, DCI);
13683   case PPCISD::SHL:
13684     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13685         return N->getOperand(0);
13686     break;
13687   case PPCISD::SRL:
13688     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13689         return N->getOperand(0);
13690     break;
13691   case PPCISD::SRA:
13692     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13693       if (C->isNullValue() ||   //  0 >>s V -> 0.
13694           C->isAllOnesValue())    // -1 >>s V -> -1.
13695         return N->getOperand(0);
13696     }
13697     break;
13698   case ISD::SIGN_EXTEND:
13699   case ISD::ZERO_EXTEND:
13700   case ISD::ANY_EXTEND:
13701     return DAGCombineExtBoolTrunc(N, DCI);
13702   case ISD::TRUNCATE:
13703     return combineTRUNCATE(N, DCI);
13704   case ISD::SETCC:
13705     if (SDValue CSCC = combineSetCC(N, DCI))
13706       return CSCC;
13707     LLVM_FALLTHROUGH;
13708   case ISD::SELECT_CC:
13709     return DAGCombineTruncBoolExt(N, DCI);
13710   case ISD::SINT_TO_FP:
13711   case ISD::UINT_TO_FP:
13712     return combineFPToIntToFP(N, DCI);
13713   case ISD::VECTOR_SHUFFLE:
13714     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13715       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13716       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13717     }
13718     break;
13719   case ISD::STORE: {
13720 
13721     EVT Op1VT = N->getOperand(1).getValueType();
13722     unsigned Opcode = N->getOperand(1).getOpcode();
13723 
13724     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13725       SDValue Val= combineStoreFPToInt(N, DCI);
13726       if (Val)
13727         return Val;
13728     }
13729 
13730     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13731       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13732       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13733       if (Val)
13734         return Val;
13735     }
13736 
13737     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13738     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13739         N->getOperand(1).getNode()->hasOneUse() &&
13740         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13741          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13742 
13743       // STBRX can only handle simple types and it makes no sense to store less
13744       // two bytes in byte-reversed order.
13745       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13746       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13747         break;
13748 
13749       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13750       // Do an any-extend to 32-bits if this is a half-word input.
13751       if (BSwapOp.getValueType() == MVT::i16)
13752         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13753 
13754       // If the type of BSWAP operand is wider than stored memory width
13755       // it need to be shifted to the right side before STBRX.
13756       if (Op1VT.bitsGT(mVT)) {
13757         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13758         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13759                               DAG.getConstant(Shift, dl, MVT::i32));
13760         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13761         if (Op1VT == MVT::i64)
13762           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13763       }
13764 
13765       SDValue Ops[] = {
13766         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13767       };
13768       return
13769         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13770                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13771                                 cast<StoreSDNode>(N)->getMemOperand());
13772     }
13773 
13774     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13775     // So it can increase the chance of CSE constant construction.
13776     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13777         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13778       // Need to sign-extended to 64-bits to handle negative values.
13779       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13780       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13781                                     MemVT.getSizeInBits());
13782       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13783 
13784       // DAG.getTruncStore() can't be used here because it doesn't accept
13785       // the general (base + offset) addressing mode.
13786       // So we use UpdateNodeOperands and setTruncatingStore instead.
13787       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13788                              N->getOperand(3));
13789       cast<StoreSDNode>(N)->setTruncatingStore(true);
13790       return SDValue(N, 0);
13791     }
13792 
13793     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13794     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13795     if (Op1VT.isSimple()) {
13796       MVT StoreVT = Op1VT.getSimpleVT();
13797       if (Subtarget.needsSwapsForVSXMemOps() &&
13798           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13799            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13800         return expandVSXStoreForLE(N, DCI);
13801     }
13802     break;
13803   }
13804   case ISD::LOAD: {
13805     LoadSDNode *LD = cast<LoadSDNode>(N);
13806     EVT VT = LD->getValueType(0);
13807 
13808     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13809     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13810     if (VT.isSimple()) {
13811       MVT LoadVT = VT.getSimpleVT();
13812       if (Subtarget.needsSwapsForVSXMemOps() &&
13813           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13814            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13815         return expandVSXLoadForLE(N, DCI);
13816     }
13817 
13818     // We sometimes end up with a 64-bit integer load, from which we extract
13819     // two single-precision floating-point numbers. This happens with
13820     // std::complex<float>, and other similar structures, because of the way we
13821     // canonicalize structure copies. However, if we lack direct moves,
13822     // then the final bitcasts from the extracted integer values to the
13823     // floating-point numbers turn into store/load pairs. Even with direct moves,
13824     // just loading the two floating-point numbers is likely better.
13825     auto ReplaceTwoFloatLoad = [&]() {
13826       if (VT != MVT::i64)
13827         return false;
13828 
13829       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13830           LD->isVolatile())
13831         return false;
13832 
13833       //  We're looking for a sequence like this:
13834       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13835       //      t16: i64 = srl t13, Constant:i32<32>
13836       //    t17: i32 = truncate t16
13837       //  t18: f32 = bitcast t17
13838       //    t19: i32 = truncate t13
13839       //  t20: f32 = bitcast t19
13840 
13841       if (!LD->hasNUsesOfValue(2, 0))
13842         return false;
13843 
13844       auto UI = LD->use_begin();
13845       while (UI.getUse().getResNo() != 0) ++UI;
13846       SDNode *Trunc = *UI++;
13847       while (UI.getUse().getResNo() != 0) ++UI;
13848       SDNode *RightShift = *UI;
13849       if (Trunc->getOpcode() != ISD::TRUNCATE)
13850         std::swap(Trunc, RightShift);
13851 
13852       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13853           Trunc->getValueType(0) != MVT::i32 ||
13854           !Trunc->hasOneUse())
13855         return false;
13856       if (RightShift->getOpcode() != ISD::SRL ||
13857           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13858           RightShift->getConstantOperandVal(1) != 32 ||
13859           !RightShift->hasOneUse())
13860         return false;
13861 
13862       SDNode *Trunc2 = *RightShift->use_begin();
13863       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13864           Trunc2->getValueType(0) != MVT::i32 ||
13865           !Trunc2->hasOneUse())
13866         return false;
13867 
13868       SDNode *Bitcast = *Trunc->use_begin();
13869       SDNode *Bitcast2 = *Trunc2->use_begin();
13870 
13871       if (Bitcast->getOpcode() != ISD::BITCAST ||
13872           Bitcast->getValueType(0) != MVT::f32)
13873         return false;
13874       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13875           Bitcast2->getValueType(0) != MVT::f32)
13876         return false;
13877 
13878       if (Subtarget.isLittleEndian())
13879         std::swap(Bitcast, Bitcast2);
13880 
13881       // Bitcast has the second float (in memory-layout order) and Bitcast2
13882       // has the first one.
13883 
13884       SDValue BasePtr = LD->getBasePtr();
13885       if (LD->isIndexed()) {
13886         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13887                "Non-pre-inc AM on PPC?");
13888         BasePtr =
13889           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13890                       LD->getOffset());
13891       }
13892 
13893       auto MMOFlags =
13894           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13895       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13896                                       LD->getPointerInfo(), LD->getAlignment(),
13897                                       MMOFlags, LD->getAAInfo());
13898       SDValue AddPtr =
13899         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13900                     BasePtr, DAG.getIntPtrConstant(4, dl));
13901       SDValue FloatLoad2 = DAG.getLoad(
13902           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13903           LD->getPointerInfo().getWithOffset(4),
13904           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13905 
13906       if (LD->isIndexed()) {
13907         // Note that DAGCombine should re-form any pre-increment load(s) from
13908         // what is produced here if that makes sense.
13909         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13910       }
13911 
13912       DCI.CombineTo(Bitcast2, FloatLoad);
13913       DCI.CombineTo(Bitcast, FloatLoad2);
13914 
13915       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13916                                     SDValue(FloatLoad2.getNode(), 1));
13917       return true;
13918     };
13919 
13920     if (ReplaceTwoFloatLoad())
13921       return SDValue(N, 0);
13922 
13923     EVT MemVT = LD->getMemoryVT();
13924     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13925     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13926     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13927     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13928     if (LD->isUnindexed() && VT.isVector() &&
13929         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13930           // P8 and later hardware should just use LOAD.
13931           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13932                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13933          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13934           LD->getAlignment() >= ScalarABIAlignment)) &&
13935         LD->getAlignment() < ABIAlignment) {
13936       // This is a type-legal unaligned Altivec or QPX load.
13937       SDValue Chain = LD->getChain();
13938       SDValue Ptr = LD->getBasePtr();
13939       bool isLittleEndian = Subtarget.isLittleEndian();
13940 
13941       // This implements the loading of unaligned vectors as described in
13942       // the venerable Apple Velocity Engine overview. Specifically:
13943       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13944       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13945       //
13946       // The general idea is to expand a sequence of one or more unaligned
13947       // loads into an alignment-based permutation-control instruction (lvsl
13948       // or lvsr), a series of regular vector loads (which always truncate
13949       // their input address to an aligned address), and a series of
13950       // permutations.  The results of these permutations are the requested
13951       // loaded values.  The trick is that the last "extra" load is not taken
13952       // from the address you might suspect (sizeof(vector) bytes after the
13953       // last requested load), but rather sizeof(vector) - 1 bytes after the
13954       // last requested vector. The point of this is to avoid a page fault if
13955       // the base address happened to be aligned. This works because if the
13956       // base address is aligned, then adding less than a full vector length
13957       // will cause the last vector in the sequence to be (re)loaded.
13958       // Otherwise, the next vector will be fetched as you might suspect was
13959       // necessary.
13960 
13961       // We might be able to reuse the permutation generation from
13962       // a different base address offset from this one by an aligned amount.
13963       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13964       // optimization later.
13965       Intrinsic::ID Intr, IntrLD, IntrPerm;
13966       MVT PermCntlTy, PermTy, LDTy;
13967       if (Subtarget.hasAltivec()) {
13968         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13969                                  Intrinsic::ppc_altivec_lvsl;
13970         IntrLD = Intrinsic::ppc_altivec_lvx;
13971         IntrPerm = Intrinsic::ppc_altivec_vperm;
13972         PermCntlTy = MVT::v16i8;
13973         PermTy = MVT::v4i32;
13974         LDTy = MVT::v4i32;
13975       } else {
13976         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13977                                        Intrinsic::ppc_qpx_qvlpcls;
13978         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13979                                        Intrinsic::ppc_qpx_qvlfs;
13980         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13981         PermCntlTy = MVT::v4f64;
13982         PermTy = MVT::v4f64;
13983         LDTy = MemVT.getSimpleVT();
13984       }
13985 
13986       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13987 
13988       // Create the new MMO for the new base load. It is like the original MMO,
13989       // but represents an area in memory almost twice the vector size centered
13990       // on the original address. If the address is unaligned, we might start
13991       // reading up to (sizeof(vector)-1) bytes below the address of the
13992       // original unaligned load.
13993       MachineFunction &MF = DAG.getMachineFunction();
13994       MachineMemOperand *BaseMMO =
13995         MF.getMachineMemOperand(LD->getMemOperand(),
13996                                 -(long)MemVT.getStoreSize()+1,
13997                                 2*MemVT.getStoreSize()-1);
13998 
13999       // Create the new base load.
14000       SDValue LDXIntID =
14001           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14002       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14003       SDValue BaseLoad =
14004         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14005                                 DAG.getVTList(PermTy, MVT::Other),
14006                                 BaseLoadOps, LDTy, BaseMMO);
14007 
14008       // Note that the value of IncOffset (which is provided to the next
14009       // load's pointer info offset value, and thus used to calculate the
14010       // alignment), and the value of IncValue (which is actually used to
14011       // increment the pointer value) are different! This is because we
14012       // require the next load to appear to be aligned, even though it
14013       // is actually offset from the base pointer by a lesser amount.
14014       int IncOffset = VT.getSizeInBits() / 8;
14015       int IncValue = IncOffset;
14016 
14017       // Walk (both up and down) the chain looking for another load at the real
14018       // (aligned) offset (the alignment of the other load does not matter in
14019       // this case). If found, then do not use the offset reduction trick, as
14020       // that will prevent the loads from being later combined (as they would
14021       // otherwise be duplicates).
14022       if (!findConsecutiveLoad(LD, DAG))
14023         --IncValue;
14024 
14025       SDValue Increment =
14026           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14027       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14028 
14029       MachineMemOperand *ExtraMMO =
14030         MF.getMachineMemOperand(LD->getMemOperand(),
14031                                 1, 2*MemVT.getStoreSize()-1);
14032       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14033       SDValue ExtraLoad =
14034         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14035                                 DAG.getVTList(PermTy, MVT::Other),
14036                                 ExtraLoadOps, LDTy, ExtraMMO);
14037 
14038       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14039         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14040 
14041       // Because vperm has a big-endian bias, we must reverse the order
14042       // of the input vectors and complement the permute control vector
14043       // when generating little endian code.  We have already handled the
14044       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14045       // and ExtraLoad here.
14046       SDValue Perm;
14047       if (isLittleEndian)
14048         Perm = BuildIntrinsicOp(IntrPerm,
14049                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14050       else
14051         Perm = BuildIntrinsicOp(IntrPerm,
14052                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14053 
14054       if (VT != PermTy)
14055         Perm = Subtarget.hasAltivec() ?
14056                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14057                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14058                                DAG.getTargetConstant(1, dl, MVT::i64));
14059                                // second argument is 1 because this rounding
14060                                // is always exact.
14061 
14062       // The output of the permutation is our loaded result, the TokenFactor is
14063       // our new chain.
14064       DCI.CombineTo(N, Perm, TF);
14065       return SDValue(N, 0);
14066     }
14067     }
14068     break;
14069     case ISD::INTRINSIC_WO_CHAIN: {
14070       bool isLittleEndian = Subtarget.isLittleEndian();
14071       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14072       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14073                                            : Intrinsic::ppc_altivec_lvsl);
14074       if ((IID == Intr ||
14075            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14076            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14077         N->getOperand(1)->getOpcode() == ISD::ADD) {
14078         SDValue Add = N->getOperand(1);
14079 
14080         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14081                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14082 
14083         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14084                                   APInt::getAllOnesValue(Bits /* alignment */)
14085                                       .zext(Add.getScalarValueSizeInBits()))) {
14086           SDNode *BasePtr = Add->getOperand(0).getNode();
14087           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14088                                     UE = BasePtr->use_end();
14089                UI != UE; ++UI) {
14090             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14091                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14092               // We've found another LVSL/LVSR, and this address is an aligned
14093               // multiple of that one. The results will be the same, so use the
14094               // one we've just found instead.
14095 
14096               return SDValue(*UI, 0);
14097             }
14098           }
14099         }
14100 
14101         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14102           SDNode *BasePtr = Add->getOperand(0).getNode();
14103           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14104                UE = BasePtr->use_end(); UI != UE; ++UI) {
14105             if (UI->getOpcode() == ISD::ADD &&
14106                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14107                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14108                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14109                 (1ULL << Bits) == 0) {
14110               SDNode *OtherAdd = *UI;
14111               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14112                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14113                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14114                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14115                   return SDValue(*VI, 0);
14116                 }
14117               }
14118             }
14119           }
14120         }
14121       }
14122 
14123       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14124       // Expose the vabsduw/h/b opportunity for down stream
14125       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14126           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14127            IID == Intrinsic::ppc_altivec_vmaxsh ||
14128            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14129         SDValue V1 = N->getOperand(1);
14130         SDValue V2 = N->getOperand(2);
14131         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14132              V1.getSimpleValueType() == MVT::v8i16 ||
14133              V1.getSimpleValueType() == MVT::v16i8) &&
14134             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14135           // (0-a, a)
14136           if (V1.getOpcode() == ISD::SUB &&
14137               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14138               V1.getOperand(1) == V2) {
14139             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14140           }
14141           // (a, 0-a)
14142           if (V2.getOpcode() == ISD::SUB &&
14143               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14144               V2.getOperand(1) == V1) {
14145             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14146           }
14147           // (x-y, y-x)
14148           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14149               V1.getOperand(0) == V2.getOperand(1) &&
14150               V1.getOperand(1) == V2.getOperand(0)) {
14151             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14152           }
14153         }
14154       }
14155     }
14156 
14157     break;
14158   case ISD::INTRINSIC_W_CHAIN:
14159     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14160     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14161     if (Subtarget.needsSwapsForVSXMemOps()) {
14162       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14163       default:
14164         break;
14165       case Intrinsic::ppc_vsx_lxvw4x:
14166       case Intrinsic::ppc_vsx_lxvd2x:
14167         return expandVSXLoadForLE(N, DCI);
14168       }
14169     }
14170     break;
14171   case ISD::INTRINSIC_VOID:
14172     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14173     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14174     if (Subtarget.needsSwapsForVSXMemOps()) {
14175       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14176       default:
14177         break;
14178       case Intrinsic::ppc_vsx_stxvw4x:
14179       case Intrinsic::ppc_vsx_stxvd2x:
14180         return expandVSXStoreForLE(N, DCI);
14181       }
14182     }
14183     break;
14184   case ISD::BSWAP:
14185     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14186     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14187         N->getOperand(0).hasOneUse() &&
14188         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14189          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14190           N->getValueType(0) == MVT::i64))) {
14191       SDValue Load = N->getOperand(0);
14192       LoadSDNode *LD = cast<LoadSDNode>(Load);
14193       // Create the byte-swapping load.
14194       SDValue Ops[] = {
14195         LD->getChain(),    // Chain
14196         LD->getBasePtr(),  // Ptr
14197         DAG.getValueType(N->getValueType(0)) // VT
14198       };
14199       SDValue BSLoad =
14200         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14201                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14202                                               MVT::i64 : MVT::i32, MVT::Other),
14203                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14204 
14205       // If this is an i16 load, insert the truncate.
14206       SDValue ResVal = BSLoad;
14207       if (N->getValueType(0) == MVT::i16)
14208         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14209 
14210       // First, combine the bswap away.  This makes the value produced by the
14211       // load dead.
14212       DCI.CombineTo(N, ResVal);
14213 
14214       // Next, combine the load away, we give it a bogus result value but a real
14215       // chain result.  The result value is dead because the bswap is dead.
14216       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14217 
14218       // Return N so it doesn't get rechecked!
14219       return SDValue(N, 0);
14220     }
14221     break;
14222   case PPCISD::VCMP:
14223     // If a VCMPo node already exists with exactly the same operands as this
14224     // node, use its result instead of this node (VCMPo computes both a CR6 and
14225     // a normal output).
14226     //
14227     if (!N->getOperand(0).hasOneUse() &&
14228         !N->getOperand(1).hasOneUse() &&
14229         !N->getOperand(2).hasOneUse()) {
14230 
14231       // Scan all of the users of the LHS, looking for VCMPo's that match.
14232       SDNode *VCMPoNode = nullptr;
14233 
14234       SDNode *LHSN = N->getOperand(0).getNode();
14235       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14236            UI != E; ++UI)
14237         if (UI->getOpcode() == PPCISD::VCMPo &&
14238             UI->getOperand(1) == N->getOperand(1) &&
14239             UI->getOperand(2) == N->getOperand(2) &&
14240             UI->getOperand(0) == N->getOperand(0)) {
14241           VCMPoNode = *UI;
14242           break;
14243         }
14244 
14245       // If there is no VCMPo node, or if the flag value has a single use, don't
14246       // transform this.
14247       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14248         break;
14249 
14250       // Look at the (necessarily single) use of the flag value.  If it has a
14251       // chain, this transformation is more complex.  Note that multiple things
14252       // could use the value result, which we should ignore.
14253       SDNode *FlagUser = nullptr;
14254       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14255            FlagUser == nullptr; ++UI) {
14256         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14257         SDNode *User = *UI;
14258         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14259           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14260             FlagUser = User;
14261             break;
14262           }
14263         }
14264       }
14265 
14266       // If the user is a MFOCRF instruction, we know this is safe.
14267       // Otherwise we give up for right now.
14268       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14269         return SDValue(VCMPoNode, 0);
14270     }
14271     break;
14272   case ISD::BRCOND: {
14273     SDValue Cond = N->getOperand(1);
14274     SDValue Target = N->getOperand(2);
14275 
14276     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14277         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14278           Intrinsic::loop_decrement) {
14279 
14280       // We now need to make the intrinsic dead (it cannot be instruction
14281       // selected).
14282       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14283       assert(Cond.getNode()->hasOneUse() &&
14284              "Counter decrement has more than one use");
14285 
14286       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14287                          N->getOperand(0), Target);
14288     }
14289   }
14290   break;
14291   case ISD::BR_CC: {
14292     // If this is a branch on an altivec predicate comparison, lower this so
14293     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14294     // lowering is done pre-legalize, because the legalizer lowers the predicate
14295     // compare down to code that is difficult to reassemble.
14296     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14297     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14298 
14299     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14300     // value. If so, pass-through the AND to get to the intrinsic.
14301     if (LHS.getOpcode() == ISD::AND &&
14302         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14303         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14304           Intrinsic::loop_decrement &&
14305         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14306         !isNullConstant(LHS.getOperand(1)))
14307       LHS = LHS.getOperand(0);
14308 
14309     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14310         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14311           Intrinsic::loop_decrement &&
14312         isa<ConstantSDNode>(RHS)) {
14313       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14314              "Counter decrement comparison is not EQ or NE");
14315 
14316       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14317       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14318                     (CC == ISD::SETNE && !Val);
14319 
14320       // We now need to make the intrinsic dead (it cannot be instruction
14321       // selected).
14322       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14323       assert(LHS.getNode()->hasOneUse() &&
14324              "Counter decrement has more than one use");
14325 
14326       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14327                          N->getOperand(0), N->getOperand(4));
14328     }
14329 
14330     int CompareOpc;
14331     bool isDot;
14332 
14333     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14334         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14335         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14336       assert(isDot && "Can't compare against a vector result!");
14337 
14338       // If this is a comparison against something other than 0/1, then we know
14339       // that the condition is never/always true.
14340       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14341       if (Val != 0 && Val != 1) {
14342         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14343           return N->getOperand(0);
14344         // Always !=, turn it into an unconditional branch.
14345         return DAG.getNode(ISD::BR, dl, MVT::Other,
14346                            N->getOperand(0), N->getOperand(4));
14347       }
14348 
14349       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14350 
14351       // Create the PPCISD altivec 'dot' comparison node.
14352       SDValue Ops[] = {
14353         LHS.getOperand(2),  // LHS of compare
14354         LHS.getOperand(3),  // RHS of compare
14355         DAG.getConstant(CompareOpc, dl, MVT::i32)
14356       };
14357       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14358       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14359 
14360       // Unpack the result based on how the target uses it.
14361       PPC::Predicate CompOpc;
14362       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14363       default:  // Can't happen, don't crash on invalid number though.
14364       case 0:   // Branch on the value of the EQ bit of CR6.
14365         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14366         break;
14367       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14368         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14369         break;
14370       case 2:   // Branch on the value of the LT bit of CR6.
14371         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14372         break;
14373       case 3:   // Branch on the inverted value of the LT bit of CR6.
14374         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14375         break;
14376       }
14377 
14378       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14379                          DAG.getConstant(CompOpc, dl, MVT::i32),
14380                          DAG.getRegister(PPC::CR6, MVT::i32),
14381                          N->getOperand(4), CompNode.getValue(1));
14382     }
14383     break;
14384   }
14385   case ISD::BUILD_VECTOR:
14386     return DAGCombineBuildVector(N, DCI);
14387   case ISD::ABS:
14388     return combineABS(N, DCI);
14389   case ISD::VSELECT:
14390     return combineVSelect(N, DCI);
14391   }
14392 
14393   return SDValue();
14394 }
14395 
14396 SDValue
14397 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14398                                  SelectionDAG &DAG,
14399                                  SmallVectorImpl<SDNode *> &Created) const {
14400   // fold (sdiv X, pow2)
14401   EVT VT = N->getValueType(0);
14402   if (VT == MVT::i64 && !Subtarget.isPPC64())
14403     return SDValue();
14404   if ((VT != MVT::i32 && VT != MVT::i64) ||
14405       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14406     return SDValue();
14407 
14408   SDLoc DL(N);
14409   SDValue N0 = N->getOperand(0);
14410 
14411   bool IsNegPow2 = (-Divisor).isPowerOf2();
14412   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14413   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14414 
14415   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14416   Created.push_back(Op.getNode());
14417 
14418   if (IsNegPow2) {
14419     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14420     Created.push_back(Op.getNode());
14421   }
14422 
14423   return Op;
14424 }
14425 
14426 //===----------------------------------------------------------------------===//
14427 // Inline Assembly Support
14428 //===----------------------------------------------------------------------===//
14429 
14430 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14431                                                       KnownBits &Known,
14432                                                       const APInt &DemandedElts,
14433                                                       const SelectionDAG &DAG,
14434                                                       unsigned Depth) const {
14435   Known.resetAll();
14436   switch (Op.getOpcode()) {
14437   default: break;
14438   case PPCISD::LBRX: {
14439     // lhbrx is known to have the top bits cleared out.
14440     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14441       Known.Zero = 0xFFFF0000;
14442     break;
14443   }
14444   case ISD::INTRINSIC_WO_CHAIN: {
14445     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14446     default: break;
14447     case Intrinsic::ppc_altivec_vcmpbfp_p:
14448     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14449     case Intrinsic::ppc_altivec_vcmpequb_p:
14450     case Intrinsic::ppc_altivec_vcmpequh_p:
14451     case Intrinsic::ppc_altivec_vcmpequw_p:
14452     case Intrinsic::ppc_altivec_vcmpequd_p:
14453     case Intrinsic::ppc_altivec_vcmpgefp_p:
14454     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14455     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14456     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14457     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14458     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14459     case Intrinsic::ppc_altivec_vcmpgtub_p:
14460     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14461     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14462     case Intrinsic::ppc_altivec_vcmpgtud_p:
14463       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14464       break;
14465     }
14466   }
14467   }
14468 }
14469 
14470 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14471   switch (Subtarget.getCPUDirective()) {
14472   default: break;
14473   case PPC::DIR_970:
14474   case PPC::DIR_PWR4:
14475   case PPC::DIR_PWR5:
14476   case PPC::DIR_PWR5X:
14477   case PPC::DIR_PWR6:
14478   case PPC::DIR_PWR6X:
14479   case PPC::DIR_PWR7:
14480   case PPC::DIR_PWR8:
14481   case PPC::DIR_PWR9:
14482   case PPC::DIR_PWR_FUTURE: {
14483     if (!ML)
14484       break;
14485 
14486     if (!DisableInnermostLoopAlign32) {
14487       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14488       // so that we can decrease cache misses and branch-prediction misses.
14489       // Actual alignment of the loop will depend on the hotness check and other
14490       // logic in alignBlocks.
14491       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14492         return Align(32);
14493     }
14494 
14495     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14496 
14497     // For small loops (between 5 and 8 instructions), align to a 32-byte
14498     // boundary so that the entire loop fits in one instruction-cache line.
14499     uint64_t LoopSize = 0;
14500     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14501       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14502         LoopSize += TII->getInstSizeInBytes(*J);
14503         if (LoopSize > 32)
14504           break;
14505       }
14506 
14507     if (LoopSize > 16 && LoopSize <= 32)
14508       return Align(32);
14509 
14510     break;
14511   }
14512   }
14513 
14514   return TargetLowering::getPrefLoopAlignment(ML);
14515 }
14516 
14517 /// getConstraintType - Given a constraint, return the type of
14518 /// constraint it is for this target.
14519 PPCTargetLowering::ConstraintType
14520 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14521   if (Constraint.size() == 1) {
14522     switch (Constraint[0]) {
14523     default: break;
14524     case 'b':
14525     case 'r':
14526     case 'f':
14527     case 'd':
14528     case 'v':
14529     case 'y':
14530       return C_RegisterClass;
14531     case 'Z':
14532       // FIXME: While Z does indicate a memory constraint, it specifically
14533       // indicates an r+r address (used in conjunction with the 'y' modifier
14534       // in the replacement string). Currently, we're forcing the base
14535       // register to be r0 in the asm printer (which is interpreted as zero)
14536       // and forming the complete address in the second register. This is
14537       // suboptimal.
14538       return C_Memory;
14539     }
14540   } else if (Constraint == "wc") { // individual CR bits.
14541     return C_RegisterClass;
14542   } else if (Constraint == "wa" || Constraint == "wd" ||
14543              Constraint == "wf" || Constraint == "ws" ||
14544              Constraint == "wi" || Constraint == "ww") {
14545     return C_RegisterClass; // VSX registers.
14546   }
14547   return TargetLowering::getConstraintType(Constraint);
14548 }
14549 
14550 /// Examine constraint type and operand type and determine a weight value.
14551 /// This object must already have been set up with the operand type
14552 /// and the current alternative constraint selected.
14553 TargetLowering::ConstraintWeight
14554 PPCTargetLowering::getSingleConstraintMatchWeight(
14555     AsmOperandInfo &info, const char *constraint) const {
14556   ConstraintWeight weight = CW_Invalid;
14557   Value *CallOperandVal = info.CallOperandVal;
14558     // If we don't have a value, we can't do a match,
14559     // but allow it at the lowest weight.
14560   if (!CallOperandVal)
14561     return CW_Default;
14562   Type *type = CallOperandVal->getType();
14563 
14564   // Look at the constraint type.
14565   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14566     return CW_Register; // an individual CR bit.
14567   else if ((StringRef(constraint) == "wa" ||
14568             StringRef(constraint) == "wd" ||
14569             StringRef(constraint) == "wf") &&
14570            type->isVectorTy())
14571     return CW_Register;
14572   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14573     return CW_Register; // just hold 64-bit integers data.
14574   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14575     return CW_Register;
14576   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14577     return CW_Register;
14578 
14579   switch (*constraint) {
14580   default:
14581     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14582     break;
14583   case 'b':
14584     if (type->isIntegerTy())
14585       weight = CW_Register;
14586     break;
14587   case 'f':
14588     if (type->isFloatTy())
14589       weight = CW_Register;
14590     break;
14591   case 'd':
14592     if (type->isDoubleTy())
14593       weight = CW_Register;
14594     break;
14595   case 'v':
14596     if (type->isVectorTy())
14597       weight = CW_Register;
14598     break;
14599   case 'y':
14600     weight = CW_Register;
14601     break;
14602   case 'Z':
14603     weight = CW_Memory;
14604     break;
14605   }
14606   return weight;
14607 }
14608 
14609 std::pair<unsigned, const TargetRegisterClass *>
14610 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14611                                                 StringRef Constraint,
14612                                                 MVT VT) const {
14613   if (Constraint.size() == 1) {
14614     // GCC RS6000 Constraint Letters
14615     switch (Constraint[0]) {
14616     case 'b':   // R1-R31
14617       if (VT == MVT::i64 && Subtarget.isPPC64())
14618         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14619       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14620     case 'r':   // R0-R31
14621       if (VT == MVT::i64 && Subtarget.isPPC64())
14622         return std::make_pair(0U, &PPC::G8RCRegClass);
14623       return std::make_pair(0U, &PPC::GPRCRegClass);
14624     // 'd' and 'f' constraints are both defined to be "the floating point
14625     // registers", where one is for 32-bit and the other for 64-bit. We don't
14626     // really care overly much here so just give them all the same reg classes.
14627     case 'd':
14628     case 'f':
14629       if (Subtarget.hasSPE()) {
14630         if (VT == MVT::f32 || VT == MVT::i32)
14631           return std::make_pair(0U, &PPC::GPRCRegClass);
14632         if (VT == MVT::f64 || VT == MVT::i64)
14633           return std::make_pair(0U, &PPC::SPERCRegClass);
14634       } else {
14635         if (VT == MVT::f32 || VT == MVT::i32)
14636           return std::make_pair(0U, &PPC::F4RCRegClass);
14637         if (VT == MVT::f64 || VT == MVT::i64)
14638           return std::make_pair(0U, &PPC::F8RCRegClass);
14639         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14640           return std::make_pair(0U, &PPC::QFRCRegClass);
14641         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14642           return std::make_pair(0U, &PPC::QSRCRegClass);
14643       }
14644       break;
14645     case 'v':
14646       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14647         return std::make_pair(0U, &PPC::QFRCRegClass);
14648       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14649         return std::make_pair(0U, &PPC::QSRCRegClass);
14650       if (Subtarget.hasAltivec())
14651         return std::make_pair(0U, &PPC::VRRCRegClass);
14652       break;
14653     case 'y':   // crrc
14654       return std::make_pair(0U, &PPC::CRRCRegClass);
14655     }
14656   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14657     // An individual CR bit.
14658     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14659   } else if ((Constraint == "wa" || Constraint == "wd" ||
14660              Constraint == "wf" || Constraint == "wi") &&
14661              Subtarget.hasVSX()) {
14662     return std::make_pair(0U, &PPC::VSRCRegClass);
14663   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14664     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14665       return std::make_pair(0U, &PPC::VSSRCRegClass);
14666     else
14667       return std::make_pair(0U, &PPC::VSFRCRegClass);
14668   }
14669 
14670   // If we name a VSX register, we can't defer to the base class because it
14671   // will not recognize the correct register (their names will be VSL{0-31}
14672   // and V{0-31} so they won't match). So we match them here.
14673   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
14674     int VSNum = atoi(Constraint.data() + 3);
14675     assert(VSNum >= 0 && VSNum <= 63 &&
14676            "Attempted to access a vsr out of range");
14677     if (VSNum < 32)
14678       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
14679     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
14680   }
14681   std::pair<unsigned, const TargetRegisterClass *> R =
14682       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14683 
14684   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14685   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14686   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14687   // register.
14688   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14689   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14690   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14691       PPC::GPRCRegClass.contains(R.first))
14692     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14693                             PPC::sub_32, &PPC::G8RCRegClass),
14694                           &PPC::G8RCRegClass);
14695 
14696   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14697   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14698     R.first = PPC::CR0;
14699     R.second = &PPC::CRRCRegClass;
14700   }
14701 
14702   return R;
14703 }
14704 
14705 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14706 /// vector.  If it is invalid, don't add anything to Ops.
14707 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14708                                                      std::string &Constraint,
14709                                                      std::vector<SDValue>&Ops,
14710                                                      SelectionDAG &DAG) const {
14711   SDValue Result;
14712 
14713   // Only support length 1 constraints.
14714   if (Constraint.length() > 1) return;
14715 
14716   char Letter = Constraint[0];
14717   switch (Letter) {
14718   default: break;
14719   case 'I':
14720   case 'J':
14721   case 'K':
14722   case 'L':
14723   case 'M':
14724   case 'N':
14725   case 'O':
14726   case 'P': {
14727     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14728     if (!CST) return; // Must be an immediate to match.
14729     SDLoc dl(Op);
14730     int64_t Value = CST->getSExtValue();
14731     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14732                          // numbers are printed as such.
14733     switch (Letter) {
14734     default: llvm_unreachable("Unknown constraint letter!");
14735     case 'I':  // "I" is a signed 16-bit constant.
14736       if (isInt<16>(Value))
14737         Result = DAG.getTargetConstant(Value, dl, TCVT);
14738       break;
14739     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14740       if (isShiftedUInt<16, 16>(Value))
14741         Result = DAG.getTargetConstant(Value, dl, TCVT);
14742       break;
14743     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14744       if (isShiftedInt<16, 16>(Value))
14745         Result = DAG.getTargetConstant(Value, dl, TCVT);
14746       break;
14747     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14748       if (isUInt<16>(Value))
14749         Result = DAG.getTargetConstant(Value, dl, TCVT);
14750       break;
14751     case 'M':  // "M" is a constant that is greater than 31.
14752       if (Value > 31)
14753         Result = DAG.getTargetConstant(Value, dl, TCVT);
14754       break;
14755     case 'N':  // "N" is a positive constant that is an exact power of two.
14756       if (Value > 0 && isPowerOf2_64(Value))
14757         Result = DAG.getTargetConstant(Value, dl, TCVT);
14758       break;
14759     case 'O':  // "O" is the constant zero.
14760       if (Value == 0)
14761         Result = DAG.getTargetConstant(Value, dl, TCVT);
14762       break;
14763     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14764       if (isInt<16>(-Value))
14765         Result = DAG.getTargetConstant(Value, dl, TCVT);
14766       break;
14767     }
14768     break;
14769   }
14770   }
14771 
14772   if (Result.getNode()) {
14773     Ops.push_back(Result);
14774     return;
14775   }
14776 
14777   // Handle standard constraint letters.
14778   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14779 }
14780 
14781 // isLegalAddressingMode - Return true if the addressing mode represented
14782 // by AM is legal for this target, for a load/store of the specified type.
14783 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14784                                               const AddrMode &AM, Type *Ty,
14785                                               unsigned AS, Instruction *I) const {
14786   // PPC does not allow r+i addressing modes for vectors!
14787   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14788     return false;
14789 
14790   // PPC allows a sign-extended 16-bit immediate field.
14791   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14792     return false;
14793 
14794   // No global is ever allowed as a base.
14795   if (AM.BaseGV)
14796     return false;
14797 
14798   // PPC only support r+r,
14799   switch (AM.Scale) {
14800   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14801     break;
14802   case 1:
14803     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14804       return false;
14805     // Otherwise we have r+r or r+i.
14806     break;
14807   case 2:
14808     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14809       return false;
14810     // Allow 2*r as r+r.
14811     break;
14812   default:
14813     // No other scales are supported.
14814     return false;
14815   }
14816 
14817   return true;
14818 }
14819 
14820 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14821                                            SelectionDAG &DAG) const {
14822   MachineFunction &MF = DAG.getMachineFunction();
14823   MachineFrameInfo &MFI = MF.getFrameInfo();
14824   MFI.setReturnAddressIsTaken(true);
14825 
14826   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14827     return SDValue();
14828 
14829   SDLoc dl(Op);
14830   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14831 
14832   // Make sure the function does not optimize away the store of the RA to
14833   // the stack.
14834   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14835   FuncInfo->setLRStoreRequired();
14836   bool isPPC64 = Subtarget.isPPC64();
14837   auto PtrVT = getPointerTy(MF.getDataLayout());
14838 
14839   if (Depth > 0) {
14840     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14841     SDValue Offset =
14842         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14843                         isPPC64 ? MVT::i64 : MVT::i32);
14844     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14845                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14846                        MachinePointerInfo());
14847   }
14848 
14849   // Just load the return address off the stack.
14850   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14851   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14852                      MachinePointerInfo());
14853 }
14854 
14855 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14856                                           SelectionDAG &DAG) const {
14857   SDLoc dl(Op);
14858   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14859 
14860   MachineFunction &MF = DAG.getMachineFunction();
14861   MachineFrameInfo &MFI = MF.getFrameInfo();
14862   MFI.setFrameAddressIsTaken(true);
14863 
14864   EVT PtrVT = getPointerTy(MF.getDataLayout());
14865   bool isPPC64 = PtrVT == MVT::i64;
14866 
14867   // Naked functions never have a frame pointer, and so we use r1. For all
14868   // other functions, this decision must be delayed until during PEI.
14869   unsigned FrameReg;
14870   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14871     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14872   else
14873     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14874 
14875   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14876                                          PtrVT);
14877   while (Depth--)
14878     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14879                             FrameAddr, MachinePointerInfo());
14880   return FrameAddr;
14881 }
14882 
14883 // FIXME? Maybe this could be a TableGen attribute on some registers and
14884 // this table could be generated automatically from RegInfo.
14885 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
14886                                               const MachineFunction &MF) const {
14887   bool isPPC64 = Subtarget.isPPC64();
14888 
14889   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
14890   if (!is64Bit && VT != LLT::scalar(32))
14891     report_fatal_error("Invalid register global variable type");
14892 
14893   Register Reg = StringSwitch<Register>(RegName)
14894                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14895                      .Case("r2", isPPC64 ? Register() : PPC::R2)
14896                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
14897                      .Default(Register());
14898 
14899   if (Reg)
14900     return Reg;
14901   report_fatal_error("Invalid register name global variable");
14902 }
14903 
14904 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14905   // 32-bit SVR4 ABI access everything as got-indirect.
14906   if (Subtarget.is32BitELFABI())
14907     return true;
14908 
14909   // AIX accesses everything indirectly through the TOC, which is similar to
14910   // the GOT.
14911   if (Subtarget.isAIXABI())
14912     return true;
14913 
14914   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14915   // If it is small or large code model, module locals are accessed
14916   // indirectly by loading their address from .toc/.got.
14917   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14918     return true;
14919 
14920   // JumpTable and BlockAddress are accessed as got-indirect.
14921   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14922     return true;
14923 
14924   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
14925     return Subtarget.isGVIndirectSymbol(G->getGlobal());
14926 
14927   return false;
14928 }
14929 
14930 bool
14931 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14932   // The PowerPC target isn't yet aware of offsets.
14933   return false;
14934 }
14935 
14936 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14937                                            const CallInst &I,
14938                                            MachineFunction &MF,
14939                                            unsigned Intrinsic) const {
14940   switch (Intrinsic) {
14941   case Intrinsic::ppc_qpx_qvlfd:
14942   case Intrinsic::ppc_qpx_qvlfs:
14943   case Intrinsic::ppc_qpx_qvlfcd:
14944   case Intrinsic::ppc_qpx_qvlfcs:
14945   case Intrinsic::ppc_qpx_qvlfiwa:
14946   case Intrinsic::ppc_qpx_qvlfiwz:
14947   case Intrinsic::ppc_altivec_lvx:
14948   case Intrinsic::ppc_altivec_lvxl:
14949   case Intrinsic::ppc_altivec_lvebx:
14950   case Intrinsic::ppc_altivec_lvehx:
14951   case Intrinsic::ppc_altivec_lvewx:
14952   case Intrinsic::ppc_vsx_lxvd2x:
14953   case Intrinsic::ppc_vsx_lxvw4x: {
14954     EVT VT;
14955     switch (Intrinsic) {
14956     case Intrinsic::ppc_altivec_lvebx:
14957       VT = MVT::i8;
14958       break;
14959     case Intrinsic::ppc_altivec_lvehx:
14960       VT = MVT::i16;
14961       break;
14962     case Intrinsic::ppc_altivec_lvewx:
14963       VT = MVT::i32;
14964       break;
14965     case Intrinsic::ppc_vsx_lxvd2x:
14966       VT = MVT::v2f64;
14967       break;
14968     case Intrinsic::ppc_qpx_qvlfd:
14969       VT = MVT::v4f64;
14970       break;
14971     case Intrinsic::ppc_qpx_qvlfs:
14972       VT = MVT::v4f32;
14973       break;
14974     case Intrinsic::ppc_qpx_qvlfcd:
14975       VT = MVT::v2f64;
14976       break;
14977     case Intrinsic::ppc_qpx_qvlfcs:
14978       VT = MVT::v2f32;
14979       break;
14980     default:
14981       VT = MVT::v4i32;
14982       break;
14983     }
14984 
14985     Info.opc = ISD::INTRINSIC_W_CHAIN;
14986     Info.memVT = VT;
14987     Info.ptrVal = I.getArgOperand(0);
14988     Info.offset = -VT.getStoreSize()+1;
14989     Info.size = 2*VT.getStoreSize()-1;
14990     Info.align = Align(1);
14991     Info.flags = MachineMemOperand::MOLoad;
14992     return true;
14993   }
14994   case Intrinsic::ppc_qpx_qvlfda:
14995   case Intrinsic::ppc_qpx_qvlfsa:
14996   case Intrinsic::ppc_qpx_qvlfcda:
14997   case Intrinsic::ppc_qpx_qvlfcsa:
14998   case Intrinsic::ppc_qpx_qvlfiwaa:
14999   case Intrinsic::ppc_qpx_qvlfiwza: {
15000     EVT VT;
15001     switch (Intrinsic) {
15002     case Intrinsic::ppc_qpx_qvlfda:
15003       VT = MVT::v4f64;
15004       break;
15005     case Intrinsic::ppc_qpx_qvlfsa:
15006       VT = MVT::v4f32;
15007       break;
15008     case Intrinsic::ppc_qpx_qvlfcda:
15009       VT = MVT::v2f64;
15010       break;
15011     case Intrinsic::ppc_qpx_qvlfcsa:
15012       VT = MVT::v2f32;
15013       break;
15014     default:
15015       VT = MVT::v4i32;
15016       break;
15017     }
15018 
15019     Info.opc = ISD::INTRINSIC_W_CHAIN;
15020     Info.memVT = VT;
15021     Info.ptrVal = I.getArgOperand(0);
15022     Info.offset = 0;
15023     Info.size = VT.getStoreSize();
15024     Info.align = Align(1);
15025     Info.flags = MachineMemOperand::MOLoad;
15026     return true;
15027   }
15028   case Intrinsic::ppc_qpx_qvstfd:
15029   case Intrinsic::ppc_qpx_qvstfs:
15030   case Intrinsic::ppc_qpx_qvstfcd:
15031   case Intrinsic::ppc_qpx_qvstfcs:
15032   case Intrinsic::ppc_qpx_qvstfiw:
15033   case Intrinsic::ppc_altivec_stvx:
15034   case Intrinsic::ppc_altivec_stvxl:
15035   case Intrinsic::ppc_altivec_stvebx:
15036   case Intrinsic::ppc_altivec_stvehx:
15037   case Intrinsic::ppc_altivec_stvewx:
15038   case Intrinsic::ppc_vsx_stxvd2x:
15039   case Intrinsic::ppc_vsx_stxvw4x: {
15040     EVT VT;
15041     switch (Intrinsic) {
15042     case Intrinsic::ppc_altivec_stvebx:
15043       VT = MVT::i8;
15044       break;
15045     case Intrinsic::ppc_altivec_stvehx:
15046       VT = MVT::i16;
15047       break;
15048     case Intrinsic::ppc_altivec_stvewx:
15049       VT = MVT::i32;
15050       break;
15051     case Intrinsic::ppc_vsx_stxvd2x:
15052       VT = MVT::v2f64;
15053       break;
15054     case Intrinsic::ppc_qpx_qvstfd:
15055       VT = MVT::v4f64;
15056       break;
15057     case Intrinsic::ppc_qpx_qvstfs:
15058       VT = MVT::v4f32;
15059       break;
15060     case Intrinsic::ppc_qpx_qvstfcd:
15061       VT = MVT::v2f64;
15062       break;
15063     case Intrinsic::ppc_qpx_qvstfcs:
15064       VT = MVT::v2f32;
15065       break;
15066     default:
15067       VT = MVT::v4i32;
15068       break;
15069     }
15070 
15071     Info.opc = ISD::INTRINSIC_VOID;
15072     Info.memVT = VT;
15073     Info.ptrVal = I.getArgOperand(1);
15074     Info.offset = -VT.getStoreSize()+1;
15075     Info.size = 2*VT.getStoreSize()-1;
15076     Info.align = Align(1);
15077     Info.flags = MachineMemOperand::MOStore;
15078     return true;
15079   }
15080   case Intrinsic::ppc_qpx_qvstfda:
15081   case Intrinsic::ppc_qpx_qvstfsa:
15082   case Intrinsic::ppc_qpx_qvstfcda:
15083   case Intrinsic::ppc_qpx_qvstfcsa:
15084   case Intrinsic::ppc_qpx_qvstfiwa: {
15085     EVT VT;
15086     switch (Intrinsic) {
15087     case Intrinsic::ppc_qpx_qvstfda:
15088       VT = MVT::v4f64;
15089       break;
15090     case Intrinsic::ppc_qpx_qvstfsa:
15091       VT = MVT::v4f32;
15092       break;
15093     case Intrinsic::ppc_qpx_qvstfcda:
15094       VT = MVT::v2f64;
15095       break;
15096     case Intrinsic::ppc_qpx_qvstfcsa:
15097       VT = MVT::v2f32;
15098       break;
15099     default:
15100       VT = MVT::v4i32;
15101       break;
15102     }
15103 
15104     Info.opc = ISD::INTRINSIC_VOID;
15105     Info.memVT = VT;
15106     Info.ptrVal = I.getArgOperand(1);
15107     Info.offset = 0;
15108     Info.size = VT.getStoreSize();
15109     Info.align = Align(1);
15110     Info.flags = MachineMemOperand::MOStore;
15111     return true;
15112   }
15113   default:
15114     break;
15115   }
15116 
15117   return false;
15118 }
15119 
15120 /// It returns EVT::Other if the type should be determined using generic
15121 /// target-independent logic.
15122 EVT PPCTargetLowering::getOptimalMemOpType(
15123     const MemOp &Op, const AttributeList &FuncAttributes) const {
15124   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15125     // When expanding a memset, require at least two QPX instructions to cover
15126     // the cost of loading the value to be stored from the constant pool.
15127     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15128         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15129         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15130       return MVT::v4f64;
15131     }
15132 
15133     // We should use Altivec/VSX loads and stores when available. For unaligned
15134     // addresses, unaligned VSX loads are only fast starting with the P8.
15135     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15136         (Op.isAligned(Align(16)) ||
15137          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15138       return MVT::v4i32;
15139   }
15140 
15141   if (Subtarget.isPPC64()) {
15142     return MVT::i64;
15143   }
15144 
15145   return MVT::i32;
15146 }
15147 
15148 /// Returns true if it is beneficial to convert a load of a constant
15149 /// to just the constant itself.
15150 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15151                                                           Type *Ty) const {
15152   assert(Ty->isIntegerTy());
15153 
15154   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15155   return !(BitSize == 0 || BitSize > 64);
15156 }
15157 
15158 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15159   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15160     return false;
15161   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15162   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15163   return NumBits1 == 64 && NumBits2 == 32;
15164 }
15165 
15166 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15167   if (!VT1.isInteger() || !VT2.isInteger())
15168     return false;
15169   unsigned NumBits1 = VT1.getSizeInBits();
15170   unsigned NumBits2 = VT2.getSizeInBits();
15171   return NumBits1 == 64 && NumBits2 == 32;
15172 }
15173 
15174 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15175   // Generally speaking, zexts are not free, but they are free when they can be
15176   // folded with other operations.
15177   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15178     EVT MemVT = LD->getMemoryVT();
15179     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15180          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15181         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15182          LD->getExtensionType() == ISD::ZEXTLOAD))
15183       return true;
15184   }
15185 
15186   // FIXME: Add other cases...
15187   //  - 32-bit shifts with a zext to i64
15188   //  - zext after ctlz, bswap, etc.
15189   //  - zext after and by a constant mask
15190 
15191   return TargetLowering::isZExtFree(Val, VT2);
15192 }
15193 
15194 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15195   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15196          "invalid fpext types");
15197   // Extending to float128 is not free.
15198   if (DestVT == MVT::f128)
15199     return false;
15200   return true;
15201 }
15202 
15203 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15204   return isInt<16>(Imm) || isUInt<16>(Imm);
15205 }
15206 
15207 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15208   return isInt<16>(Imm) || isUInt<16>(Imm);
15209 }
15210 
15211 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15212                                                        unsigned,
15213                                                        unsigned,
15214                                                        MachineMemOperand::Flags,
15215                                                        bool *Fast) const {
15216   if (DisablePPCUnaligned)
15217     return false;
15218 
15219   // PowerPC supports unaligned memory access for simple non-vector types.
15220   // Although accessing unaligned addresses is not as efficient as accessing
15221   // aligned addresses, it is generally more efficient than manual expansion,
15222   // and generally only traps for software emulation when crossing page
15223   // boundaries.
15224 
15225   if (!VT.isSimple())
15226     return false;
15227 
15228   if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess())
15229     return false;
15230 
15231   if (VT.getSimpleVT().isVector()) {
15232     if (Subtarget.hasVSX()) {
15233       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15234           VT != MVT::v4f32 && VT != MVT::v4i32)
15235         return false;
15236     } else {
15237       return false;
15238     }
15239   }
15240 
15241   if (VT == MVT::ppcf128)
15242     return false;
15243 
15244   if (Fast)
15245     *Fast = true;
15246 
15247   return true;
15248 }
15249 
15250 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15251                                                    EVT VT) const {
15252   VT = VT.getScalarType();
15253 
15254   if (!VT.isSimple())
15255     return false;
15256 
15257   switch (VT.getSimpleVT().SimpleTy) {
15258   case MVT::f32:
15259   case MVT::f64:
15260     return true;
15261   case MVT::f128:
15262     return (EnableQuadPrecision && Subtarget.hasP9Vector());
15263   default:
15264     break;
15265   }
15266 
15267   return false;
15268 }
15269 
15270 const MCPhysReg *
15271 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15272   // LR is a callee-save register, but we must treat it as clobbered by any call
15273   // site. Hence we include LR in the scratch registers, which are in turn added
15274   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15275   // to CTR, which is used by any indirect call.
15276   static const MCPhysReg ScratchRegs[] = {
15277     PPC::X12, PPC::LR8, PPC::CTR8, 0
15278   };
15279 
15280   return ScratchRegs;
15281 }
15282 
15283 unsigned PPCTargetLowering::getExceptionPointerRegister(
15284     const Constant *PersonalityFn) const {
15285   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15286 }
15287 
15288 unsigned PPCTargetLowering::getExceptionSelectorRegister(
15289     const Constant *PersonalityFn) const {
15290   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15291 }
15292 
15293 bool
15294 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15295                      EVT VT , unsigned DefinedValues) const {
15296   if (VT == MVT::v2i64)
15297     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15298 
15299   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15300     return true;
15301 
15302   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15303 }
15304 
15305 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15306   if (DisableILPPref || Subtarget.enableMachineScheduler())
15307     return TargetLowering::getSchedulingPreference(N);
15308 
15309   return Sched::ILP;
15310 }
15311 
15312 // Create a fast isel object.
15313 FastISel *
15314 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15315                                   const TargetLibraryInfo *LibInfo) const {
15316   return PPC::createFastISel(FuncInfo, LibInfo);
15317 }
15318 
15319 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15320   if (!Subtarget.isPPC64()) return;
15321 
15322   // Update IsSplitCSR in PPCFunctionInfo
15323   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15324   PFI->setIsSplitCSR(true);
15325 }
15326 
15327 void PPCTargetLowering::insertCopiesSplitCSR(
15328   MachineBasicBlock *Entry,
15329   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15330   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15331   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15332   if (!IStart)
15333     return;
15334 
15335   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15336   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15337   MachineBasicBlock::iterator MBBI = Entry->begin();
15338   for (const MCPhysReg *I = IStart; *I; ++I) {
15339     const TargetRegisterClass *RC = nullptr;
15340     if (PPC::G8RCRegClass.contains(*I))
15341       RC = &PPC::G8RCRegClass;
15342     else if (PPC::F8RCRegClass.contains(*I))
15343       RC = &PPC::F8RCRegClass;
15344     else if (PPC::CRRCRegClass.contains(*I))
15345       RC = &PPC::CRRCRegClass;
15346     else if (PPC::VRRCRegClass.contains(*I))
15347       RC = &PPC::VRRCRegClass;
15348     else
15349       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15350 
15351     Register NewVR = MRI->createVirtualRegister(RC);
15352     // Create copy from CSR to a virtual register.
15353     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15354     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15355     // nounwind. If we want to generalize this later, we may need to emit
15356     // CFI pseudo-instructions.
15357     assert(Entry->getParent()->getFunction().hasFnAttribute(
15358              Attribute::NoUnwind) &&
15359            "Function should be nounwind in insertCopiesSplitCSR!");
15360     Entry->addLiveIn(*I);
15361     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15362       .addReg(*I);
15363 
15364     // Insert the copy-back instructions right before the terminator.
15365     for (auto *Exit : Exits)
15366       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15367               TII->get(TargetOpcode::COPY), *I)
15368         .addReg(NewVR);
15369   }
15370 }
15371 
15372 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15373 bool PPCTargetLowering::useLoadStackGuardNode() const {
15374   if (!Subtarget.isTargetLinux())
15375     return TargetLowering::useLoadStackGuardNode();
15376   return true;
15377 }
15378 
15379 // Override to disable global variable loading on Linux.
15380 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15381   if (!Subtarget.isTargetLinux())
15382     return TargetLowering::insertSSPDeclarations(M);
15383 }
15384 
15385 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15386                                      bool ForCodeSize) const {
15387   if (!VT.isSimple() || !Subtarget.hasVSX())
15388     return false;
15389 
15390   switch(VT.getSimpleVT().SimpleTy) {
15391   default:
15392     // For FP types that are currently not supported by PPC backend, return
15393     // false. Examples: f16, f80.
15394     return false;
15395   case MVT::f32:
15396   case MVT::f64:
15397   case MVT::ppcf128:
15398     return Imm.isPosZero();
15399   }
15400 }
15401 
15402 // For vector shift operation op, fold
15403 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15404 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15405                                   SelectionDAG &DAG) {
15406   SDValue N0 = N->getOperand(0);
15407   SDValue N1 = N->getOperand(1);
15408   EVT VT = N0.getValueType();
15409   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15410   unsigned Opcode = N->getOpcode();
15411   unsigned TargetOpcode;
15412 
15413   switch (Opcode) {
15414   default:
15415     llvm_unreachable("Unexpected shift operation");
15416   case ISD::SHL:
15417     TargetOpcode = PPCISD::SHL;
15418     break;
15419   case ISD::SRL:
15420     TargetOpcode = PPCISD::SRL;
15421     break;
15422   case ISD::SRA:
15423     TargetOpcode = PPCISD::SRA;
15424     break;
15425   }
15426 
15427   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15428       N1->getOpcode() == ISD::AND)
15429     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15430       if (Mask->getZExtValue() == OpSizeInBits - 1)
15431         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15432 
15433   return SDValue();
15434 }
15435 
15436 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15437   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15438     return Value;
15439 
15440   SDValue N0 = N->getOperand(0);
15441   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15442   if (!Subtarget.isISA3_0() ||
15443       N0.getOpcode() != ISD::SIGN_EXTEND ||
15444       N0.getOperand(0).getValueType() != MVT::i32 ||
15445       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15446     return SDValue();
15447 
15448   // We can't save an operation here if the value is already extended, and
15449   // the existing shift is easier to combine.
15450   SDValue ExtsSrc = N0.getOperand(0);
15451   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15452       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15453     return SDValue();
15454 
15455   SDLoc DL(N0);
15456   SDValue ShiftBy = SDValue(CN1, 0);
15457   // We want the shift amount to be i32 on the extswli, but the shift could
15458   // have an i64.
15459   if (ShiftBy.getValueType() == MVT::i64)
15460     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15461 
15462   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15463                          ShiftBy);
15464 }
15465 
15466 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15467   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15468     return Value;
15469 
15470   return SDValue();
15471 }
15472 
15473 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15474   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15475     return Value;
15476 
15477   return SDValue();
15478 }
15479 
15480 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15481 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15482 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15483 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15484 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15485                                  const PPCSubtarget &Subtarget) {
15486   if (!Subtarget.isPPC64())
15487     return SDValue();
15488 
15489   SDValue LHS = N->getOperand(0);
15490   SDValue RHS = N->getOperand(1);
15491 
15492   auto isZextOfCompareWithConstant = [](SDValue Op) {
15493     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15494         Op.getValueType() != MVT::i64)
15495       return false;
15496 
15497     SDValue Cmp = Op.getOperand(0);
15498     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15499         Cmp.getOperand(0).getValueType() != MVT::i64)
15500       return false;
15501 
15502     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15503       int64_t NegConstant = 0 - Constant->getSExtValue();
15504       // Due to the limitations of the addi instruction,
15505       // -C is required to be [-32768, 32767].
15506       return isInt<16>(NegConstant);
15507     }
15508 
15509     return false;
15510   };
15511 
15512   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15513   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15514 
15515   // If there is a pattern, canonicalize a zext operand to the RHS.
15516   if (LHSHasPattern && !RHSHasPattern)
15517     std::swap(LHS, RHS);
15518   else if (!LHSHasPattern && !RHSHasPattern)
15519     return SDValue();
15520 
15521   SDLoc DL(N);
15522   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15523   SDValue Cmp = RHS.getOperand(0);
15524   SDValue Z = Cmp.getOperand(0);
15525   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15526 
15527   assert(Constant && "Constant Should not be a null pointer.");
15528   int64_t NegConstant = 0 - Constant->getSExtValue();
15529 
15530   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15531   default: break;
15532   case ISD::SETNE: {
15533     //                                 when C == 0
15534     //                             --> addze X, (addic Z, -1).carry
15535     //                            /
15536     // add X, (zext(setne Z, C))--
15537     //                            \    when -32768 <= -C <= 32767 && C != 0
15538     //                             --> addze X, (addic (addi Z, -C), -1).carry
15539     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15540                               DAG.getConstant(NegConstant, DL, MVT::i64));
15541     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15542     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15543                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15544     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15545                        SDValue(Addc.getNode(), 1));
15546     }
15547   case ISD::SETEQ: {
15548     //                                 when C == 0
15549     //                             --> addze X, (subfic Z, 0).carry
15550     //                            /
15551     // add X, (zext(sete  Z, C))--
15552     //                            \    when -32768 <= -C <= 32767 && C != 0
15553     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15554     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15555                               DAG.getConstant(NegConstant, DL, MVT::i64));
15556     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15557     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15558                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15559     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15560                        SDValue(Subc.getNode(), 1));
15561     }
15562   }
15563 
15564   return SDValue();
15565 }
15566 
15567 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15568   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15569     return Value;
15570 
15571   return SDValue();
15572 }
15573 
15574 // Detect TRUNCATE operations on bitcasts of float128 values.
15575 // What we are looking for here is the situtation where we extract a subset
15576 // of bits from a 128 bit float.
15577 // This can be of two forms:
15578 // 1) BITCAST of f128 feeding TRUNCATE
15579 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15580 // The reason this is required is because we do not have a legal i128 type
15581 // and so we want to prevent having to store the f128 and then reload part
15582 // of it.
15583 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15584                                            DAGCombinerInfo &DCI) const {
15585   // If we are using CRBits then try that first.
15586   if (Subtarget.useCRBits()) {
15587     // Check if CRBits did anything and return that if it did.
15588     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15589       return CRTruncValue;
15590   }
15591 
15592   SDLoc dl(N);
15593   SDValue Op0 = N->getOperand(0);
15594 
15595   // Looking for a truncate of i128 to i64.
15596   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15597     return SDValue();
15598 
15599   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15600 
15601   // SRL feeding TRUNCATE.
15602   if (Op0.getOpcode() == ISD::SRL) {
15603     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15604     // The right shift has to be by 64 bits.
15605     if (!ConstNode || ConstNode->getZExtValue() != 64)
15606       return SDValue();
15607 
15608     // Switch the element number to extract.
15609     EltToExtract = EltToExtract ? 0 : 1;
15610     // Update Op0 past the SRL.
15611     Op0 = Op0.getOperand(0);
15612   }
15613 
15614   // BITCAST feeding a TRUNCATE possibly via SRL.
15615   if (Op0.getOpcode() == ISD::BITCAST &&
15616       Op0.getValueType() == MVT::i128 &&
15617       Op0.getOperand(0).getValueType() == MVT::f128) {
15618     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15619     return DCI.DAG.getNode(
15620         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15621         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15622   }
15623   return SDValue();
15624 }
15625 
15626 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15627   SelectionDAG &DAG = DCI.DAG;
15628 
15629   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15630   if (!ConstOpOrElement)
15631     return SDValue();
15632 
15633   // An imul is usually smaller than the alternative sequence for legal type.
15634   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15635       isOperationLegal(ISD::MUL, N->getValueType(0)))
15636     return SDValue();
15637 
15638   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15639     switch (this->Subtarget.getCPUDirective()) {
15640     default:
15641       // TODO: enhance the condition for subtarget before pwr8
15642       return false;
15643     case PPC::DIR_PWR8:
15644       //  type        mul     add    shl
15645       // scalar        4       1      1
15646       // vector        7       2      2
15647       return true;
15648     case PPC::DIR_PWR9:
15649     case PPC::DIR_PWR_FUTURE:
15650       //  type        mul     add    shl
15651       // scalar        5       2      2
15652       // vector        7       2      2
15653 
15654       // The cycle RATIO of related operations are showed as a table above.
15655       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15656       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15657       // are 4, it is always profitable; but for 3 instrs patterns
15658       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15659       // So we should only do it for vector type.
15660       return IsAddOne && IsNeg ? VT.isVector() : true;
15661     }
15662   };
15663 
15664   EVT VT = N->getValueType(0);
15665   SDLoc DL(N);
15666 
15667   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15668   bool IsNeg = MulAmt.isNegative();
15669   APInt MulAmtAbs = MulAmt.abs();
15670 
15671   if ((MulAmtAbs - 1).isPowerOf2()) {
15672     // (mul x, 2^N + 1) => (add (shl x, N), x)
15673     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15674 
15675     if (!IsProfitable(IsNeg, true, VT))
15676       return SDValue();
15677 
15678     SDValue Op0 = N->getOperand(0);
15679     SDValue Op1 =
15680         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15681                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15682     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15683 
15684     if (!IsNeg)
15685       return Res;
15686 
15687     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15688   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15689     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15690     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15691 
15692     if (!IsProfitable(IsNeg, false, VT))
15693       return SDValue();
15694 
15695     SDValue Op0 = N->getOperand(0);
15696     SDValue Op1 =
15697         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15698                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15699 
15700     if (!IsNeg)
15701       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15702     else
15703       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15704 
15705   } else {
15706     return SDValue();
15707   }
15708 }
15709 
15710 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15711   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15712   if (!Subtarget.is64BitELFABI())
15713     return false;
15714 
15715   // If not a tail call then no need to proceed.
15716   if (!CI->isTailCall())
15717     return false;
15718 
15719   // If sibling calls have been disabled and tail-calls aren't guaranteed
15720   // there is no reason to duplicate.
15721   auto &TM = getTargetMachine();
15722   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15723     return false;
15724 
15725   // Can't tail call a function called indirectly, or if it has variadic args.
15726   const Function *Callee = CI->getCalledFunction();
15727   if (!Callee || Callee->isVarArg())
15728     return false;
15729 
15730   // Make sure the callee and caller calling conventions are eligible for tco.
15731   const Function *Caller = CI->getParent()->getParent();
15732   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15733                                            CI->getCallingConv()))
15734       return false;
15735 
15736   // If the function is local then we have a good chance at tail-calling it
15737   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15738 }
15739 
15740 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15741   if (!Subtarget.hasVSX())
15742     return false;
15743   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15744     return true;
15745   return VT == MVT::f32 || VT == MVT::f64 ||
15746     VT == MVT::v4f32 || VT == MVT::v2f64;
15747 }
15748 
15749 bool PPCTargetLowering::
15750 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15751   const Value *Mask = AndI.getOperand(1);
15752   // If the mask is suitable for andi. or andis. we should sink the and.
15753   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15754     // Can't handle constants wider than 64-bits.
15755     if (CI->getBitWidth() > 64)
15756       return false;
15757     int64_t ConstVal = CI->getZExtValue();
15758     return isUInt<16>(ConstVal) ||
15759       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15760   }
15761 
15762   // For non-constant masks, we can always use the record-form and.
15763   return true;
15764 }
15765 
15766 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15767 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15768 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15769 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15770 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15771 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15772   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15773   assert(Subtarget.hasP9Altivec() &&
15774          "Only combine this when P9 altivec supported!");
15775   EVT VT = N->getValueType(0);
15776   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15777     return SDValue();
15778 
15779   SelectionDAG &DAG = DCI.DAG;
15780   SDLoc dl(N);
15781   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15782     // Even for signed integers, if it's known to be positive (as signed
15783     // integer) due to zero-extended inputs.
15784     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15785     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15786     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15787          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15788         (SubOpcd1 == ISD::ZERO_EXTEND ||
15789          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15790       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15791                          N->getOperand(0)->getOperand(0),
15792                          N->getOperand(0)->getOperand(1),
15793                          DAG.getTargetConstant(0, dl, MVT::i32));
15794     }
15795 
15796     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15797     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15798         N->getOperand(0).hasOneUse()) {
15799       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15800                          N->getOperand(0)->getOperand(0),
15801                          N->getOperand(0)->getOperand(1),
15802                          DAG.getTargetConstant(1, dl, MVT::i32));
15803     }
15804   }
15805 
15806   return SDValue();
15807 }
15808 
15809 // For type v4i32/v8ii16/v16i8, transform
15810 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15811 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15812 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15813 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15814 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15815                                           DAGCombinerInfo &DCI) const {
15816   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15817   assert(Subtarget.hasP9Altivec() &&
15818          "Only combine this when P9 altivec supported!");
15819 
15820   SelectionDAG &DAG = DCI.DAG;
15821   SDLoc dl(N);
15822   SDValue Cond = N->getOperand(0);
15823   SDValue TrueOpnd = N->getOperand(1);
15824   SDValue FalseOpnd = N->getOperand(2);
15825   EVT VT = N->getOperand(1).getValueType();
15826 
15827   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15828       FalseOpnd.getOpcode() != ISD::SUB)
15829     return SDValue();
15830 
15831   // ABSD only available for type v4i32/v8i16/v16i8
15832   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15833     return SDValue();
15834 
15835   // At least to save one more dependent computation
15836   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15837     return SDValue();
15838 
15839   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15840 
15841   // Can only handle unsigned comparison here
15842   switch (CC) {
15843   default:
15844     return SDValue();
15845   case ISD::SETUGT:
15846   case ISD::SETUGE:
15847     break;
15848   case ISD::SETULT:
15849   case ISD::SETULE:
15850     std::swap(TrueOpnd, FalseOpnd);
15851     break;
15852   }
15853 
15854   SDValue CmpOpnd1 = Cond.getOperand(0);
15855   SDValue CmpOpnd2 = Cond.getOperand(1);
15856 
15857   // SETCC CmpOpnd1 CmpOpnd2 cond
15858   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15859   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15860   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15861       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15862       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15863       FalseOpnd.getOperand(1) == CmpOpnd1) {
15864     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15865                        CmpOpnd1, CmpOpnd2,
15866                        DAG.getTargetConstant(0, dl, MVT::i32));
15867   }
15868 
15869   return SDValue();
15870 }
15871