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     // First set operation action for all vector types to expand. Then we
571     // will selectively turn on ones that can be effectively codegen'd.
572     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
573       // add/sub are legal for all supported vector VT's.
574       setOperationAction(ISD::ADD, VT, Legal);
575       setOperationAction(ISD::SUB, VT, Legal);
576 
577       // For v2i64, these are only valid with P8Vector. This is corrected after
578       // the loop.
579       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
580         setOperationAction(ISD::SMAX, VT, Legal);
581         setOperationAction(ISD::SMIN, VT, Legal);
582         setOperationAction(ISD::UMAX, VT, Legal);
583         setOperationAction(ISD::UMIN, VT, Legal);
584       }
585       else {
586         setOperationAction(ISD::SMAX, VT, Expand);
587         setOperationAction(ISD::SMIN, VT, Expand);
588         setOperationAction(ISD::UMAX, VT, Expand);
589         setOperationAction(ISD::UMIN, VT, Expand);
590       }
591 
592       if (Subtarget.hasVSX()) {
593         setOperationAction(ISD::FMAXNUM, VT, Legal);
594         setOperationAction(ISD::FMINNUM, VT, Legal);
595       }
596 
597       // Vector instructions introduced in P8
598       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
599         setOperationAction(ISD::CTPOP, VT, Legal);
600         setOperationAction(ISD::CTLZ, VT, Legal);
601       }
602       else {
603         setOperationAction(ISD::CTPOP, VT, Expand);
604         setOperationAction(ISD::CTLZ, VT, Expand);
605       }
606 
607       // Vector instructions introduced in P9
608       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
609         setOperationAction(ISD::CTTZ, VT, Legal);
610       else
611         setOperationAction(ISD::CTTZ, VT, Expand);
612 
613       // We promote all shuffles to v16i8.
614       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
615       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
616 
617       // We promote all non-typed operations to v4i32.
618       setOperationAction(ISD::AND   , VT, Promote);
619       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
620       setOperationAction(ISD::OR    , VT, Promote);
621       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
622       setOperationAction(ISD::XOR   , VT, Promote);
623       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
624       setOperationAction(ISD::LOAD  , VT, Promote);
625       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
626       setOperationAction(ISD::SELECT, VT, Promote);
627       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
628       setOperationAction(ISD::VSELECT, VT, Legal);
629       setOperationAction(ISD::SELECT_CC, VT, Promote);
630       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
631       setOperationAction(ISD::STORE, VT, Promote);
632       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
633 
634       // No other operations are legal.
635       setOperationAction(ISD::MUL , VT, Expand);
636       setOperationAction(ISD::SDIV, VT, Expand);
637       setOperationAction(ISD::SREM, VT, Expand);
638       setOperationAction(ISD::UDIV, VT, Expand);
639       setOperationAction(ISD::UREM, VT, Expand);
640       setOperationAction(ISD::FDIV, VT, Expand);
641       setOperationAction(ISD::FREM, VT, Expand);
642       setOperationAction(ISD::FNEG, VT, Expand);
643       setOperationAction(ISD::FSQRT, VT, Expand);
644       setOperationAction(ISD::FLOG, VT, Expand);
645       setOperationAction(ISD::FLOG10, VT, Expand);
646       setOperationAction(ISD::FLOG2, VT, Expand);
647       setOperationAction(ISD::FEXP, VT, Expand);
648       setOperationAction(ISD::FEXP2, VT, Expand);
649       setOperationAction(ISD::FSIN, VT, Expand);
650       setOperationAction(ISD::FCOS, VT, Expand);
651       setOperationAction(ISD::FABS, VT, Expand);
652       setOperationAction(ISD::FFLOOR, VT, Expand);
653       setOperationAction(ISD::FCEIL,  VT, Expand);
654       setOperationAction(ISD::FTRUNC, VT, Expand);
655       setOperationAction(ISD::FRINT,  VT, Expand);
656       setOperationAction(ISD::FNEARBYINT, VT, Expand);
657       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
658       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
659       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
660       setOperationAction(ISD::MULHU, VT, Expand);
661       setOperationAction(ISD::MULHS, VT, Expand);
662       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
663       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
664       setOperationAction(ISD::UDIVREM, VT, Expand);
665       setOperationAction(ISD::SDIVREM, VT, Expand);
666       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
667       setOperationAction(ISD::FPOW, VT, Expand);
668       setOperationAction(ISD::BSWAP, VT, Expand);
669       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
670       setOperationAction(ISD::ROTL, VT, Expand);
671       setOperationAction(ISD::ROTR, VT, Expand);
672 
673       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
674         setTruncStoreAction(VT, InnerVT, Expand);
675         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
676         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
677         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
678       }
679     }
680     if (!Subtarget.hasP8Vector()) {
681       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
682       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
683       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
684       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
685     }
686 
687     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
688       setOperationAction(ISD::ABS, VT, Custom);
689 
690     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
691     // with merges, splats, etc.
692     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
693 
694     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
695     // are cheap, so handle them before they get expanded to scalar.
696     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
697     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
698     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
699     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
700     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
701 
702     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
703     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
704     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
705     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
706     setOperationAction(ISD::SELECT, MVT::v4i32,
707                        Subtarget.useCRBits() ? Legal : Expand);
708     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
709     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
710     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
711     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
712     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
713     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
714     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
715     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
716     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
717 
718     // Without hasP8Altivec set, v2i64 SMAX isn't available.
719     // But ABS custom lowering requires SMAX support.
720     if (!Subtarget.hasP8Altivec())
721       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
722 
723     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
724     if (Subtarget.hasAltivec())
725       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
726         setOperationAction(ISD::ROTL, VT, Legal);
727     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
728     if (Subtarget.hasP8Altivec())
729       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
730 
731     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
732     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
733     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
734     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
735 
736     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
737     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
738 
739     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
740       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
741       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
742     }
743 
744     if (Subtarget.hasP8Altivec())
745       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
746     else
747       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
748 
749     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
750     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
751 
752     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
753     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
754 
755     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
756     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
757     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
758     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
759 
760     // Altivec does not contain unordered floating-point compare instructions
761     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
762     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
763     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
764     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
765 
766     if (Subtarget.hasVSX()) {
767       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
768       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
769       if (Subtarget.hasP8Vector()) {
770         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
771         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
772       }
773       if (Subtarget.hasDirectMove() && isPPC64) {
774         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
775         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
776         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
777         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
778         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
779         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
780         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
781         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
782       }
783       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
784 
785       // The nearbyint variants are not allowed to raise the inexact exception
786       // so we can only code-gen them with unsafe math.
787       if (TM.Options.UnsafeFPMath) {
788         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
789         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
790       }
791 
792       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
793       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
794       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
795       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
796       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
797       setOperationAction(ISD::FROUND, MVT::f64, Legal);
798 
799       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
800       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
801       setOperationAction(ISD::FROUND, MVT::f32, Legal);
802 
803       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
804       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
805 
806       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
807       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
808 
809       // Share the Altivec comparison restrictions.
810       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
811       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
812       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
813       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
814 
815       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
816       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
817 
818       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
819 
820       if (Subtarget.hasP8Vector())
821         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
822 
823       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
824 
825       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
826       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
827       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
828 
829       if (Subtarget.hasP8Altivec()) {
830         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
831         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
832         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
833 
834         // 128 bit shifts can be accomplished via 3 instructions for SHL and
835         // SRL, but not for SRA because of the instructions available:
836         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
837         // doing
838         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
839         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
840         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
841 
842         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
843       }
844       else {
845         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
846         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
847         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
848 
849         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
850 
851         // VSX v2i64 only supports non-arithmetic operations.
852         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
853         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
854       }
855 
856       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
857       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
858       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
859       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
860 
861       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
862 
863       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
864       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
865       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
866       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
867 
868       // Custom handling for partial vectors of integers converted to
869       // floating point. We already have optimal handling for v2i32 through
870       // the DAG combine, so those aren't necessary.
871       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
872       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
873       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
874       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
875       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
876       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
877       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
878       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
879 
880       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
881       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
882       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
883       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
884       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
885       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
886 
887       if (Subtarget.hasDirectMove())
888         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
889       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
890 
891       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
892     }
893 
894     if (Subtarget.hasP8Altivec()) {
895       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
896       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
897     }
898 
899     if (Subtarget.hasP9Vector()) {
900       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
901       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
902 
903       // 128 bit shifts can be accomplished via 3 instructions for SHL and
904       // SRL, but not for SRA because of the instructions available:
905       // VS{RL} and VS{RL}O.
906       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
907       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
908       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
909 
910       if (EnableQuadPrecision) {
911         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
912         setOperationAction(ISD::FADD, MVT::f128, Legal);
913         setOperationAction(ISD::FSUB, MVT::f128, Legal);
914         setOperationAction(ISD::FDIV, MVT::f128, Legal);
915         setOperationAction(ISD::FMUL, MVT::f128, Legal);
916         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
917         // No extending loads to f128 on PPC.
918         for (MVT FPT : MVT::fp_valuetypes())
919           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
920         setOperationAction(ISD::FMA, MVT::f128, Legal);
921         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
922         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
923         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
924         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
925         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
926         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
927 
928         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
929         setOperationAction(ISD::FRINT, MVT::f128, Legal);
930         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
931         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
932         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
933         setOperationAction(ISD::FROUND, MVT::f128, Legal);
934 
935         setOperationAction(ISD::SELECT, MVT::f128, Expand);
936         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
937         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
938         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
939         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
940         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
941         // No implementation for these ops for PowerPC.
942         setOperationAction(ISD::FSIN , MVT::f128, Expand);
943         setOperationAction(ISD::FCOS , MVT::f128, Expand);
944         setOperationAction(ISD::FPOW, MVT::f128, Expand);
945         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
946         setOperationAction(ISD::FREM, MVT::f128, Expand);
947       }
948       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
949       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
950       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
951       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
952       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
953     }
954 
955     if (Subtarget.hasP9Altivec()) {
956       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
957       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
958 
959       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
960       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
961       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
962       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
963       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
964       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
965       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
966     }
967   }
968 
969   if (Subtarget.hasQPX()) {
970     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
971     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
972     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
973     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
974 
975     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
976     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
977 
978     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
979     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
980 
981     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
982     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
983 
984     if (!Subtarget.useCRBits())
985       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
986     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
987 
988     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
989     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
990     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
991     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
992     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
993     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
994     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
995 
996     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
997     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
998 
999     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1000     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1001 
1002     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1003     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1004     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1005     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1006     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1007     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1008     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1009     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1010     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1011     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1012 
1013     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1014     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1015 
1016     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1017     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1018 
1019     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1020 
1021     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1022     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1023     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1024     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1025 
1026     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1027     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1028 
1029     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1030     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1031 
1032     if (!Subtarget.useCRBits())
1033       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1034     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1035 
1036     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1037     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1038     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1039     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1040     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1041     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1042     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1043 
1044     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1045     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1046 
1047     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1048     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1049     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1050     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1051     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1052     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1053     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1054     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1055     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1056     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1057 
1058     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1059     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1060 
1061     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1062     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1063 
1064     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1065 
1066     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1067     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1068     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1069 
1070     if (!Subtarget.useCRBits())
1071       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1072     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1073 
1074     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1075     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1076 
1077     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1078     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1079     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1080     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1081     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1082     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1083     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1084 
1085     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1086     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1087 
1088     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1089 
1090     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1091     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1092     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1093     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1094 
1095     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1096     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1097     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1098     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1099 
1100     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1101     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1102 
1103     // These need to set FE_INEXACT, and so cannot be vectorized here.
1104     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1105     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1106 
1107     if (TM.Options.UnsafeFPMath) {
1108       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1109       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1110 
1111       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1112       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1113     } else {
1114       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1115       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1116 
1117       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1118       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1119     }
1120   }
1121 
1122   if (Subtarget.has64BitSupport())
1123     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1124 
1125   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1126 
1127   if (!isPPC64) {
1128     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1129     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1130   }
1131 
1132   setBooleanContents(ZeroOrOneBooleanContent);
1133 
1134   if (Subtarget.hasAltivec()) {
1135     // Altivec instructions set fields to all zeros or all ones.
1136     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1137   }
1138 
1139   if (!isPPC64) {
1140     // These libcalls are not available in 32-bit.
1141     setLibcallName(RTLIB::SHL_I128, nullptr);
1142     setLibcallName(RTLIB::SRL_I128, nullptr);
1143     setLibcallName(RTLIB::SRA_I128, nullptr);
1144   }
1145 
1146   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1147 
1148   // We have target-specific dag combine patterns for the following nodes:
1149   setTargetDAGCombine(ISD::ADD);
1150   setTargetDAGCombine(ISD::SHL);
1151   setTargetDAGCombine(ISD::SRA);
1152   setTargetDAGCombine(ISD::SRL);
1153   setTargetDAGCombine(ISD::MUL);
1154   setTargetDAGCombine(ISD::SINT_TO_FP);
1155   setTargetDAGCombine(ISD::BUILD_VECTOR);
1156   if (Subtarget.hasFPCVT())
1157     setTargetDAGCombine(ISD::UINT_TO_FP);
1158   setTargetDAGCombine(ISD::LOAD);
1159   setTargetDAGCombine(ISD::STORE);
1160   setTargetDAGCombine(ISD::BR_CC);
1161   if (Subtarget.useCRBits())
1162     setTargetDAGCombine(ISD::BRCOND);
1163   setTargetDAGCombine(ISD::BSWAP);
1164   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1165   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1166   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1167 
1168   setTargetDAGCombine(ISD::SIGN_EXTEND);
1169   setTargetDAGCombine(ISD::ZERO_EXTEND);
1170   setTargetDAGCombine(ISD::ANY_EXTEND);
1171 
1172   setTargetDAGCombine(ISD::TRUNCATE);
1173   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1174 
1175 
1176   if (Subtarget.useCRBits()) {
1177     setTargetDAGCombine(ISD::TRUNCATE);
1178     setTargetDAGCombine(ISD::SETCC);
1179     setTargetDAGCombine(ISD::SELECT_CC);
1180   }
1181 
1182   // Use reciprocal estimates.
1183   if (TM.Options.UnsafeFPMath) {
1184     setTargetDAGCombine(ISD::FDIV);
1185     setTargetDAGCombine(ISD::FSQRT);
1186   }
1187 
1188   if (Subtarget.hasP9Altivec()) {
1189     setTargetDAGCombine(ISD::ABS);
1190     setTargetDAGCombine(ISD::VSELECT);
1191   }
1192 
1193   // Darwin long double math library functions have $LDBL128 appended.
1194   if (Subtarget.isDarwin()) {
1195     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1196     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1197     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1198     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1199     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1200     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1201     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1202     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1203     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1204     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1205   }
1206 
1207   if (EnableQuadPrecision) {
1208     setLibcallName(RTLIB::LOG_F128, "logf128");
1209     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1210     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1211     setLibcallName(RTLIB::EXP_F128, "expf128");
1212     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1213     setLibcallName(RTLIB::SIN_F128, "sinf128");
1214     setLibcallName(RTLIB::COS_F128, "cosf128");
1215     setLibcallName(RTLIB::POW_F128, "powf128");
1216     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1217     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1218     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1219     setLibcallName(RTLIB::REM_F128, "fmodf128");
1220   }
1221 
1222   // With 32 condition bits, we don't need to sink (and duplicate) compares
1223   // aggressively in CodeGenPrep.
1224   if (Subtarget.useCRBits()) {
1225     setHasMultipleConditionRegisters();
1226     setJumpIsExpensive();
1227   }
1228 
1229   setMinFunctionAlignment(Align(4));
1230   if (Subtarget.isDarwin())
1231     setPrefFunctionAlignment(Align(16));
1232 
1233   switch (Subtarget.getCPUDirective()) {
1234   default: break;
1235   case PPC::DIR_970:
1236   case PPC::DIR_A2:
1237   case PPC::DIR_E500:
1238   case PPC::DIR_E500mc:
1239   case PPC::DIR_E5500:
1240   case PPC::DIR_PWR4:
1241   case PPC::DIR_PWR5:
1242   case PPC::DIR_PWR5X:
1243   case PPC::DIR_PWR6:
1244   case PPC::DIR_PWR6X:
1245   case PPC::DIR_PWR7:
1246   case PPC::DIR_PWR8:
1247   case PPC::DIR_PWR9:
1248   case PPC::DIR_PWR_FUTURE:
1249     setPrefLoopAlignment(Align(16));
1250     setPrefFunctionAlignment(Align(16));
1251     break;
1252   }
1253 
1254   if (Subtarget.enableMachineScheduler())
1255     setSchedulingPreference(Sched::Source);
1256   else
1257     setSchedulingPreference(Sched::Hybrid);
1258 
1259   computeRegisterProperties(STI.getRegisterInfo());
1260 
1261   // The Freescale cores do better with aggressive inlining of memcpy and
1262   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1263   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1264       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1265     MaxStoresPerMemset = 32;
1266     MaxStoresPerMemsetOptSize = 16;
1267     MaxStoresPerMemcpy = 32;
1268     MaxStoresPerMemcpyOptSize = 8;
1269     MaxStoresPerMemmove = 32;
1270     MaxStoresPerMemmoveOptSize = 8;
1271   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1272     // The A2 also benefits from (very) aggressive inlining of memcpy and
1273     // friends. The overhead of a the function call, even when warm, can be
1274     // over one hundred cycles.
1275     MaxStoresPerMemset = 128;
1276     MaxStoresPerMemcpy = 128;
1277     MaxStoresPerMemmove = 128;
1278     MaxLoadsPerMemcmp = 128;
1279   } else {
1280     MaxLoadsPerMemcmp = 8;
1281     MaxLoadsPerMemcmpOptSize = 4;
1282   }
1283 }
1284 
1285 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1286 /// the desired ByVal argument alignment.
1287 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1288                              unsigned MaxMaxAlign) {
1289   if (MaxAlign == MaxMaxAlign)
1290     return;
1291   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1292     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1293       MaxAlign = 32;
1294     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1295       MaxAlign = 16;
1296   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1297     unsigned EltAlign = 0;
1298     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1299     if (EltAlign > MaxAlign)
1300       MaxAlign = EltAlign;
1301   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1302     for (auto *EltTy : STy->elements()) {
1303       unsigned EltAlign = 0;
1304       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1305       if (EltAlign > MaxAlign)
1306         MaxAlign = EltAlign;
1307       if (MaxAlign == MaxMaxAlign)
1308         break;
1309     }
1310   }
1311 }
1312 
1313 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1314 /// function arguments in the caller parameter area.
1315 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1316                                                   const DataLayout &DL) const {
1317   // Darwin passes everything on 4 byte boundary.
1318   if (Subtarget.isDarwin())
1319     return 4;
1320 
1321   // 16byte and wider vectors are passed on 16byte boundary.
1322   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1323   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1324   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1325     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1326   return Align;
1327 }
1328 
1329 bool PPCTargetLowering::useSoftFloat() const {
1330   return Subtarget.useSoftFloat();
1331 }
1332 
1333 bool PPCTargetLowering::hasSPE() const {
1334   return Subtarget.hasSPE();
1335 }
1336 
1337 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1338   return VT.isScalarInteger();
1339 }
1340 
1341 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1342   switch ((PPCISD::NodeType)Opcode) {
1343   case PPCISD::FIRST_NUMBER:    break;
1344   case PPCISD::FSEL:            return "PPCISD::FSEL";
1345   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1346   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1347   case PPCISD::FCFID:           return "PPCISD::FCFID";
1348   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1349   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1350   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1351   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1352   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1353   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1354   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1355   case PPCISD::FP_TO_UINT_IN_VSR:
1356                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1357   case PPCISD::FP_TO_SINT_IN_VSR:
1358                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1359   case PPCISD::FRE:             return "PPCISD::FRE";
1360   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1361   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1362   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1363   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1364   case PPCISD::VPERM:           return "PPCISD::VPERM";
1365   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1366   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1367   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1368   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1369   case PPCISD::CMPB:            return "PPCISD::CMPB";
1370   case PPCISD::Hi:              return "PPCISD::Hi";
1371   case PPCISD::Lo:              return "PPCISD::Lo";
1372   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1373   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1374   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1375   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1376   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1377   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1378   case PPCISD::SRL:             return "PPCISD::SRL";
1379   case PPCISD::SRA:             return "PPCISD::SRA";
1380   case PPCISD::SHL:             return "PPCISD::SHL";
1381   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1382   case PPCISD::CALL:            return "PPCISD::CALL";
1383   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1384   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1385   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1386   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1387   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1388   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1389   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1390   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1391   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1392   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1393   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1394   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1395   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1396   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1397   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1398   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1399   case PPCISD::VCMP:            return "PPCISD::VCMP";
1400   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1401   case PPCISD::LBRX:            return "PPCISD::LBRX";
1402   case PPCISD::STBRX:           return "PPCISD::STBRX";
1403   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1404   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1405   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1406   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1407   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1408   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1409   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1410   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1411   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1412   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1413   case PPCISD::ST_VSR_SCAL_INT:
1414                                 return "PPCISD::ST_VSR_SCAL_INT";
1415   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1416   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1417   case PPCISD::BDZ:             return "PPCISD::BDZ";
1418   case PPCISD::MFFS:            return "PPCISD::MFFS";
1419   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1420   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1421   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1422   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1423   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1424   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1425   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1426   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1427   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1428   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1429   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1430   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1431   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1432   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1433   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1434   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1435   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1436   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1437   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1438   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1439   case PPCISD::SC:              return "PPCISD::SC";
1440   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1441   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1442   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1443   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1444   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1445   case PPCISD::VABSD:           return "PPCISD::VABSD";
1446   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1447   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1448   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1449   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1450   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1451   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1452   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1453   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1454   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1455   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1456   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1457   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1458   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1459   }
1460   return nullptr;
1461 }
1462 
1463 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1464                                           EVT VT) const {
1465   if (!VT.isVector())
1466     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1467 
1468   if (Subtarget.hasQPX())
1469     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1470 
1471   return VT.changeVectorElementTypeToInteger();
1472 }
1473 
1474 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1475   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1476   return true;
1477 }
1478 
1479 //===----------------------------------------------------------------------===//
1480 // Node matching predicates, for use by the tblgen matching code.
1481 //===----------------------------------------------------------------------===//
1482 
1483 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1484 static bool isFloatingPointZero(SDValue Op) {
1485   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1486     return CFP->getValueAPF().isZero();
1487   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1488     // Maybe this has already been legalized into the constant pool?
1489     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1490       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1491         return CFP->getValueAPF().isZero();
1492   }
1493   return false;
1494 }
1495 
1496 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1497 /// true if Op is undef or if it matches the specified value.
1498 static bool isConstantOrUndef(int Op, int Val) {
1499   return Op < 0 || Op == Val;
1500 }
1501 
1502 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1503 /// VPKUHUM instruction.
1504 /// The ShuffleKind distinguishes between big-endian operations with
1505 /// two different inputs (0), either-endian operations with two identical
1506 /// inputs (1), and little-endian operations with two different inputs (2).
1507 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1508 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1509                                SelectionDAG &DAG) {
1510   bool IsLE = DAG.getDataLayout().isLittleEndian();
1511   if (ShuffleKind == 0) {
1512     if (IsLE)
1513       return false;
1514     for (unsigned i = 0; i != 16; ++i)
1515       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1516         return false;
1517   } else if (ShuffleKind == 2) {
1518     if (!IsLE)
1519       return false;
1520     for (unsigned i = 0; i != 16; ++i)
1521       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1522         return false;
1523   } else if (ShuffleKind == 1) {
1524     unsigned j = IsLE ? 0 : 1;
1525     for (unsigned i = 0; i != 8; ++i)
1526       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1527           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1528         return false;
1529   }
1530   return true;
1531 }
1532 
1533 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1534 /// VPKUWUM instruction.
1535 /// The ShuffleKind distinguishes between big-endian operations with
1536 /// two different inputs (0), either-endian operations with two identical
1537 /// inputs (1), and little-endian operations with two different inputs (2).
1538 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1539 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1540                                SelectionDAG &DAG) {
1541   bool IsLE = DAG.getDataLayout().isLittleEndian();
1542   if (ShuffleKind == 0) {
1543     if (IsLE)
1544       return false;
1545     for (unsigned i = 0; i != 16; i += 2)
1546       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1547           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1548         return false;
1549   } else if (ShuffleKind == 2) {
1550     if (!IsLE)
1551       return false;
1552     for (unsigned i = 0; i != 16; i += 2)
1553       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1554           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1555         return false;
1556   } else if (ShuffleKind == 1) {
1557     unsigned j = IsLE ? 0 : 2;
1558     for (unsigned i = 0; i != 8; i += 2)
1559       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1560           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1561           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1562           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1563         return false;
1564   }
1565   return true;
1566 }
1567 
1568 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1569 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1570 /// current subtarget.
1571 ///
1572 /// The ShuffleKind distinguishes between big-endian operations with
1573 /// two different inputs (0), either-endian operations with two identical
1574 /// inputs (1), and little-endian operations with two different inputs (2).
1575 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1576 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1577                                SelectionDAG &DAG) {
1578   const PPCSubtarget& Subtarget =
1579       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1580   if (!Subtarget.hasP8Vector())
1581     return false;
1582 
1583   bool IsLE = DAG.getDataLayout().isLittleEndian();
1584   if (ShuffleKind == 0) {
1585     if (IsLE)
1586       return false;
1587     for (unsigned i = 0; i != 16; i += 4)
1588       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1589           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1590           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1591           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1592         return false;
1593   } else if (ShuffleKind == 2) {
1594     if (!IsLE)
1595       return false;
1596     for (unsigned i = 0; i != 16; i += 4)
1597       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1598           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1599           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1600           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1601         return false;
1602   } else if (ShuffleKind == 1) {
1603     unsigned j = IsLE ? 0 : 4;
1604     for (unsigned i = 0; i != 8; i += 4)
1605       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1606           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1607           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1608           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1609           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1610           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1611           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1612           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1613         return false;
1614   }
1615   return true;
1616 }
1617 
1618 /// isVMerge - Common function, used to match vmrg* shuffles.
1619 ///
1620 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1621                      unsigned LHSStart, unsigned RHSStart) {
1622   if (N->getValueType(0) != MVT::v16i8)
1623     return false;
1624   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1625          "Unsupported merge size!");
1626 
1627   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1628     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1629       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1630                              LHSStart+j+i*UnitSize) ||
1631           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1632                              RHSStart+j+i*UnitSize))
1633         return false;
1634     }
1635   return true;
1636 }
1637 
1638 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1639 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1640 /// The ShuffleKind distinguishes between big-endian merges with two
1641 /// different inputs (0), either-endian merges with two identical inputs (1),
1642 /// and little-endian merges with two different inputs (2).  For the latter,
1643 /// the input operands are swapped (see PPCInstrAltivec.td).
1644 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1645                              unsigned ShuffleKind, SelectionDAG &DAG) {
1646   if (DAG.getDataLayout().isLittleEndian()) {
1647     if (ShuffleKind == 1) // unary
1648       return isVMerge(N, UnitSize, 0, 0);
1649     else if (ShuffleKind == 2) // swapped
1650       return isVMerge(N, UnitSize, 0, 16);
1651     else
1652       return false;
1653   } else {
1654     if (ShuffleKind == 1) // unary
1655       return isVMerge(N, UnitSize, 8, 8);
1656     else if (ShuffleKind == 0) // normal
1657       return isVMerge(N, UnitSize, 8, 24);
1658     else
1659       return false;
1660   }
1661 }
1662 
1663 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1664 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1665 /// The ShuffleKind distinguishes between big-endian merges with two
1666 /// different inputs (0), either-endian merges with two identical inputs (1),
1667 /// and little-endian merges with two different inputs (2).  For the latter,
1668 /// the input operands are swapped (see PPCInstrAltivec.td).
1669 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1670                              unsigned ShuffleKind, SelectionDAG &DAG) {
1671   if (DAG.getDataLayout().isLittleEndian()) {
1672     if (ShuffleKind == 1) // unary
1673       return isVMerge(N, UnitSize, 8, 8);
1674     else if (ShuffleKind == 2) // swapped
1675       return isVMerge(N, UnitSize, 8, 24);
1676     else
1677       return false;
1678   } else {
1679     if (ShuffleKind == 1) // unary
1680       return isVMerge(N, UnitSize, 0, 0);
1681     else if (ShuffleKind == 0) // normal
1682       return isVMerge(N, UnitSize, 0, 16);
1683     else
1684       return false;
1685   }
1686 }
1687 
1688 /**
1689  * Common function used to match vmrgew and vmrgow shuffles
1690  *
1691  * The indexOffset determines whether to look for even or odd words in
1692  * the shuffle mask. This is based on the of the endianness of the target
1693  * machine.
1694  *   - Little Endian:
1695  *     - Use offset of 0 to check for odd elements
1696  *     - Use offset of 4 to check for even elements
1697  *   - Big Endian:
1698  *     - Use offset of 0 to check for even elements
1699  *     - Use offset of 4 to check for odd elements
1700  * A detailed description of the vector element ordering for little endian and
1701  * big endian can be found at
1702  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1703  * Targeting your applications - what little endian and big endian IBM XL C/C++
1704  * compiler differences mean to you
1705  *
1706  * The mask to the shuffle vector instruction specifies the indices of the
1707  * elements from the two input vectors to place in the result. The elements are
1708  * numbered in array-access order, starting with the first vector. These vectors
1709  * are always of type v16i8, thus each vector will contain 16 elements of size
1710  * 8. More info on the shuffle vector can be found in the
1711  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1712  * Language Reference.
1713  *
1714  * The RHSStartValue indicates whether the same input vectors are used (unary)
1715  * or two different input vectors are used, based on the following:
1716  *   - If the instruction uses the same vector for both inputs, the range of the
1717  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1718  *     be 0.
1719  *   - If the instruction has two different vectors then the range of the
1720  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1721  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1722  *     to 31 specify elements in the second vector).
1723  *
1724  * \param[in] N The shuffle vector SD Node to analyze
1725  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1726  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1727  * vector to the shuffle_vector instruction
1728  * \return true iff this shuffle vector represents an even or odd word merge
1729  */
1730 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1731                      unsigned RHSStartValue) {
1732   if (N->getValueType(0) != MVT::v16i8)
1733     return false;
1734 
1735   for (unsigned i = 0; i < 2; ++i)
1736     for (unsigned j = 0; j < 4; ++j)
1737       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1738                              i*RHSStartValue+j+IndexOffset) ||
1739           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1740                              i*RHSStartValue+j+IndexOffset+8))
1741         return false;
1742   return true;
1743 }
1744 
1745 /**
1746  * Determine if the specified shuffle mask is suitable for the vmrgew or
1747  * vmrgow instructions.
1748  *
1749  * \param[in] N The shuffle vector SD Node to analyze
1750  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1751  * \param[in] ShuffleKind Identify the type of merge:
1752  *   - 0 = big-endian merge with two different inputs;
1753  *   - 1 = either-endian merge with two identical inputs;
1754  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1755  *     little-endian merges).
1756  * \param[in] DAG The current SelectionDAG
1757  * \return true iff this shuffle mask
1758  */
1759 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1760                               unsigned ShuffleKind, SelectionDAG &DAG) {
1761   if (DAG.getDataLayout().isLittleEndian()) {
1762     unsigned indexOffset = CheckEven ? 4 : 0;
1763     if (ShuffleKind == 1) // Unary
1764       return isVMerge(N, indexOffset, 0);
1765     else if (ShuffleKind == 2) // swapped
1766       return isVMerge(N, indexOffset, 16);
1767     else
1768       return false;
1769   }
1770   else {
1771     unsigned indexOffset = CheckEven ? 0 : 4;
1772     if (ShuffleKind == 1) // Unary
1773       return isVMerge(N, indexOffset, 0);
1774     else if (ShuffleKind == 0) // Normal
1775       return isVMerge(N, indexOffset, 16);
1776     else
1777       return false;
1778   }
1779   return false;
1780 }
1781 
1782 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1783 /// amount, otherwise return -1.
1784 /// The ShuffleKind distinguishes between big-endian operations with two
1785 /// different inputs (0), either-endian operations with two identical inputs
1786 /// (1), and little-endian operations with two different inputs (2).  For the
1787 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1788 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1789                              SelectionDAG &DAG) {
1790   if (N->getValueType(0) != MVT::v16i8)
1791     return -1;
1792 
1793   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1794 
1795   // Find the first non-undef value in the shuffle mask.
1796   unsigned i;
1797   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1798     /*search*/;
1799 
1800   if (i == 16) return -1;  // all undef.
1801 
1802   // Otherwise, check to see if the rest of the elements are consecutively
1803   // numbered from this value.
1804   unsigned ShiftAmt = SVOp->getMaskElt(i);
1805   if (ShiftAmt < i) return -1;
1806 
1807   ShiftAmt -= i;
1808   bool isLE = DAG.getDataLayout().isLittleEndian();
1809 
1810   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1811     // Check the rest of the elements to see if they are consecutive.
1812     for (++i; i != 16; ++i)
1813       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1814         return -1;
1815   } else if (ShuffleKind == 1) {
1816     // Check the rest of the elements to see if they are consecutive.
1817     for (++i; i != 16; ++i)
1818       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1819         return -1;
1820   } else
1821     return -1;
1822 
1823   if (isLE)
1824     ShiftAmt = 16 - ShiftAmt;
1825 
1826   return ShiftAmt;
1827 }
1828 
1829 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1830 /// specifies a splat of a single element that is suitable for input to
1831 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1832 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1833   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1834          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1835 
1836   // The consecutive indices need to specify an element, not part of two
1837   // different elements.  So abandon ship early if this isn't the case.
1838   if (N->getMaskElt(0) % EltSize != 0)
1839     return false;
1840 
1841   // This is a splat operation if each element of the permute is the same, and
1842   // if the value doesn't reference the second vector.
1843   unsigned ElementBase = N->getMaskElt(0);
1844 
1845   // FIXME: Handle UNDEF elements too!
1846   if (ElementBase >= 16)
1847     return false;
1848 
1849   // Check that the indices are consecutive, in the case of a multi-byte element
1850   // splatted with a v16i8 mask.
1851   for (unsigned i = 1; i != EltSize; ++i)
1852     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1853       return false;
1854 
1855   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1856     if (N->getMaskElt(i) < 0) continue;
1857     for (unsigned j = 0; j != EltSize; ++j)
1858       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1859         return false;
1860   }
1861   return true;
1862 }
1863 
1864 /// Check that the mask is shuffling N byte elements. Within each N byte
1865 /// element of the mask, the indices could be either in increasing or
1866 /// decreasing order as long as they are consecutive.
1867 /// \param[in] N the shuffle vector SD Node to analyze
1868 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1869 /// Word/DoubleWord/QuadWord).
1870 /// \param[in] StepLen the delta indices number among the N byte element, if
1871 /// the mask is in increasing/decreasing order then it is 1/-1.
1872 /// \return true iff the mask is shuffling N byte elements.
1873 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1874                                    int StepLen) {
1875   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1876          "Unexpected element width.");
1877   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1878 
1879   unsigned NumOfElem = 16 / Width;
1880   unsigned MaskVal[16]; //  Width is never greater than 16
1881   for (unsigned i = 0; i < NumOfElem; ++i) {
1882     MaskVal[0] = N->getMaskElt(i * Width);
1883     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1884       return false;
1885     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1886       return false;
1887     }
1888 
1889     for (unsigned int j = 1; j < Width; ++j) {
1890       MaskVal[j] = N->getMaskElt(i * Width + j);
1891       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1892         return false;
1893       }
1894     }
1895   }
1896 
1897   return true;
1898 }
1899 
1900 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1901                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1902   if (!isNByteElemShuffleMask(N, 4, 1))
1903     return false;
1904 
1905   // Now we look at mask elements 0,4,8,12
1906   unsigned M0 = N->getMaskElt(0) / 4;
1907   unsigned M1 = N->getMaskElt(4) / 4;
1908   unsigned M2 = N->getMaskElt(8) / 4;
1909   unsigned M3 = N->getMaskElt(12) / 4;
1910   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1911   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1912 
1913   // Below, let H and L be arbitrary elements of the shuffle mask
1914   // where H is in the range [4,7] and L is in the range [0,3].
1915   // H, 1, 2, 3 or L, 5, 6, 7
1916   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1917       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1918     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1919     InsertAtByte = IsLE ? 12 : 0;
1920     Swap = M0 < 4;
1921     return true;
1922   }
1923   // 0, H, 2, 3 or 4, L, 6, 7
1924   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1925       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1926     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1927     InsertAtByte = IsLE ? 8 : 4;
1928     Swap = M1 < 4;
1929     return true;
1930   }
1931   // 0, 1, H, 3 or 4, 5, L, 7
1932   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1933       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1934     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1935     InsertAtByte = IsLE ? 4 : 8;
1936     Swap = M2 < 4;
1937     return true;
1938   }
1939   // 0, 1, 2, H or 4, 5, 6, L
1940   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1941       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1942     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1943     InsertAtByte = IsLE ? 0 : 12;
1944     Swap = M3 < 4;
1945     return true;
1946   }
1947 
1948   // If both vector operands for the shuffle are the same vector, the mask will
1949   // contain only elements from the first one and the second one will be undef.
1950   if (N->getOperand(1).isUndef()) {
1951     ShiftElts = 0;
1952     Swap = true;
1953     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1954     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1955       InsertAtByte = IsLE ? 12 : 0;
1956       return true;
1957     }
1958     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1959       InsertAtByte = IsLE ? 8 : 4;
1960       return true;
1961     }
1962     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1963       InsertAtByte = IsLE ? 4 : 8;
1964       return true;
1965     }
1966     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1967       InsertAtByte = IsLE ? 0 : 12;
1968       return true;
1969     }
1970   }
1971 
1972   return false;
1973 }
1974 
1975 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1976                                bool &Swap, bool IsLE) {
1977   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1978   // Ensure each byte index of the word is consecutive.
1979   if (!isNByteElemShuffleMask(N, 4, 1))
1980     return false;
1981 
1982   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1983   unsigned M0 = N->getMaskElt(0) / 4;
1984   unsigned M1 = N->getMaskElt(4) / 4;
1985   unsigned M2 = N->getMaskElt(8) / 4;
1986   unsigned M3 = N->getMaskElt(12) / 4;
1987 
1988   // If both vector operands for the shuffle are the same vector, the mask will
1989   // contain only elements from the first one and the second one will be undef.
1990   if (N->getOperand(1).isUndef()) {
1991     assert(M0 < 4 && "Indexing into an undef vector?");
1992     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1993       return false;
1994 
1995     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1996     Swap = false;
1997     return true;
1998   }
1999 
2000   // Ensure each word index of the ShuffleVector Mask is consecutive.
2001   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2002     return false;
2003 
2004   if (IsLE) {
2005     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2006       // Input vectors don't need to be swapped if the leading element
2007       // of the result is one of the 3 left elements of the second vector
2008       // (or if there is no shift to be done at all).
2009       Swap = false;
2010       ShiftElts = (8 - M0) % 8;
2011     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2012       // Input vectors need to be swapped if the leading element
2013       // of the result is one of the 3 left elements of the first vector
2014       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2015       Swap = true;
2016       ShiftElts = (4 - M0) % 4;
2017     }
2018 
2019     return true;
2020   } else {                                          // BE
2021     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2022       // Input vectors don't need to be swapped if the leading element
2023       // of the result is one of the 4 elements of the first vector.
2024       Swap = false;
2025       ShiftElts = M0;
2026     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2027       // Input vectors need to be swapped if the leading element
2028       // of the result is one of the 4 elements of the right vector.
2029       Swap = true;
2030       ShiftElts = M0 - 4;
2031     }
2032 
2033     return true;
2034   }
2035 }
2036 
2037 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2038   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2039 
2040   if (!isNByteElemShuffleMask(N, Width, -1))
2041     return false;
2042 
2043   for (int i = 0; i < 16; i += Width)
2044     if (N->getMaskElt(i) != i + Width - 1)
2045       return false;
2046 
2047   return true;
2048 }
2049 
2050 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2051   return isXXBRShuffleMaskHelper(N, 2);
2052 }
2053 
2054 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2055   return isXXBRShuffleMaskHelper(N, 4);
2056 }
2057 
2058 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2059   return isXXBRShuffleMaskHelper(N, 8);
2060 }
2061 
2062 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2063   return isXXBRShuffleMaskHelper(N, 16);
2064 }
2065 
2066 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2067 /// if the inputs to the instruction should be swapped and set \p DM to the
2068 /// value for the immediate.
2069 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2070 /// AND element 0 of the result comes from the first input (LE) or second input
2071 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2072 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2073 /// mask.
2074 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2075                                bool &Swap, bool IsLE) {
2076   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2077 
2078   // Ensure each byte index of the double word is consecutive.
2079   if (!isNByteElemShuffleMask(N, 8, 1))
2080     return false;
2081 
2082   unsigned M0 = N->getMaskElt(0) / 8;
2083   unsigned M1 = N->getMaskElt(8) / 8;
2084   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2085 
2086   // If both vector operands for the shuffle are the same vector, the mask will
2087   // contain only elements from the first one and the second one will be undef.
2088   if (N->getOperand(1).isUndef()) {
2089     if ((M0 | M1) < 2) {
2090       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2091       Swap = false;
2092       return true;
2093     } else
2094       return false;
2095   }
2096 
2097   if (IsLE) {
2098     if (M0 > 1 && M1 < 2) {
2099       Swap = false;
2100     } else if (M0 < 2 && M1 > 1) {
2101       M0 = (M0 + 2) % 4;
2102       M1 = (M1 + 2) % 4;
2103       Swap = true;
2104     } else
2105       return false;
2106 
2107     // Note: if control flow comes here that means Swap is already set above
2108     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2109     return true;
2110   } else { // BE
2111     if (M0 < 2 && M1 > 1) {
2112       Swap = false;
2113     } else if (M0 > 1 && M1 < 2) {
2114       M0 = (M0 + 2) % 4;
2115       M1 = (M1 + 2) % 4;
2116       Swap = true;
2117     } else
2118       return false;
2119 
2120     // Note: if control flow comes here that means Swap is already set above
2121     DM = (M0 << 1) + (M1 & 1);
2122     return true;
2123   }
2124 }
2125 
2126 
2127 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2128 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2129 /// elements are counted from the left of the vector register).
2130 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2131                                          SelectionDAG &DAG) {
2132   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2133   assert(isSplatShuffleMask(SVOp, EltSize));
2134   if (DAG.getDataLayout().isLittleEndian())
2135     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2136   else
2137     return SVOp->getMaskElt(0) / EltSize;
2138 }
2139 
2140 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2141 /// by using a vspltis[bhw] instruction of the specified element size, return
2142 /// the constant being splatted.  The ByteSize field indicates the number of
2143 /// bytes of each element [124] -> [bhw].
2144 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2145   SDValue OpVal(nullptr, 0);
2146 
2147   // If ByteSize of the splat is bigger than the element size of the
2148   // build_vector, then we have a case where we are checking for a splat where
2149   // multiple elements of the buildvector are folded together into a single
2150   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2151   unsigned EltSize = 16/N->getNumOperands();
2152   if (EltSize < ByteSize) {
2153     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2154     SDValue UniquedVals[4];
2155     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2156 
2157     // See if all of the elements in the buildvector agree across.
2158     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2159       if (N->getOperand(i).isUndef()) continue;
2160       // If the element isn't a constant, bail fully out.
2161       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2162 
2163       if (!UniquedVals[i&(Multiple-1)].getNode())
2164         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2165       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2166         return SDValue();  // no match.
2167     }
2168 
2169     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2170     // either constant or undef values that are identical for each chunk.  See
2171     // if these chunks can form into a larger vspltis*.
2172 
2173     // Check to see if all of the leading entries are either 0 or -1.  If
2174     // neither, then this won't fit into the immediate field.
2175     bool LeadingZero = true;
2176     bool LeadingOnes = true;
2177     for (unsigned i = 0; i != Multiple-1; ++i) {
2178       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2179 
2180       LeadingZero &= isNullConstant(UniquedVals[i]);
2181       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2182     }
2183     // Finally, check the least significant entry.
2184     if (LeadingZero) {
2185       if (!UniquedVals[Multiple-1].getNode())
2186         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2187       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2188       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2189         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2190     }
2191     if (LeadingOnes) {
2192       if (!UniquedVals[Multiple-1].getNode())
2193         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2194       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2195       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2196         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2197     }
2198 
2199     return SDValue();
2200   }
2201 
2202   // Check to see if this buildvec has a single non-undef value in its elements.
2203   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2204     if (N->getOperand(i).isUndef()) continue;
2205     if (!OpVal.getNode())
2206       OpVal = N->getOperand(i);
2207     else if (OpVal != N->getOperand(i))
2208       return SDValue();
2209   }
2210 
2211   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2212 
2213   unsigned ValSizeInBytes = EltSize;
2214   uint64_t Value = 0;
2215   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2216     Value = CN->getZExtValue();
2217   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2218     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2219     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2220   }
2221 
2222   // If the splat value is larger than the element value, then we can never do
2223   // this splat.  The only case that we could fit the replicated bits into our
2224   // immediate field for would be zero, and we prefer to use vxor for it.
2225   if (ValSizeInBytes < ByteSize) return SDValue();
2226 
2227   // If the element value is larger than the splat value, check if it consists
2228   // of a repeated bit pattern of size ByteSize.
2229   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2230     return SDValue();
2231 
2232   // Properly sign extend the value.
2233   int MaskVal = SignExtend32(Value, ByteSize * 8);
2234 
2235   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2236   if (MaskVal == 0) return SDValue();
2237 
2238   // Finally, if this value fits in a 5 bit sext field, return it
2239   if (SignExtend32<5>(MaskVal) == MaskVal)
2240     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2241   return SDValue();
2242 }
2243 
2244 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2245 /// amount, otherwise return -1.
2246 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2247   EVT VT = N->getValueType(0);
2248   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2249     return -1;
2250 
2251   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2252 
2253   // Find the first non-undef value in the shuffle mask.
2254   unsigned i;
2255   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2256     /*search*/;
2257 
2258   if (i == 4) return -1;  // all undef.
2259 
2260   // Otherwise, check to see if the rest of the elements are consecutively
2261   // numbered from this value.
2262   unsigned ShiftAmt = SVOp->getMaskElt(i);
2263   if (ShiftAmt < i) return -1;
2264   ShiftAmt -= i;
2265 
2266   // Check the rest of the elements to see if they are consecutive.
2267   for (++i; i != 4; ++i)
2268     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2269       return -1;
2270 
2271   return ShiftAmt;
2272 }
2273 
2274 //===----------------------------------------------------------------------===//
2275 //  Addressing Mode Selection
2276 //===----------------------------------------------------------------------===//
2277 
2278 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2279 /// or 64-bit immediate, and if the value can be accurately represented as a
2280 /// sign extension from a 16-bit value.  If so, this returns true and the
2281 /// immediate.
2282 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2283   if (!isa<ConstantSDNode>(N))
2284     return false;
2285 
2286   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2287   if (N->getValueType(0) == MVT::i32)
2288     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2289   else
2290     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2291 }
2292 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2293   return isIntS16Immediate(Op.getNode(), Imm);
2294 }
2295 
2296 
2297 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2298 /// be represented as an indexed [r+r] operation.
2299 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2300                                                SDValue &Index,
2301                                                SelectionDAG &DAG) const {
2302   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2303       UI != E; ++UI) {
2304     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2305       if (Memop->getMemoryVT() == MVT::f64) {
2306           Base = N.getOperand(0);
2307           Index = N.getOperand(1);
2308           return true;
2309       }
2310     }
2311   }
2312   return false;
2313 }
2314 
2315 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2316 /// can be represented as an indexed [r+r] operation.  Returns false if it
2317 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2318 /// non-zero and N can be represented by a base register plus a signed 16-bit
2319 /// displacement, make a more precise judgement by checking (displacement % \p
2320 /// EncodingAlignment).
2321 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2322                                             SDValue &Index, SelectionDAG &DAG,
2323                                             unsigned EncodingAlignment) const {
2324   int16_t imm = 0;
2325   if (N.getOpcode() == ISD::ADD) {
2326     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2327     // SPE load/store can only handle 8-bit offsets.
2328     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2329         return true;
2330     if (isIntS16Immediate(N.getOperand(1), imm) &&
2331         (!EncodingAlignment || !(imm % EncodingAlignment)))
2332       return false; // r+i
2333     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2334       return false;    // r+i
2335 
2336     Base = N.getOperand(0);
2337     Index = N.getOperand(1);
2338     return true;
2339   } else if (N.getOpcode() == ISD::OR) {
2340     if (isIntS16Immediate(N.getOperand(1), imm) &&
2341         (!EncodingAlignment || !(imm % EncodingAlignment)))
2342       return false; // r+i can fold it if we can.
2343 
2344     // If this is an or of disjoint bitfields, we can codegen this as an add
2345     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2346     // disjoint.
2347     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2348 
2349     if (LHSKnown.Zero.getBoolValue()) {
2350       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2351       // If all of the bits are known zero on the LHS or RHS, the add won't
2352       // carry.
2353       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2354         Base = N.getOperand(0);
2355         Index = N.getOperand(1);
2356         return true;
2357       }
2358     }
2359   }
2360 
2361   return false;
2362 }
2363 
2364 // If we happen to be doing an i64 load or store into a stack slot that has
2365 // less than a 4-byte alignment, then the frame-index elimination may need to
2366 // use an indexed load or store instruction (because the offset may not be a
2367 // multiple of 4). The extra register needed to hold the offset comes from the
2368 // register scavenger, and it is possible that the scavenger will need to use
2369 // an emergency spill slot. As a result, we need to make sure that a spill slot
2370 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2371 // stack slot.
2372 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2373   // FIXME: This does not handle the LWA case.
2374   if (VT != MVT::i64)
2375     return;
2376 
2377   // NOTE: We'll exclude negative FIs here, which come from argument
2378   // lowering, because there are no known test cases triggering this problem
2379   // using packed structures (or similar). We can remove this exclusion if
2380   // we find such a test case. The reason why this is so test-case driven is
2381   // because this entire 'fixup' is only to prevent crashes (from the
2382   // register scavenger) on not-really-valid inputs. For example, if we have:
2383   //   %a = alloca i1
2384   //   %b = bitcast i1* %a to i64*
2385   //   store i64* a, i64 b
2386   // then the store should really be marked as 'align 1', but is not. If it
2387   // were marked as 'align 1' then the indexed form would have been
2388   // instruction-selected initially, and the problem this 'fixup' is preventing
2389   // won't happen regardless.
2390   if (FrameIdx < 0)
2391     return;
2392 
2393   MachineFunction &MF = DAG.getMachineFunction();
2394   MachineFrameInfo &MFI = MF.getFrameInfo();
2395 
2396   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2397   if (Align >= 4)
2398     return;
2399 
2400   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2401   FuncInfo->setHasNonRISpills();
2402 }
2403 
2404 /// Returns true if the address N can be represented by a base register plus
2405 /// a signed 16-bit displacement [r+imm], and if it is not better
2406 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2407 /// displacements that are multiples of that value.
2408 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2409                                             SDValue &Base,
2410                                             SelectionDAG &DAG,
2411                                             unsigned EncodingAlignment) const {
2412   // FIXME dl should come from parent load or store, not from address
2413   SDLoc dl(N);
2414   // If this can be more profitably realized as r+r, fail.
2415   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2416     return false;
2417 
2418   if (N.getOpcode() == ISD::ADD) {
2419     int16_t imm = 0;
2420     if (isIntS16Immediate(N.getOperand(1), imm) &&
2421         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2422       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2423       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2424         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2425         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2426       } else {
2427         Base = N.getOperand(0);
2428       }
2429       return true; // [r+i]
2430     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2431       // Match LOAD (ADD (X, Lo(G))).
2432       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2433              && "Cannot handle constant offsets yet!");
2434       Disp = N.getOperand(1).getOperand(0);  // The global address.
2435       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2436              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2437              Disp.getOpcode() == ISD::TargetConstantPool ||
2438              Disp.getOpcode() == ISD::TargetJumpTable);
2439       Base = N.getOperand(0);
2440       return true;  // [&g+r]
2441     }
2442   } else if (N.getOpcode() == ISD::OR) {
2443     int16_t imm = 0;
2444     if (isIntS16Immediate(N.getOperand(1), imm) &&
2445         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2446       // If this is an or of disjoint bitfields, we can codegen this as an add
2447       // (for better address arithmetic) if the LHS and RHS of the OR are
2448       // provably disjoint.
2449       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2450 
2451       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2452         // If all of the bits are known zero on the LHS or RHS, the add won't
2453         // carry.
2454         if (FrameIndexSDNode *FI =
2455               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2456           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2457           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2458         } else {
2459           Base = N.getOperand(0);
2460         }
2461         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2462         return true;
2463       }
2464     }
2465   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2466     // Loading from a constant address.
2467 
2468     // If this address fits entirely in a 16-bit sext immediate field, codegen
2469     // this as "d, 0"
2470     int16_t Imm;
2471     if (isIntS16Immediate(CN, Imm) &&
2472         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2473       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2474       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2475                              CN->getValueType(0));
2476       return true;
2477     }
2478 
2479     // Handle 32-bit sext immediates with LIS + addr mode.
2480     if ((CN->getValueType(0) == MVT::i32 ||
2481          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2482         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2483       int Addr = (int)CN->getZExtValue();
2484 
2485       // Otherwise, break this down into an LIS + disp.
2486       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2487 
2488       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2489                                    MVT::i32);
2490       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2491       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2492       return true;
2493     }
2494   }
2495 
2496   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2497   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2498     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2499     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2500   } else
2501     Base = N;
2502   return true;      // [r+0]
2503 }
2504 
2505 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2506 /// represented as an indexed [r+r] operation.
2507 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2508                                                 SDValue &Index,
2509                                                 SelectionDAG &DAG) const {
2510   // Check to see if we can easily represent this as an [r+r] address.  This
2511   // will fail if it thinks that the address is more profitably represented as
2512   // reg+imm, e.g. where imm = 0.
2513   if (SelectAddressRegReg(N, Base, Index, DAG))
2514     return true;
2515 
2516   // If the address is the result of an add, we will utilize the fact that the
2517   // address calculation includes an implicit add.  However, we can reduce
2518   // register pressure if we do not materialize a constant just for use as the
2519   // index register.  We only get rid of the add if it is not an add of a
2520   // value and a 16-bit signed constant and both have a single use.
2521   int16_t imm = 0;
2522   if (N.getOpcode() == ISD::ADD &&
2523       (!isIntS16Immediate(N.getOperand(1), imm) ||
2524        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2525     Base = N.getOperand(0);
2526     Index = N.getOperand(1);
2527     return true;
2528   }
2529 
2530   // Otherwise, do it the hard way, using R0 as the base register.
2531   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2532                          N.getValueType());
2533   Index = N;
2534   return true;
2535 }
2536 
2537 /// Returns true if we should use a direct load into vector instruction
2538 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2539 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2540 
2541   // If there are any other uses other than scalar to vector, then we should
2542   // keep it as a scalar load -> direct move pattern to prevent multiple
2543   // loads.
2544   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2545   if (!LD)
2546     return false;
2547 
2548   EVT MemVT = LD->getMemoryVT();
2549   if (!MemVT.isSimple())
2550     return false;
2551   switch(MemVT.getSimpleVT().SimpleTy) {
2552   case MVT::i64:
2553     break;
2554   case MVT::i32:
2555     if (!ST.hasP8Vector())
2556       return false;
2557     break;
2558   case MVT::i16:
2559   case MVT::i8:
2560     if (!ST.hasP9Vector())
2561       return false;
2562     break;
2563   default:
2564     return false;
2565   }
2566 
2567   SDValue LoadedVal(N, 0);
2568   if (!LoadedVal.hasOneUse())
2569     return false;
2570 
2571   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2572        UI != UE; ++UI)
2573     if (UI.getUse().get().getResNo() == 0 &&
2574         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2575       return false;
2576 
2577   return true;
2578 }
2579 
2580 /// getPreIndexedAddressParts - returns true by value, base pointer and
2581 /// offset pointer and addressing mode by reference if the node's address
2582 /// can be legally represented as pre-indexed load / store address.
2583 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2584                                                   SDValue &Offset,
2585                                                   ISD::MemIndexedMode &AM,
2586                                                   SelectionDAG &DAG) const {
2587   if (DisablePPCPreinc) return false;
2588 
2589   bool isLoad = true;
2590   SDValue Ptr;
2591   EVT VT;
2592   unsigned Alignment;
2593   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2594     Ptr = LD->getBasePtr();
2595     VT = LD->getMemoryVT();
2596     Alignment = LD->getAlignment();
2597   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2598     Ptr = ST->getBasePtr();
2599     VT  = ST->getMemoryVT();
2600     Alignment = ST->getAlignment();
2601     isLoad = false;
2602   } else
2603     return false;
2604 
2605   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2606   // instructions because we can fold these into a more efficient instruction
2607   // instead, (such as LXSD).
2608   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2609     return false;
2610   }
2611 
2612   // PowerPC doesn't have preinc load/store instructions for vectors (except
2613   // for QPX, which does have preinc r+r forms).
2614   if (VT.isVector()) {
2615     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2616       return false;
2617     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2618       AM = ISD::PRE_INC;
2619       return true;
2620     }
2621   }
2622 
2623   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2624     // Common code will reject creating a pre-inc form if the base pointer
2625     // is a frame index, or if N is a store and the base pointer is either
2626     // the same as or a predecessor of the value being stored.  Check for
2627     // those situations here, and try with swapped Base/Offset instead.
2628     bool Swap = false;
2629 
2630     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2631       Swap = true;
2632     else if (!isLoad) {
2633       SDValue Val = cast<StoreSDNode>(N)->getValue();
2634       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2635         Swap = true;
2636     }
2637 
2638     if (Swap)
2639       std::swap(Base, Offset);
2640 
2641     AM = ISD::PRE_INC;
2642     return true;
2643   }
2644 
2645   // LDU/STU can only handle immediates that are a multiple of 4.
2646   if (VT != MVT::i64) {
2647     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2648       return false;
2649   } else {
2650     // LDU/STU need an address with at least 4-byte alignment.
2651     if (Alignment < 4)
2652       return false;
2653 
2654     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2655       return false;
2656   }
2657 
2658   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2659     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2660     // sext i32 to i64 when addr mode is r+i.
2661     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2662         LD->getExtensionType() == ISD::SEXTLOAD &&
2663         isa<ConstantSDNode>(Offset))
2664       return false;
2665   }
2666 
2667   AM = ISD::PRE_INC;
2668   return true;
2669 }
2670 
2671 //===----------------------------------------------------------------------===//
2672 //  LowerOperation implementation
2673 //===----------------------------------------------------------------------===//
2674 
2675 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2676 /// and LoOpFlags to the target MO flags.
2677 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2678                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2679                                const GlobalValue *GV = nullptr) {
2680   HiOpFlags = PPCII::MO_HA;
2681   LoOpFlags = PPCII::MO_LO;
2682 
2683   // Don't use the pic base if not in PIC relocation model.
2684   if (IsPIC) {
2685     HiOpFlags |= PPCII::MO_PIC_FLAG;
2686     LoOpFlags |= PPCII::MO_PIC_FLAG;
2687   }
2688 
2689   // If this is a reference to a global value that requires a non-lazy-ptr, make
2690   // sure that instruction lowering adds it.
2691   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2692     HiOpFlags |= PPCII::MO_NLP_FLAG;
2693     LoOpFlags |= PPCII::MO_NLP_FLAG;
2694 
2695     if (GV->hasHiddenVisibility()) {
2696       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2697       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2698     }
2699   }
2700 }
2701 
2702 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2703                              SelectionDAG &DAG) {
2704   SDLoc DL(HiPart);
2705   EVT PtrVT = HiPart.getValueType();
2706   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2707 
2708   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2709   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2710 
2711   // With PIC, the first instruction is actually "GR+hi(&G)".
2712   if (isPIC)
2713     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2714                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2715 
2716   // Generate non-pic code that has direct accesses to the constant pool.
2717   // The address of the global is just (hi(&g)+lo(&g)).
2718   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2719 }
2720 
2721 static void setUsesTOCBasePtr(MachineFunction &MF) {
2722   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2723   FuncInfo->setUsesTOCBasePtr();
2724 }
2725 
2726 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2727   setUsesTOCBasePtr(DAG.getMachineFunction());
2728 }
2729 
2730 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2731                                        SDValue GA) const {
2732   const bool Is64Bit = Subtarget.isPPC64();
2733   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2734   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2735                         : Subtarget.isAIXABI()
2736                               ? DAG.getRegister(PPC::R2, VT)
2737                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2738   SDValue Ops[] = { GA, Reg };
2739   return DAG.getMemIntrinsicNode(
2740       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2741       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2742       MachineMemOperand::MOLoad);
2743 }
2744 
2745 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2746                                              SelectionDAG &DAG) const {
2747   EVT PtrVT = Op.getValueType();
2748   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2749   const Constant *C = CP->getConstVal();
2750 
2751   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2752   // The actual address of the GlobalValue is stored in the TOC.
2753   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2754     setUsesTOCBasePtr(DAG);
2755     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2756     return getTOCEntry(DAG, SDLoc(CP), GA);
2757   }
2758 
2759   unsigned MOHiFlag, MOLoFlag;
2760   bool IsPIC = isPositionIndependent();
2761   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2762 
2763   if (IsPIC && Subtarget.isSVR4ABI()) {
2764     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2765                                            PPCII::MO_PIC_FLAG);
2766     return getTOCEntry(DAG, SDLoc(CP), GA);
2767   }
2768 
2769   SDValue CPIHi =
2770     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2771   SDValue CPILo =
2772     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2773   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2774 }
2775 
2776 // For 64-bit PowerPC, prefer the more compact relative encodings.
2777 // This trades 32 bits per jump table entry for one or two instructions
2778 // on the jump site.
2779 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2780   if (isJumpTableRelative())
2781     return MachineJumpTableInfo::EK_LabelDifference32;
2782 
2783   return TargetLowering::getJumpTableEncoding();
2784 }
2785 
2786 bool PPCTargetLowering::isJumpTableRelative() const {
2787   if (UseAbsoluteJumpTables)
2788     return false;
2789   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2790     return true;
2791   return TargetLowering::isJumpTableRelative();
2792 }
2793 
2794 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2795                                                     SelectionDAG &DAG) const {
2796   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2797     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2798 
2799   switch (getTargetMachine().getCodeModel()) {
2800   case CodeModel::Small:
2801   case CodeModel::Medium:
2802     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2803   default:
2804     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2805                        getPointerTy(DAG.getDataLayout()));
2806   }
2807 }
2808 
2809 const MCExpr *
2810 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2811                                                 unsigned JTI,
2812                                                 MCContext &Ctx) const {
2813   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2814     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2815 
2816   switch (getTargetMachine().getCodeModel()) {
2817   case CodeModel::Small:
2818   case CodeModel::Medium:
2819     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2820   default:
2821     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2822   }
2823 }
2824 
2825 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2826   EVT PtrVT = Op.getValueType();
2827   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2828 
2829   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2830   // The actual address of the GlobalValue is stored in the TOC.
2831   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2832     setUsesTOCBasePtr(DAG);
2833     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2834     return getTOCEntry(DAG, SDLoc(JT), GA);
2835   }
2836 
2837   unsigned MOHiFlag, MOLoFlag;
2838   bool IsPIC = isPositionIndependent();
2839   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2840 
2841   if (IsPIC && Subtarget.isSVR4ABI()) {
2842     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2843                                         PPCII::MO_PIC_FLAG);
2844     return getTOCEntry(DAG, SDLoc(GA), GA);
2845   }
2846 
2847   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2848   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2849   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2850 }
2851 
2852 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2853                                              SelectionDAG &DAG) const {
2854   EVT PtrVT = Op.getValueType();
2855   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2856   const BlockAddress *BA = BASDN->getBlockAddress();
2857 
2858   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2859   // The actual BlockAddress is stored in the TOC.
2860   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2861     setUsesTOCBasePtr(DAG);
2862     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2863     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2864   }
2865 
2866   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2867   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2868     return getTOCEntry(
2869         DAG, SDLoc(BASDN),
2870         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2871 
2872   unsigned MOHiFlag, MOLoFlag;
2873   bool IsPIC = isPositionIndependent();
2874   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2875   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2876   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2877   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2878 }
2879 
2880 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2881                                               SelectionDAG &DAG) const {
2882   // FIXME: TLS addresses currently use medium model code sequences,
2883   // which is the most useful form.  Eventually support for small and
2884   // large models could be added if users need it, at the cost of
2885   // additional complexity.
2886   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2887   if (DAG.getTarget().useEmulatedTLS())
2888     return LowerToTLSEmulatedModel(GA, DAG);
2889 
2890   SDLoc dl(GA);
2891   const GlobalValue *GV = GA->getGlobal();
2892   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2893   bool is64bit = Subtarget.isPPC64();
2894   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2895   PICLevel::Level picLevel = M->getPICLevel();
2896 
2897   const TargetMachine &TM = getTargetMachine();
2898   TLSModel::Model Model = TM.getTLSModel(GV);
2899 
2900   if (Model == TLSModel::LocalExec) {
2901     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2902                                                PPCII::MO_TPREL_HA);
2903     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2904                                                PPCII::MO_TPREL_LO);
2905     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2906                              : DAG.getRegister(PPC::R2, MVT::i32);
2907 
2908     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2909     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2910   }
2911 
2912   if (Model == TLSModel::InitialExec) {
2913     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2914     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2915                                                 PPCII::MO_TLS);
2916     SDValue GOTPtr;
2917     if (is64bit) {
2918       setUsesTOCBasePtr(DAG);
2919       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2920       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2921                            PtrVT, GOTReg, TGA);
2922     } else {
2923       if (!TM.isPositionIndependent())
2924         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2925       else if (picLevel == PICLevel::SmallPIC)
2926         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2927       else
2928         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2929     }
2930     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2931                                    PtrVT, TGA, GOTPtr);
2932     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2933   }
2934 
2935   if (Model == TLSModel::GeneralDynamic) {
2936     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2937     SDValue GOTPtr;
2938     if (is64bit) {
2939       setUsesTOCBasePtr(DAG);
2940       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2941       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2942                                    GOTReg, TGA);
2943     } else {
2944       if (picLevel == PICLevel::SmallPIC)
2945         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2946       else
2947         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2948     }
2949     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2950                        GOTPtr, TGA, TGA);
2951   }
2952 
2953   if (Model == TLSModel::LocalDynamic) {
2954     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2955     SDValue GOTPtr;
2956     if (is64bit) {
2957       setUsesTOCBasePtr(DAG);
2958       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2959       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2960                            GOTReg, TGA);
2961     } else {
2962       if (picLevel == PICLevel::SmallPIC)
2963         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2964       else
2965         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2966     }
2967     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2968                                   PtrVT, GOTPtr, TGA, TGA);
2969     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2970                                       PtrVT, TLSAddr, TGA);
2971     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2972   }
2973 
2974   llvm_unreachable("Unknown TLS model!");
2975 }
2976 
2977 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2978                                               SelectionDAG &DAG) const {
2979   EVT PtrVT = Op.getValueType();
2980   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2981   SDLoc DL(GSDN);
2982   const GlobalValue *GV = GSDN->getGlobal();
2983 
2984   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
2985   // The actual address of the GlobalValue is stored in the TOC.
2986   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2987     setUsesTOCBasePtr(DAG);
2988     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2989     return getTOCEntry(DAG, DL, GA);
2990   }
2991 
2992   unsigned MOHiFlag, MOLoFlag;
2993   bool IsPIC = isPositionIndependent();
2994   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2995 
2996   if (IsPIC && Subtarget.isSVR4ABI()) {
2997     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2998                                             GSDN->getOffset(),
2999                                             PPCII::MO_PIC_FLAG);
3000     return getTOCEntry(DAG, DL, GA);
3001   }
3002 
3003   SDValue GAHi =
3004     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3005   SDValue GALo =
3006     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3007 
3008   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3009 
3010   // If the global reference is actually to a non-lazy-pointer, we have to do an
3011   // extra load to get the address of the global.
3012   if (MOHiFlag & PPCII::MO_NLP_FLAG)
3013     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3014   return Ptr;
3015 }
3016 
3017 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3018   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3019   SDLoc dl(Op);
3020 
3021   if (Op.getValueType() == MVT::v2i64) {
3022     // When the operands themselves are v2i64 values, we need to do something
3023     // special because VSX has no underlying comparison operations for these.
3024     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3025       // Equality can be handled by casting to the legal type for Altivec
3026       // comparisons, everything else needs to be expanded.
3027       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3028         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3029                  DAG.getSetCC(dl, MVT::v4i32,
3030                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3031                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3032                    CC));
3033       }
3034 
3035       return SDValue();
3036     }
3037 
3038     // We handle most of these in the usual way.
3039     return Op;
3040   }
3041 
3042   // If we're comparing for equality to zero, expose the fact that this is
3043   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3044   // fold the new nodes.
3045   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3046     return V;
3047 
3048   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3049     // Leave comparisons against 0 and -1 alone for now, since they're usually
3050     // optimized.  FIXME: revisit this when we can custom lower all setcc
3051     // optimizations.
3052     if (C->isAllOnesValue() || C->isNullValue())
3053       return SDValue();
3054   }
3055 
3056   // If we have an integer seteq/setne, turn it into a compare against zero
3057   // by xor'ing the rhs with the lhs, which is faster than setting a
3058   // condition register, reading it back out, and masking the correct bit.  The
3059   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3060   // the result to other bit-twiddling opportunities.
3061   EVT LHSVT = Op.getOperand(0).getValueType();
3062   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3063     EVT VT = Op.getValueType();
3064     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3065                                 Op.getOperand(1));
3066     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3067   }
3068   return SDValue();
3069 }
3070 
3071 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3072   SDNode *Node = Op.getNode();
3073   EVT VT = Node->getValueType(0);
3074   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3075   SDValue InChain = Node->getOperand(0);
3076   SDValue VAListPtr = Node->getOperand(1);
3077   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3078   SDLoc dl(Node);
3079 
3080   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3081 
3082   // gpr_index
3083   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3084                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3085   InChain = GprIndex.getValue(1);
3086 
3087   if (VT == MVT::i64) {
3088     // Check if GprIndex is even
3089     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3090                                  DAG.getConstant(1, dl, MVT::i32));
3091     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3092                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3093     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3094                                           DAG.getConstant(1, dl, MVT::i32));
3095     // Align GprIndex to be even if it isn't
3096     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3097                            GprIndex);
3098   }
3099 
3100   // fpr index is 1 byte after gpr
3101   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3102                                DAG.getConstant(1, dl, MVT::i32));
3103 
3104   // fpr
3105   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3106                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3107   InChain = FprIndex.getValue(1);
3108 
3109   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3110                                        DAG.getConstant(8, dl, MVT::i32));
3111 
3112   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3113                                         DAG.getConstant(4, dl, MVT::i32));
3114 
3115   // areas
3116   SDValue OverflowArea =
3117       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3118   InChain = OverflowArea.getValue(1);
3119 
3120   SDValue RegSaveArea =
3121       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3122   InChain = RegSaveArea.getValue(1);
3123 
3124   // select overflow_area if index > 8
3125   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3126                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3127 
3128   // adjustment constant gpr_index * 4/8
3129   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3130                                     VT.isInteger() ? GprIndex : FprIndex,
3131                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3132                                                     MVT::i32));
3133 
3134   // OurReg = RegSaveArea + RegConstant
3135   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3136                                RegConstant);
3137 
3138   // Floating types are 32 bytes into RegSaveArea
3139   if (VT.isFloatingPoint())
3140     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3141                          DAG.getConstant(32, dl, MVT::i32));
3142 
3143   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3144   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3145                                    VT.isInteger() ? GprIndex : FprIndex,
3146                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3147                                                    MVT::i32));
3148 
3149   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3150                               VT.isInteger() ? VAListPtr : FprPtr,
3151                               MachinePointerInfo(SV), MVT::i8);
3152 
3153   // determine if we should load from reg_save_area or overflow_area
3154   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3155 
3156   // increase overflow_area by 4/8 if gpr/fpr > 8
3157   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3158                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3159                                           dl, MVT::i32));
3160 
3161   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3162                              OverflowAreaPlusN);
3163 
3164   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3165                               MachinePointerInfo(), MVT::i32);
3166 
3167   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3168 }
3169 
3170 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3171   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3172 
3173   // We have to copy the entire va_list struct:
3174   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3175   return DAG.getMemcpy(Op.getOperand(0), Op,
3176                        Op.getOperand(1), Op.getOperand(2),
3177                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3178                        false, MachinePointerInfo(), MachinePointerInfo());
3179 }
3180 
3181 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3182                                                   SelectionDAG &DAG) const {
3183   if (Subtarget.isAIXABI())
3184     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3185 
3186   return Op.getOperand(0);
3187 }
3188 
3189 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3190                                                 SelectionDAG &DAG) const {
3191   if (Subtarget.isAIXABI())
3192     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3193 
3194   SDValue Chain = Op.getOperand(0);
3195   SDValue Trmp = Op.getOperand(1); // trampoline
3196   SDValue FPtr = Op.getOperand(2); // nested function
3197   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3198   SDLoc dl(Op);
3199 
3200   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3201   bool isPPC64 = (PtrVT == MVT::i64);
3202   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3203 
3204   TargetLowering::ArgListTy Args;
3205   TargetLowering::ArgListEntry Entry;
3206 
3207   Entry.Ty = IntPtrTy;
3208   Entry.Node = Trmp; Args.push_back(Entry);
3209 
3210   // TrampSize == (isPPC64 ? 48 : 40);
3211   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3212                                isPPC64 ? MVT::i64 : MVT::i32);
3213   Args.push_back(Entry);
3214 
3215   Entry.Node = FPtr; Args.push_back(Entry);
3216   Entry.Node = Nest; Args.push_back(Entry);
3217 
3218   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3219   TargetLowering::CallLoweringInfo CLI(DAG);
3220   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3221       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3222       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3223 
3224   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3225   return CallResult.second;
3226 }
3227 
3228 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3229   MachineFunction &MF = DAG.getMachineFunction();
3230   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3231   EVT PtrVT = getPointerTy(MF.getDataLayout());
3232 
3233   SDLoc dl(Op);
3234 
3235   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3236     // vastart just stores the address of the VarArgsFrameIndex slot into the
3237     // memory location argument.
3238     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3239     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3240     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3241                         MachinePointerInfo(SV));
3242   }
3243 
3244   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3245   // We suppose the given va_list is already allocated.
3246   //
3247   // typedef struct {
3248   //  char gpr;     /* index into the array of 8 GPRs
3249   //                 * stored in the register save area
3250   //                 * gpr=0 corresponds to r3,
3251   //                 * gpr=1 to r4, etc.
3252   //                 */
3253   //  char fpr;     /* index into the array of 8 FPRs
3254   //                 * stored in the register save area
3255   //                 * fpr=0 corresponds to f1,
3256   //                 * fpr=1 to f2, etc.
3257   //                 */
3258   //  char *overflow_arg_area;
3259   //                /* location on stack that holds
3260   //                 * the next overflow argument
3261   //                 */
3262   //  char *reg_save_area;
3263   //               /* where r3:r10 and f1:f8 (if saved)
3264   //                * are stored
3265   //                */
3266   // } va_list[1];
3267 
3268   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3269   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3270   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3271                                             PtrVT);
3272   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3273                                  PtrVT);
3274 
3275   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3276   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3277 
3278   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3279   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3280 
3281   uint64_t FPROffset = 1;
3282   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3283 
3284   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3285 
3286   // Store first byte : number of int regs
3287   SDValue firstStore =
3288       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3289                         MachinePointerInfo(SV), MVT::i8);
3290   uint64_t nextOffset = FPROffset;
3291   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3292                                   ConstFPROffset);
3293 
3294   // Store second byte : number of float regs
3295   SDValue secondStore =
3296       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3297                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3298   nextOffset += StackOffset;
3299   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3300 
3301   // Store second word : arguments given on stack
3302   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3303                                     MachinePointerInfo(SV, nextOffset));
3304   nextOffset += FrameOffset;
3305   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3306 
3307   // Store third word : arguments given in registers
3308   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3309                       MachinePointerInfo(SV, nextOffset));
3310 }
3311 
3312 /// FPR - The set of FP registers that should be allocated for arguments
3313 /// on Darwin and AIX.
3314 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3315                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3316                                 PPC::F11, PPC::F12, PPC::F13};
3317 
3318 /// QFPR - The set of QPX registers that should be allocated for arguments.
3319 static const MCPhysReg QFPR[] = {
3320     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3321     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3322 
3323 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3324 /// the stack.
3325 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3326                                        unsigned PtrByteSize) {
3327   unsigned ArgSize = ArgVT.getStoreSize();
3328   if (Flags.isByVal())
3329     ArgSize = Flags.getByValSize();
3330 
3331   // Round up to multiples of the pointer size, except for array members,
3332   // which are always packed.
3333   if (!Flags.isInConsecutiveRegs())
3334     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3335 
3336   return ArgSize;
3337 }
3338 
3339 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3340 /// on the stack.
3341 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3342                                             ISD::ArgFlagsTy Flags,
3343                                             unsigned PtrByteSize) {
3344   unsigned Align = PtrByteSize;
3345 
3346   // Altivec parameters are padded to a 16 byte boundary.
3347   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3348       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3349       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3350       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3351     Align = 16;
3352   // QPX vector types stored in double-precision are padded to a 32 byte
3353   // boundary.
3354   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3355     Align = 32;
3356 
3357   // ByVal parameters are aligned as requested.
3358   if (Flags.isByVal()) {
3359     unsigned BVAlign = Flags.getByValAlign();
3360     if (BVAlign > PtrByteSize) {
3361       if (BVAlign % PtrByteSize != 0)
3362           llvm_unreachable(
3363             "ByVal alignment is not a multiple of the pointer size");
3364 
3365       Align = BVAlign;
3366     }
3367   }
3368 
3369   // Array members are always packed to their original alignment.
3370   if (Flags.isInConsecutiveRegs()) {
3371     // If the array member was split into multiple registers, the first
3372     // needs to be aligned to the size of the full type.  (Except for
3373     // ppcf128, which is only aligned as its f64 components.)
3374     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3375       Align = OrigVT.getStoreSize();
3376     else
3377       Align = ArgVT.getStoreSize();
3378   }
3379 
3380   return Align;
3381 }
3382 
3383 /// CalculateStackSlotUsed - Return whether this argument will use its
3384 /// stack slot (instead of being passed in registers).  ArgOffset,
3385 /// AvailableFPRs, and AvailableVRs must hold the current argument
3386 /// position, and will be updated to account for this argument.
3387 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3388                                    ISD::ArgFlagsTy Flags,
3389                                    unsigned PtrByteSize,
3390                                    unsigned LinkageSize,
3391                                    unsigned ParamAreaSize,
3392                                    unsigned &ArgOffset,
3393                                    unsigned &AvailableFPRs,
3394                                    unsigned &AvailableVRs, bool HasQPX) {
3395   bool UseMemory = false;
3396 
3397   // Respect alignment of argument on the stack.
3398   unsigned Align =
3399     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3400   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3401   // If there's no space left in the argument save area, we must
3402   // use memory (this check also catches zero-sized arguments).
3403   if (ArgOffset >= LinkageSize + ParamAreaSize)
3404     UseMemory = true;
3405 
3406   // Allocate argument on the stack.
3407   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3408   if (Flags.isInConsecutiveRegsLast())
3409     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3410   // If we overran the argument save area, we must use memory
3411   // (this check catches arguments passed partially in memory)
3412   if (ArgOffset > LinkageSize + ParamAreaSize)
3413     UseMemory = true;
3414 
3415   // However, if the argument is actually passed in an FPR or a VR,
3416   // we don't use memory after all.
3417   if (!Flags.isByVal()) {
3418     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3419         // QPX registers overlap with the scalar FP registers.
3420         (HasQPX && (ArgVT == MVT::v4f32 ||
3421                     ArgVT == MVT::v4f64 ||
3422                     ArgVT == MVT::v4i1)))
3423       if (AvailableFPRs > 0) {
3424         --AvailableFPRs;
3425         return false;
3426       }
3427     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3428         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3429         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3430         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3431       if (AvailableVRs > 0) {
3432         --AvailableVRs;
3433         return false;
3434       }
3435   }
3436 
3437   return UseMemory;
3438 }
3439 
3440 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3441 /// ensure minimum alignment required for target.
3442 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3443                                      unsigned NumBytes) {
3444   unsigned TargetAlign = Lowering->getStackAlignment();
3445   unsigned AlignMask = TargetAlign - 1;
3446   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3447   return NumBytes;
3448 }
3449 
3450 SDValue PPCTargetLowering::LowerFormalArguments(
3451     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3452     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3453     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3454   if (Subtarget.isAIXABI())
3455     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3456                                     InVals);
3457   if (Subtarget.is64BitELFABI())
3458     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3459                                        InVals);
3460   if (Subtarget.is32BitELFABI())
3461     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3462                                        InVals);
3463 
3464   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3465                                      InVals);
3466 }
3467 
3468 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3469     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3470     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3471     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3472 
3473   // 32-bit SVR4 ABI Stack Frame Layout:
3474   //              +-----------------------------------+
3475   //        +-->  |            Back chain             |
3476   //        |     +-----------------------------------+
3477   //        |     | Floating-point register save area |
3478   //        |     +-----------------------------------+
3479   //        |     |    General register save area     |
3480   //        |     +-----------------------------------+
3481   //        |     |          CR save word             |
3482   //        |     +-----------------------------------+
3483   //        |     |         VRSAVE save word          |
3484   //        |     +-----------------------------------+
3485   //        |     |         Alignment padding         |
3486   //        |     +-----------------------------------+
3487   //        |     |     Vector register save area     |
3488   //        |     +-----------------------------------+
3489   //        |     |       Local variable space        |
3490   //        |     +-----------------------------------+
3491   //        |     |        Parameter list area        |
3492   //        |     +-----------------------------------+
3493   //        |     |           LR save word            |
3494   //        |     +-----------------------------------+
3495   // SP-->  +---  |            Back chain             |
3496   //              +-----------------------------------+
3497   //
3498   // Specifications:
3499   //   System V Application Binary Interface PowerPC Processor Supplement
3500   //   AltiVec Technology Programming Interface Manual
3501 
3502   MachineFunction &MF = DAG.getMachineFunction();
3503   MachineFrameInfo &MFI = MF.getFrameInfo();
3504   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3505 
3506   EVT PtrVT = getPointerTy(MF.getDataLayout());
3507   // Potential tail calls could cause overwriting of argument stack slots.
3508   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3509                        (CallConv == CallingConv::Fast));
3510   unsigned PtrByteSize = 4;
3511 
3512   // Assign locations to all of the incoming arguments.
3513   SmallVector<CCValAssign, 16> ArgLocs;
3514   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3515                  *DAG.getContext());
3516 
3517   // Reserve space for the linkage area on the stack.
3518   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3519   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3520   if (useSoftFloat())
3521     CCInfo.PreAnalyzeFormalArguments(Ins);
3522 
3523   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3524   CCInfo.clearWasPPCF128();
3525 
3526   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3527     CCValAssign &VA = ArgLocs[i];
3528 
3529     // Arguments stored in registers.
3530     if (VA.isRegLoc()) {
3531       const TargetRegisterClass *RC;
3532       EVT ValVT = VA.getValVT();
3533 
3534       switch (ValVT.getSimpleVT().SimpleTy) {
3535         default:
3536           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3537         case MVT::i1:
3538         case MVT::i32:
3539           RC = &PPC::GPRCRegClass;
3540           break;
3541         case MVT::f32:
3542           if (Subtarget.hasP8Vector())
3543             RC = &PPC::VSSRCRegClass;
3544           else if (Subtarget.hasSPE())
3545             RC = &PPC::GPRCRegClass;
3546           else
3547             RC = &PPC::F4RCRegClass;
3548           break;
3549         case MVT::f64:
3550           if (Subtarget.hasVSX())
3551             RC = &PPC::VSFRCRegClass;
3552           else if (Subtarget.hasSPE())
3553             // SPE passes doubles in GPR pairs.
3554             RC = &PPC::GPRCRegClass;
3555           else
3556             RC = &PPC::F8RCRegClass;
3557           break;
3558         case MVT::v16i8:
3559         case MVT::v8i16:
3560         case MVT::v4i32:
3561           RC = &PPC::VRRCRegClass;
3562           break;
3563         case MVT::v4f32:
3564           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3565           break;
3566         case MVT::v2f64:
3567         case MVT::v2i64:
3568           RC = &PPC::VRRCRegClass;
3569           break;
3570         case MVT::v4f64:
3571           RC = &PPC::QFRCRegClass;
3572           break;
3573         case MVT::v4i1:
3574           RC = &PPC::QBRCRegClass;
3575           break;
3576       }
3577 
3578       SDValue ArgValue;
3579       // Transform the arguments stored in physical registers into
3580       // virtual ones.
3581       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3582         assert(i + 1 < e && "No second half of double precision argument");
3583         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3584         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3585         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3586         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3587         if (!Subtarget.isLittleEndian())
3588           std::swap (ArgValueLo, ArgValueHi);
3589         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3590                                ArgValueHi);
3591       } else {
3592         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3593         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3594                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3595         if (ValVT == MVT::i1)
3596           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3597       }
3598 
3599       InVals.push_back(ArgValue);
3600     } else {
3601       // Argument stored in memory.
3602       assert(VA.isMemLoc());
3603 
3604       // Get the extended size of the argument type in stack
3605       unsigned ArgSize = VA.getLocVT().getStoreSize();
3606       // Get the actual size of the argument type
3607       unsigned ObjSize = VA.getValVT().getStoreSize();
3608       unsigned ArgOffset = VA.getLocMemOffset();
3609       // Stack objects in PPC32 are right justified.
3610       ArgOffset += ArgSize - ObjSize;
3611       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3612 
3613       // Create load nodes to retrieve arguments from the stack.
3614       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3615       InVals.push_back(
3616           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3617     }
3618   }
3619 
3620   // Assign locations to all of the incoming aggregate by value arguments.
3621   // Aggregates passed by value are stored in the local variable space of the
3622   // caller's stack frame, right above the parameter list area.
3623   SmallVector<CCValAssign, 16> ByValArgLocs;
3624   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3625                       ByValArgLocs, *DAG.getContext());
3626 
3627   // Reserve stack space for the allocations in CCInfo.
3628   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3629 
3630   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3631 
3632   // Area that is at least reserved in the caller of this function.
3633   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3634   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3635 
3636   // Set the size that is at least reserved in caller of this function.  Tail
3637   // call optimized function's reserved stack space needs to be aligned so that
3638   // taking the difference between two stack areas will result in an aligned
3639   // stack.
3640   MinReservedArea =
3641       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3642   FuncInfo->setMinReservedArea(MinReservedArea);
3643 
3644   SmallVector<SDValue, 8> MemOps;
3645 
3646   // If the function takes variable number of arguments, make a frame index for
3647   // the start of the first vararg value... for expansion of llvm.va_start.
3648   if (isVarArg) {
3649     static const MCPhysReg GPArgRegs[] = {
3650       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3651       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3652     };
3653     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3654 
3655     static const MCPhysReg FPArgRegs[] = {
3656       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3657       PPC::F8
3658     };
3659     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3660 
3661     if (useSoftFloat() || hasSPE())
3662        NumFPArgRegs = 0;
3663 
3664     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3665     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3666 
3667     // Make room for NumGPArgRegs and NumFPArgRegs.
3668     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3669                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3670 
3671     FuncInfo->setVarArgsStackOffset(
3672       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3673                             CCInfo.getNextStackOffset(), true));
3674 
3675     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3676     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3677 
3678     // The fixed integer arguments of a variadic function are stored to the
3679     // VarArgsFrameIndex on the stack so that they may be loaded by
3680     // dereferencing the result of va_next.
3681     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3682       // Get an existing live-in vreg, or add a new one.
3683       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3684       if (!VReg)
3685         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3686 
3687       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3688       SDValue Store =
3689           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3690       MemOps.push_back(Store);
3691       // Increment the address by four for the next argument to store
3692       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3693       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3694     }
3695 
3696     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3697     // is set.
3698     // The double arguments are stored to the VarArgsFrameIndex
3699     // on the stack.
3700     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3701       // Get an existing live-in vreg, or add a new one.
3702       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3703       if (!VReg)
3704         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3705 
3706       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3707       SDValue Store =
3708           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3709       MemOps.push_back(Store);
3710       // Increment the address by eight for the next argument to store
3711       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3712                                          PtrVT);
3713       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3714     }
3715   }
3716 
3717   if (!MemOps.empty())
3718     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3719 
3720   return Chain;
3721 }
3722 
3723 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3724 // value to MVT::i64 and then truncate to the correct register size.
3725 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3726                                              EVT ObjectVT, SelectionDAG &DAG,
3727                                              SDValue ArgVal,
3728                                              const SDLoc &dl) const {
3729   if (Flags.isSExt())
3730     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3731                          DAG.getValueType(ObjectVT));
3732   else if (Flags.isZExt())
3733     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3734                          DAG.getValueType(ObjectVT));
3735 
3736   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3737 }
3738 
3739 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3740     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3741     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3742     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3743   // TODO: add description of PPC stack frame format, or at least some docs.
3744   //
3745   bool isELFv2ABI = Subtarget.isELFv2ABI();
3746   bool isLittleEndian = Subtarget.isLittleEndian();
3747   MachineFunction &MF = DAG.getMachineFunction();
3748   MachineFrameInfo &MFI = MF.getFrameInfo();
3749   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3750 
3751   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3752          "fastcc not supported on varargs functions");
3753 
3754   EVT PtrVT = getPointerTy(MF.getDataLayout());
3755   // Potential tail calls could cause overwriting of argument stack slots.
3756   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3757                        (CallConv == CallingConv::Fast));
3758   unsigned PtrByteSize = 8;
3759   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3760 
3761   static const MCPhysReg GPR[] = {
3762     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3763     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3764   };
3765   static const MCPhysReg VR[] = {
3766     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3767     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3768   };
3769 
3770   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3771   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3772   const unsigned Num_VR_Regs  = array_lengthof(VR);
3773   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3774 
3775   // Do a first pass over the arguments to determine whether the ABI
3776   // guarantees that our caller has allocated the parameter save area
3777   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3778   // in the ELFv2 ABI, it is true if this is a vararg function or if
3779   // any parameter is located in a stack slot.
3780 
3781   bool HasParameterArea = !isELFv2ABI || isVarArg;
3782   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3783   unsigned NumBytes = LinkageSize;
3784   unsigned AvailableFPRs = Num_FPR_Regs;
3785   unsigned AvailableVRs = Num_VR_Regs;
3786   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3787     if (Ins[i].Flags.isNest())
3788       continue;
3789 
3790     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3791                                PtrByteSize, LinkageSize, ParamAreaSize,
3792                                NumBytes, AvailableFPRs, AvailableVRs,
3793                                Subtarget.hasQPX()))
3794       HasParameterArea = true;
3795   }
3796 
3797   // Add DAG nodes to load the arguments or copy them out of registers.  On
3798   // entry to a function on PPC, the arguments start after the linkage area,
3799   // although the first ones are often in registers.
3800 
3801   unsigned ArgOffset = LinkageSize;
3802   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3803   unsigned &QFPR_idx = FPR_idx;
3804   SmallVector<SDValue, 8> MemOps;
3805   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3806   unsigned CurArgIdx = 0;
3807   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3808     SDValue ArgVal;
3809     bool needsLoad = false;
3810     EVT ObjectVT = Ins[ArgNo].VT;
3811     EVT OrigVT = Ins[ArgNo].ArgVT;
3812     unsigned ObjSize = ObjectVT.getStoreSize();
3813     unsigned ArgSize = ObjSize;
3814     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3815     if (Ins[ArgNo].isOrigArg()) {
3816       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3817       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3818     }
3819     // We re-align the argument offset for each argument, except when using the
3820     // fast calling convention, when we need to make sure we do that only when
3821     // we'll actually use a stack slot.
3822     unsigned CurArgOffset, Align;
3823     auto ComputeArgOffset = [&]() {
3824       /* Respect alignment of argument on the stack.  */
3825       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3826       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3827       CurArgOffset = ArgOffset;
3828     };
3829 
3830     if (CallConv != CallingConv::Fast) {
3831       ComputeArgOffset();
3832 
3833       /* Compute GPR index associated with argument offset.  */
3834       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3835       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3836     }
3837 
3838     // FIXME the codegen can be much improved in some cases.
3839     // We do not have to keep everything in memory.
3840     if (Flags.isByVal()) {
3841       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3842 
3843       if (CallConv == CallingConv::Fast)
3844         ComputeArgOffset();
3845 
3846       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3847       ObjSize = Flags.getByValSize();
3848       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3849       // Empty aggregate parameters do not take up registers.  Examples:
3850       //   struct { } a;
3851       //   union  { } b;
3852       //   int c[0];
3853       // etc.  However, we have to provide a place-holder in InVals, so
3854       // pretend we have an 8-byte item at the current address for that
3855       // purpose.
3856       if (!ObjSize) {
3857         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3858         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3859         InVals.push_back(FIN);
3860         continue;
3861       }
3862 
3863       // Create a stack object covering all stack doublewords occupied
3864       // by the argument.  If the argument is (fully or partially) on
3865       // the stack, or if the argument is fully in registers but the
3866       // caller has allocated the parameter save anyway, we can refer
3867       // directly to the caller's stack frame.  Otherwise, create a
3868       // local copy in our own frame.
3869       int FI;
3870       if (HasParameterArea ||
3871           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3872         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3873       else
3874         FI = MFI.CreateStackObject(ArgSize, Align, false);
3875       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3876 
3877       // Handle aggregates smaller than 8 bytes.
3878       if (ObjSize < PtrByteSize) {
3879         // The value of the object is its address, which differs from the
3880         // address of the enclosing doubleword on big-endian systems.
3881         SDValue Arg = FIN;
3882         if (!isLittleEndian) {
3883           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3884           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3885         }
3886         InVals.push_back(Arg);
3887 
3888         if (GPR_idx != Num_GPR_Regs) {
3889           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3890           FuncInfo->addLiveInAttr(VReg, Flags);
3891           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3892           SDValue Store;
3893 
3894           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3895             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3896                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3897             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3898                                       MachinePointerInfo(&*FuncArg), ObjType);
3899           } else {
3900             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3901             // store the whole register as-is to the parameter save area
3902             // slot.
3903             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3904                                  MachinePointerInfo(&*FuncArg));
3905           }
3906 
3907           MemOps.push_back(Store);
3908         }
3909         // Whether we copied from a register or not, advance the offset
3910         // into the parameter save area by a full doubleword.
3911         ArgOffset += PtrByteSize;
3912         continue;
3913       }
3914 
3915       // The value of the object is its address, which is the address of
3916       // its first stack doubleword.
3917       InVals.push_back(FIN);
3918 
3919       // Store whatever pieces of the object are in registers to memory.
3920       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3921         if (GPR_idx == Num_GPR_Regs)
3922           break;
3923 
3924         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3925         FuncInfo->addLiveInAttr(VReg, Flags);
3926         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3927         SDValue Addr = FIN;
3928         if (j) {
3929           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3930           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3931         }
3932         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3933                                      MachinePointerInfo(&*FuncArg, j));
3934         MemOps.push_back(Store);
3935         ++GPR_idx;
3936       }
3937       ArgOffset += ArgSize;
3938       continue;
3939     }
3940 
3941     switch (ObjectVT.getSimpleVT().SimpleTy) {
3942     default: llvm_unreachable("Unhandled argument type!");
3943     case MVT::i1:
3944     case MVT::i32:
3945     case MVT::i64:
3946       if (Flags.isNest()) {
3947         // The 'nest' parameter, if any, is passed in R11.
3948         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3949         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3950 
3951         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3952           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3953 
3954         break;
3955       }
3956 
3957       // These can be scalar arguments or elements of an integer array type
3958       // passed directly.  Clang may use those instead of "byval" aggregate
3959       // types to avoid forcing arguments to memory unnecessarily.
3960       if (GPR_idx != Num_GPR_Regs) {
3961         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3962         FuncInfo->addLiveInAttr(VReg, Flags);
3963         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3964 
3965         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3966           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3967           // value to MVT::i64 and then truncate to the correct register size.
3968           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3969       } else {
3970         if (CallConv == CallingConv::Fast)
3971           ComputeArgOffset();
3972 
3973         needsLoad = true;
3974         ArgSize = PtrByteSize;
3975       }
3976       if (CallConv != CallingConv::Fast || needsLoad)
3977         ArgOffset += 8;
3978       break;
3979 
3980     case MVT::f32:
3981     case MVT::f64:
3982       // These can be scalar arguments or elements of a float array type
3983       // passed directly.  The latter are used to implement ELFv2 homogenous
3984       // float aggregates.
3985       if (FPR_idx != Num_FPR_Regs) {
3986         unsigned VReg;
3987 
3988         if (ObjectVT == MVT::f32)
3989           VReg = MF.addLiveIn(FPR[FPR_idx],
3990                               Subtarget.hasP8Vector()
3991                                   ? &PPC::VSSRCRegClass
3992                                   : &PPC::F4RCRegClass);
3993         else
3994           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3995                                                 ? &PPC::VSFRCRegClass
3996                                                 : &PPC::F8RCRegClass);
3997 
3998         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3999         ++FPR_idx;
4000       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4001         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4002         // once we support fp <-> gpr moves.
4003 
4004         // This can only ever happen in the presence of f32 array types,
4005         // since otherwise we never run out of FPRs before running out
4006         // of GPRs.
4007         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4008         FuncInfo->addLiveInAttr(VReg, Flags);
4009         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4010 
4011         if (ObjectVT == MVT::f32) {
4012           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4013             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4014                                  DAG.getConstant(32, dl, MVT::i32));
4015           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4016         }
4017 
4018         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4019       } else {
4020         if (CallConv == CallingConv::Fast)
4021           ComputeArgOffset();
4022 
4023         needsLoad = true;
4024       }
4025 
4026       // When passing an array of floats, the array occupies consecutive
4027       // space in the argument area; only round up to the next doubleword
4028       // at the end of the array.  Otherwise, each float takes 8 bytes.
4029       if (CallConv != CallingConv::Fast || needsLoad) {
4030         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4031         ArgOffset += ArgSize;
4032         if (Flags.isInConsecutiveRegsLast())
4033           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4034       }
4035       break;
4036     case MVT::v4f32:
4037     case MVT::v4i32:
4038     case MVT::v8i16:
4039     case MVT::v16i8:
4040     case MVT::v2f64:
4041     case MVT::v2i64:
4042     case MVT::v1i128:
4043     case MVT::f128:
4044       if (!Subtarget.hasQPX()) {
4045         // These can be scalar arguments or elements of a vector array type
4046         // passed directly.  The latter are used to implement ELFv2 homogenous
4047         // vector aggregates.
4048         if (VR_idx != Num_VR_Regs) {
4049           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4050           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4051           ++VR_idx;
4052         } else {
4053           if (CallConv == CallingConv::Fast)
4054             ComputeArgOffset();
4055           needsLoad = true;
4056         }
4057         if (CallConv != CallingConv::Fast || needsLoad)
4058           ArgOffset += 16;
4059         break;
4060       } // not QPX
4061 
4062       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4063              "Invalid QPX parameter type");
4064       LLVM_FALLTHROUGH;
4065 
4066     case MVT::v4f64:
4067     case MVT::v4i1:
4068       // QPX vectors are treated like their scalar floating-point subregisters
4069       // (except that they're larger).
4070       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4071       if (QFPR_idx != Num_QFPR_Regs) {
4072         const TargetRegisterClass *RC;
4073         switch (ObjectVT.getSimpleVT().SimpleTy) {
4074         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4075         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4076         default:         RC = &PPC::QBRCRegClass; break;
4077         }
4078 
4079         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4080         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4081         ++QFPR_idx;
4082       } else {
4083         if (CallConv == CallingConv::Fast)
4084           ComputeArgOffset();
4085         needsLoad = true;
4086       }
4087       if (CallConv != CallingConv::Fast || needsLoad)
4088         ArgOffset += Sz;
4089       break;
4090     }
4091 
4092     // We need to load the argument to a virtual register if we determined
4093     // above that we ran out of physical registers of the appropriate type.
4094     if (needsLoad) {
4095       if (ObjSize < ArgSize && !isLittleEndian)
4096         CurArgOffset += ArgSize - ObjSize;
4097       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4098       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4099       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4100     }
4101 
4102     InVals.push_back(ArgVal);
4103   }
4104 
4105   // Area that is at least reserved in the caller of this function.
4106   unsigned MinReservedArea;
4107   if (HasParameterArea)
4108     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4109   else
4110     MinReservedArea = LinkageSize;
4111 
4112   // Set the size that is at least reserved in caller of this function.  Tail
4113   // call optimized functions' reserved stack space needs to be aligned so that
4114   // taking the difference between two stack areas will result in an aligned
4115   // stack.
4116   MinReservedArea =
4117       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4118   FuncInfo->setMinReservedArea(MinReservedArea);
4119 
4120   // If the function takes variable number of arguments, make a frame index for
4121   // the start of the first vararg value... for expansion of llvm.va_start.
4122   if (isVarArg) {
4123     int Depth = ArgOffset;
4124 
4125     FuncInfo->setVarArgsFrameIndex(
4126       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4127     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4128 
4129     // If this function is vararg, store any remaining integer argument regs
4130     // to their spots on the stack so that they may be loaded by dereferencing
4131     // the result of va_next.
4132     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4133          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4134       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4135       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4136       SDValue Store =
4137           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4138       MemOps.push_back(Store);
4139       // Increment the address by four for the next argument to store
4140       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4141       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4142     }
4143   }
4144 
4145   if (!MemOps.empty())
4146     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4147 
4148   return Chain;
4149 }
4150 
4151 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4152     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4153     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4154     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4155   // TODO: add description of PPC stack frame format, or at least some docs.
4156   //
4157   MachineFunction &MF = DAG.getMachineFunction();
4158   MachineFrameInfo &MFI = MF.getFrameInfo();
4159   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4160 
4161   EVT PtrVT = getPointerTy(MF.getDataLayout());
4162   bool isPPC64 = PtrVT == MVT::i64;
4163   // Potential tail calls could cause overwriting of argument stack slots.
4164   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4165                        (CallConv == CallingConv::Fast));
4166   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4167   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4168   unsigned ArgOffset = LinkageSize;
4169   // Area that is at least reserved in caller of this function.
4170   unsigned MinReservedArea = ArgOffset;
4171 
4172   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4173     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4174     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4175   };
4176   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4177     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4178     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4179   };
4180   static const MCPhysReg VR[] = {
4181     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4182     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4183   };
4184 
4185   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4186   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4187   const unsigned Num_VR_Regs  = array_lengthof( VR);
4188 
4189   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4190 
4191   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4192 
4193   // In 32-bit non-varargs functions, the stack space for vectors is after the
4194   // stack space for non-vectors.  We do not use this space unless we have
4195   // too many vectors to fit in registers, something that only occurs in
4196   // constructed examples:), but we have to walk the arglist to figure
4197   // that out...for the pathological case, compute VecArgOffset as the
4198   // start of the vector parameter area.  Computing VecArgOffset is the
4199   // entire point of the following loop.
4200   unsigned VecArgOffset = ArgOffset;
4201   if (!isVarArg && !isPPC64) {
4202     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4203          ++ArgNo) {
4204       EVT ObjectVT = Ins[ArgNo].VT;
4205       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4206 
4207       if (Flags.isByVal()) {
4208         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4209         unsigned ObjSize = Flags.getByValSize();
4210         unsigned ArgSize =
4211                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4212         VecArgOffset += ArgSize;
4213         continue;
4214       }
4215 
4216       switch(ObjectVT.getSimpleVT().SimpleTy) {
4217       default: llvm_unreachable("Unhandled argument type!");
4218       case MVT::i1:
4219       case MVT::i32:
4220       case MVT::f32:
4221         VecArgOffset += 4;
4222         break;
4223       case MVT::i64:  // PPC64
4224       case MVT::f64:
4225         // FIXME: We are guaranteed to be !isPPC64 at this point.
4226         // Does MVT::i64 apply?
4227         VecArgOffset += 8;
4228         break;
4229       case MVT::v4f32:
4230       case MVT::v4i32:
4231       case MVT::v8i16:
4232       case MVT::v16i8:
4233         // Nothing to do, we're only looking at Nonvector args here.
4234         break;
4235       }
4236     }
4237   }
4238   // We've found where the vector parameter area in memory is.  Skip the
4239   // first 12 parameters; these don't use that memory.
4240   VecArgOffset = ((VecArgOffset+15)/16)*16;
4241   VecArgOffset += 12*16;
4242 
4243   // Add DAG nodes to load the arguments or copy them out of registers.  On
4244   // entry to a function on PPC, the arguments start after the linkage area,
4245   // although the first ones are often in registers.
4246 
4247   SmallVector<SDValue, 8> MemOps;
4248   unsigned nAltivecParamsAtEnd = 0;
4249   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4250   unsigned CurArgIdx = 0;
4251   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4252     SDValue ArgVal;
4253     bool needsLoad = false;
4254     EVT ObjectVT = Ins[ArgNo].VT;
4255     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4256     unsigned ArgSize = ObjSize;
4257     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4258     if (Ins[ArgNo].isOrigArg()) {
4259       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4260       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4261     }
4262     unsigned CurArgOffset = ArgOffset;
4263 
4264     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4265     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4266         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4267       if (isVarArg || isPPC64) {
4268         MinReservedArea = ((MinReservedArea+15)/16)*16;
4269         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4270                                                   Flags,
4271                                                   PtrByteSize);
4272       } else  nAltivecParamsAtEnd++;
4273     } else
4274       // Calculate min reserved area.
4275       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4276                                                 Flags,
4277                                                 PtrByteSize);
4278 
4279     // FIXME the codegen can be much improved in some cases.
4280     // We do not have to keep everything in memory.
4281     if (Flags.isByVal()) {
4282       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4283 
4284       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4285       ObjSize = Flags.getByValSize();
4286       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4287       // Objects of size 1 and 2 are right justified, everything else is
4288       // left justified.  This means the memory address is adjusted forwards.
4289       if (ObjSize==1 || ObjSize==2) {
4290         CurArgOffset = CurArgOffset + (4 - ObjSize);
4291       }
4292       // The value of the object is its address.
4293       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4294       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4295       InVals.push_back(FIN);
4296       if (ObjSize==1 || ObjSize==2) {
4297         if (GPR_idx != Num_GPR_Regs) {
4298           unsigned VReg;
4299           if (isPPC64)
4300             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4301           else
4302             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4303           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4304           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4305           SDValue Store =
4306               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4307                                 MachinePointerInfo(&*FuncArg), ObjType);
4308           MemOps.push_back(Store);
4309           ++GPR_idx;
4310         }
4311 
4312         ArgOffset += PtrByteSize;
4313 
4314         continue;
4315       }
4316       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4317         // Store whatever pieces of the object are in registers
4318         // to memory.  ArgOffset will be the address of the beginning
4319         // of the object.
4320         if (GPR_idx != Num_GPR_Regs) {
4321           unsigned VReg;
4322           if (isPPC64)
4323             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4324           else
4325             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4326           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4327           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4328           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4329           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4330                                        MachinePointerInfo(&*FuncArg, j));
4331           MemOps.push_back(Store);
4332           ++GPR_idx;
4333           ArgOffset += PtrByteSize;
4334         } else {
4335           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4336           break;
4337         }
4338       }
4339       continue;
4340     }
4341 
4342     switch (ObjectVT.getSimpleVT().SimpleTy) {
4343     default: llvm_unreachable("Unhandled argument type!");
4344     case MVT::i1:
4345     case MVT::i32:
4346       if (!isPPC64) {
4347         if (GPR_idx != Num_GPR_Regs) {
4348           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4349           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4350 
4351           if (ObjectVT == MVT::i1)
4352             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4353 
4354           ++GPR_idx;
4355         } else {
4356           needsLoad = true;
4357           ArgSize = PtrByteSize;
4358         }
4359         // All int arguments reserve stack space in the Darwin ABI.
4360         ArgOffset += PtrByteSize;
4361         break;
4362       }
4363       LLVM_FALLTHROUGH;
4364     case MVT::i64:  // PPC64
4365       if (GPR_idx != Num_GPR_Regs) {
4366         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4367         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4368 
4369         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4370           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4371           // value to MVT::i64 and then truncate to the correct register size.
4372           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4373 
4374         ++GPR_idx;
4375       } else {
4376         needsLoad = true;
4377         ArgSize = PtrByteSize;
4378       }
4379       // All int arguments reserve stack space in the Darwin ABI.
4380       ArgOffset += 8;
4381       break;
4382 
4383     case MVT::f32:
4384     case MVT::f64:
4385       // Every 4 bytes of argument space consumes one of the GPRs available for
4386       // argument passing.
4387       if (GPR_idx != Num_GPR_Regs) {
4388         ++GPR_idx;
4389         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4390           ++GPR_idx;
4391       }
4392       if (FPR_idx != Num_FPR_Regs) {
4393         unsigned VReg;
4394 
4395         if (ObjectVT == MVT::f32)
4396           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4397         else
4398           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4399 
4400         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4401         ++FPR_idx;
4402       } else {
4403         needsLoad = true;
4404       }
4405 
4406       // All FP arguments reserve stack space in the Darwin ABI.
4407       ArgOffset += isPPC64 ? 8 : ObjSize;
4408       break;
4409     case MVT::v4f32:
4410     case MVT::v4i32:
4411     case MVT::v8i16:
4412     case MVT::v16i8:
4413       // Note that vector arguments in registers don't reserve stack space,
4414       // except in varargs functions.
4415       if (VR_idx != Num_VR_Regs) {
4416         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4417         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4418         if (isVarArg) {
4419           while ((ArgOffset % 16) != 0) {
4420             ArgOffset += PtrByteSize;
4421             if (GPR_idx != Num_GPR_Regs)
4422               GPR_idx++;
4423           }
4424           ArgOffset += 16;
4425           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4426         }
4427         ++VR_idx;
4428       } else {
4429         if (!isVarArg && !isPPC64) {
4430           // Vectors go after all the nonvectors.
4431           CurArgOffset = VecArgOffset;
4432           VecArgOffset += 16;
4433         } else {
4434           // Vectors are aligned.
4435           ArgOffset = ((ArgOffset+15)/16)*16;
4436           CurArgOffset = ArgOffset;
4437           ArgOffset += 16;
4438         }
4439         needsLoad = true;
4440       }
4441       break;
4442     }
4443 
4444     // We need to load the argument to a virtual register if we determined above
4445     // that we ran out of physical registers of the appropriate type.
4446     if (needsLoad) {
4447       int FI = MFI.CreateFixedObject(ObjSize,
4448                                      CurArgOffset + (ArgSize - ObjSize),
4449                                      isImmutable);
4450       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4451       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4452     }
4453 
4454     InVals.push_back(ArgVal);
4455   }
4456 
4457   // Allow for Altivec parameters at the end, if needed.
4458   if (nAltivecParamsAtEnd) {
4459     MinReservedArea = ((MinReservedArea+15)/16)*16;
4460     MinReservedArea += 16*nAltivecParamsAtEnd;
4461   }
4462 
4463   // Area that is at least reserved in the caller of this function.
4464   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4465 
4466   // Set the size that is at least reserved in caller of this function.  Tail
4467   // call optimized functions' reserved stack space needs to be aligned so that
4468   // taking the difference between two stack areas will result in an aligned
4469   // stack.
4470   MinReservedArea =
4471       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4472   FuncInfo->setMinReservedArea(MinReservedArea);
4473 
4474   // If the function takes variable number of arguments, make a frame index for
4475   // the start of the first vararg value... for expansion of llvm.va_start.
4476   if (isVarArg) {
4477     int Depth = ArgOffset;
4478 
4479     FuncInfo->setVarArgsFrameIndex(
4480       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4481                             Depth, true));
4482     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4483 
4484     // If this function is vararg, store any remaining integer argument regs
4485     // to their spots on the stack so that they may be loaded by dereferencing
4486     // the result of va_next.
4487     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4488       unsigned VReg;
4489 
4490       if (isPPC64)
4491         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4492       else
4493         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4494 
4495       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4496       SDValue Store =
4497           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4498       MemOps.push_back(Store);
4499       // Increment the address by four for the next argument to store
4500       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4501       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4502     }
4503   }
4504 
4505   if (!MemOps.empty())
4506     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4507 
4508   return Chain;
4509 }
4510 
4511 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4512 /// adjusted to accommodate the arguments for the tailcall.
4513 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4514                                    unsigned ParamSize) {
4515 
4516   if (!isTailCall) return 0;
4517 
4518   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4519   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4520   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4521   // Remember only if the new adjustment is bigger.
4522   if (SPDiff < FI->getTailCallSPDelta())
4523     FI->setTailCallSPDelta(SPDiff);
4524 
4525   return SPDiff;
4526 }
4527 
4528 static bool isFunctionGlobalAddress(SDValue Callee);
4529 
4530 static bool
4531 callsShareTOCBase(const Function *Caller, SDValue Callee,
4532                     const TargetMachine &TM) {
4533    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4534    // don't have enough information to determine if the caller and calle share
4535    // the same  TOC base, so we have to pessimistically assume they don't for
4536    // correctness.
4537    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4538    if (!G)
4539      return false;
4540 
4541    const GlobalValue *GV = G->getGlobal();
4542   // The medium and large code models are expected to provide a sufficiently
4543   // large TOC to provide all data addressing needs of a module with a
4544   // single TOC. Since each module will be addressed with a single TOC then we
4545   // only need to check that caller and callee don't cross dso boundaries.
4546   if (CodeModel::Medium == TM.getCodeModel() ||
4547       CodeModel::Large == TM.getCodeModel())
4548     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4549 
4550   // Otherwise we need to ensure callee and caller are in the same section,
4551   // since the linker may allocate multiple TOCs, and we don't know which
4552   // sections will belong to the same TOC base.
4553 
4554   if (!GV->isStrongDefinitionForLinker())
4555     return false;
4556 
4557   // Any explicitly-specified sections and section prefixes must also match.
4558   // Also, if we're using -ffunction-sections, then each function is always in
4559   // a different section (the same is true for COMDAT functions).
4560   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4561       GV->getSection() != Caller->getSection())
4562     return false;
4563   if (const auto *F = dyn_cast<Function>(GV)) {
4564     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4565       return false;
4566   }
4567 
4568   // If the callee might be interposed, then we can't assume the ultimate call
4569   // target will be in the same section. Even in cases where we can assume that
4570   // interposition won't happen, in any case where the linker might insert a
4571   // stub to allow for interposition, we must generate code as though
4572   // interposition might occur. To understand why this matters, consider a
4573   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4574   // in the same section, but a is in a different module (i.e. has a different
4575   // TOC base pointer). If the linker allows for interposition between b and c,
4576   // then it will generate a stub for the call edge between b and c which will
4577   // save the TOC pointer into the designated stack slot allocated by b. If we
4578   // return true here, and therefore allow a tail call between b and c, that
4579   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4580   // pointer into the stack slot allocated by a (where the a -> b stub saved
4581   // a's TOC base pointer). If we're not considering a tail call, but rather,
4582   // whether a nop is needed after the call instruction in b, because the linker
4583   // will insert a stub, it might complain about a missing nop if we omit it
4584   // (although many don't complain in this case).
4585   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4586     return false;
4587 
4588   return true;
4589 }
4590 
4591 static bool
4592 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4593                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4594   assert(Subtarget.is64BitELFABI());
4595 
4596   const unsigned PtrByteSize = 8;
4597   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4598 
4599   static const MCPhysReg GPR[] = {
4600     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4601     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4602   };
4603   static const MCPhysReg VR[] = {
4604     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4605     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4606   };
4607 
4608   const unsigned NumGPRs = array_lengthof(GPR);
4609   const unsigned NumFPRs = 13;
4610   const unsigned NumVRs = array_lengthof(VR);
4611   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4612 
4613   unsigned NumBytes = LinkageSize;
4614   unsigned AvailableFPRs = NumFPRs;
4615   unsigned AvailableVRs = NumVRs;
4616 
4617   for (const ISD::OutputArg& Param : Outs) {
4618     if (Param.Flags.isNest()) continue;
4619 
4620     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4621                                PtrByteSize, LinkageSize, ParamAreaSize,
4622                                NumBytes, AvailableFPRs, AvailableVRs,
4623                                Subtarget.hasQPX()))
4624       return true;
4625   }
4626   return false;
4627 }
4628 
4629 static bool
4630 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4631   if (CS.arg_size() != CallerFn->arg_size())
4632     return false;
4633 
4634   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4635   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4636   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4637 
4638   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4639     const Value* CalleeArg = *CalleeArgIter;
4640     const Value* CallerArg = &(*CallerArgIter);
4641     if (CalleeArg == CallerArg)
4642       continue;
4643 
4644     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4645     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4646     //      }
4647     // 1st argument of callee is undef and has the same type as caller.
4648     if (CalleeArg->getType() == CallerArg->getType() &&
4649         isa<UndefValue>(CalleeArg))
4650       continue;
4651 
4652     return false;
4653   }
4654 
4655   return true;
4656 }
4657 
4658 // Returns true if TCO is possible between the callers and callees
4659 // calling conventions.
4660 static bool
4661 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4662                                     CallingConv::ID CalleeCC) {
4663   // Tail calls are possible with fastcc and ccc.
4664   auto isTailCallableCC  = [] (CallingConv::ID CC){
4665       return  CC == CallingConv::C || CC == CallingConv::Fast;
4666   };
4667   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4668     return false;
4669 
4670   // We can safely tail call both fastcc and ccc callees from a c calling
4671   // convention caller. If the caller is fastcc, we may have less stack space
4672   // than a non-fastcc caller with the same signature so disable tail-calls in
4673   // that case.
4674   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4675 }
4676 
4677 bool
4678 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4679                                     SDValue Callee,
4680                                     CallingConv::ID CalleeCC,
4681                                     ImmutableCallSite CS,
4682                                     bool isVarArg,
4683                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4684                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4685                                     SelectionDAG& DAG) const {
4686   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4687 
4688   if (DisableSCO && !TailCallOpt) return false;
4689 
4690   // Variadic argument functions are not supported.
4691   if (isVarArg) return false;
4692 
4693   auto &Caller = DAG.getMachineFunction().getFunction();
4694   // Check that the calling conventions are compatible for tco.
4695   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4696     return false;
4697 
4698   // Caller contains any byval parameter is not supported.
4699   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4700     return false;
4701 
4702   // Callee contains any byval parameter is not supported, too.
4703   // Note: This is a quick work around, because in some cases, e.g.
4704   // caller's stack size > callee's stack size, we are still able to apply
4705   // sibling call optimization. For example, gcc is able to do SCO for caller1
4706   // in the following example, but not for caller2.
4707   //   struct test {
4708   //     long int a;
4709   //     char ary[56];
4710   //   } gTest;
4711   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4712   //     b->a = v.a;
4713   //     return 0;
4714   //   }
4715   //   void caller1(struct test a, struct test c, struct test *b) {
4716   //     callee(gTest, b); }
4717   //   void caller2(struct test *b) { callee(gTest, b); }
4718   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4719     return false;
4720 
4721   // If callee and caller use different calling conventions, we cannot pass
4722   // parameters on stack since offsets for the parameter area may be different.
4723   if (Caller.getCallingConv() != CalleeCC &&
4724       needStackSlotPassParameters(Subtarget, Outs))
4725     return false;
4726 
4727   // No TCO/SCO on indirect call because Caller have to restore its TOC
4728   if (!isFunctionGlobalAddress(Callee) &&
4729       !isa<ExternalSymbolSDNode>(Callee))
4730     return false;
4731 
4732   // If the caller and callee potentially have different TOC bases then we
4733   // cannot tail call since we need to restore the TOC pointer after the call.
4734   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4735   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4736     return false;
4737 
4738   // TCO allows altering callee ABI, so we don't have to check further.
4739   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4740     return true;
4741 
4742   if (DisableSCO) return false;
4743 
4744   // If callee use the same argument list that caller is using, then we can
4745   // apply SCO on this case. If it is not, then we need to check if callee needs
4746   // stack for passing arguments.
4747   if (!hasSameArgumentList(&Caller, CS) &&
4748       needStackSlotPassParameters(Subtarget, Outs)) {
4749     return false;
4750   }
4751 
4752   return true;
4753 }
4754 
4755 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4756 /// for tail call optimization. Targets which want to do tail call
4757 /// optimization should implement this function.
4758 bool
4759 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4760                                                      CallingConv::ID CalleeCC,
4761                                                      bool isVarArg,
4762                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4763                                                      SelectionDAG& DAG) const {
4764   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4765     return false;
4766 
4767   // Variable argument functions are not supported.
4768   if (isVarArg)
4769     return false;
4770 
4771   MachineFunction &MF = DAG.getMachineFunction();
4772   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4773   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4774     // Functions containing by val parameters are not supported.
4775     for (unsigned i = 0; i != Ins.size(); i++) {
4776        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4777        if (Flags.isByVal()) return false;
4778     }
4779 
4780     // Non-PIC/GOT tail calls are supported.
4781     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4782       return true;
4783 
4784     // At the moment we can only do local tail calls (in same module, hidden
4785     // or protected) if we are generating PIC.
4786     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4787       return G->getGlobal()->hasHiddenVisibility()
4788           || G->getGlobal()->hasProtectedVisibility();
4789   }
4790 
4791   return false;
4792 }
4793 
4794 /// isCallCompatibleAddress - Return the immediate to use if the specified
4795 /// 32-bit value is representable in the immediate field of a BxA instruction.
4796 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4797   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4798   if (!C) return nullptr;
4799 
4800   int Addr = C->getZExtValue();
4801   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4802       SignExtend32<26>(Addr) != Addr)
4803     return nullptr;  // Top 6 bits have to be sext of immediate.
4804 
4805   return DAG
4806       .getConstant(
4807           (int)C->getZExtValue() >> 2, SDLoc(Op),
4808           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4809       .getNode();
4810 }
4811 
4812 namespace {
4813 
4814 struct TailCallArgumentInfo {
4815   SDValue Arg;
4816   SDValue FrameIdxOp;
4817   int FrameIdx = 0;
4818 
4819   TailCallArgumentInfo() = default;
4820 };
4821 
4822 } // end anonymous namespace
4823 
4824 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4825 static void StoreTailCallArgumentsToStackSlot(
4826     SelectionDAG &DAG, SDValue Chain,
4827     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4828     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4829   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4830     SDValue Arg = TailCallArgs[i].Arg;
4831     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4832     int FI = TailCallArgs[i].FrameIdx;
4833     // Store relative to framepointer.
4834     MemOpChains.push_back(DAG.getStore(
4835         Chain, dl, Arg, FIN,
4836         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4837   }
4838 }
4839 
4840 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4841 /// the appropriate stack slot for the tail call optimized function call.
4842 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4843                                              SDValue OldRetAddr, SDValue OldFP,
4844                                              int SPDiff, const SDLoc &dl) {
4845   if (SPDiff) {
4846     // Calculate the new stack slot for the return address.
4847     MachineFunction &MF = DAG.getMachineFunction();
4848     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4849     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4850     bool isPPC64 = Subtarget.isPPC64();
4851     int SlotSize = isPPC64 ? 8 : 4;
4852     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4853     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4854                                                          NewRetAddrLoc, true);
4855     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4856     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4857     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4858                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4859 
4860     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4861     // slot as the FP is never overwritten.
4862     if (Subtarget.isDarwinABI()) {
4863       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4864       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4865                                                          true);
4866       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4867       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4868                            MachinePointerInfo::getFixedStack(
4869                                DAG.getMachineFunction(), NewFPIdx));
4870     }
4871   }
4872   return Chain;
4873 }
4874 
4875 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4876 /// the position of the argument.
4877 static void
4878 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4879                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4880                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4881   int Offset = ArgOffset + SPDiff;
4882   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4883   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4884   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4885   SDValue FIN = DAG.getFrameIndex(FI, VT);
4886   TailCallArgumentInfo Info;
4887   Info.Arg = Arg;
4888   Info.FrameIdxOp = FIN;
4889   Info.FrameIdx = FI;
4890   TailCallArguments.push_back(Info);
4891 }
4892 
4893 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4894 /// stack slot. Returns the chain as result and the loaded frame pointers in
4895 /// LROpOut/FPOpout. Used when tail calling.
4896 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4897     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4898     SDValue &FPOpOut, const SDLoc &dl) const {
4899   if (SPDiff) {
4900     // Load the LR and FP stack slot for later adjusting.
4901     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4902     LROpOut = getReturnAddrFrameIndex(DAG);
4903     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4904     Chain = SDValue(LROpOut.getNode(), 1);
4905 
4906     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4907     // slot as the FP is never overwritten.
4908     if (Subtarget.isDarwinABI()) {
4909       FPOpOut = getFramePointerFrameIndex(DAG);
4910       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4911       Chain = SDValue(FPOpOut.getNode(), 1);
4912     }
4913   }
4914   return Chain;
4915 }
4916 
4917 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4918 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4919 /// specified by the specific parameter attribute. The copy will be passed as
4920 /// a byval function parameter.
4921 /// Sometimes what we are copying is the end of a larger object, the part that
4922 /// does not fit in registers.
4923 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4924                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4925                                          SelectionDAG &DAG, const SDLoc &dl) {
4926   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4927   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4928                        false, false, false, MachinePointerInfo(),
4929                        MachinePointerInfo());
4930 }
4931 
4932 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4933 /// tail calls.
4934 static void LowerMemOpCallTo(
4935     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4936     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4937     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4938     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4939   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4940   if (!isTailCall) {
4941     if (isVector) {
4942       SDValue StackPtr;
4943       if (isPPC64)
4944         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4945       else
4946         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4947       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4948                            DAG.getConstant(ArgOffset, dl, PtrVT));
4949     }
4950     MemOpChains.push_back(
4951         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4952     // Calculate and remember argument location.
4953   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4954                                   TailCallArguments);
4955 }
4956 
4957 static void
4958 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4959                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4960                 SDValue FPOp,
4961                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4962   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4963   // might overwrite each other in case of tail call optimization.
4964   SmallVector<SDValue, 8> MemOpChains2;
4965   // Do not flag preceding copytoreg stuff together with the following stuff.
4966   InFlag = SDValue();
4967   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4968                                     MemOpChains2, dl);
4969   if (!MemOpChains2.empty())
4970     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4971 
4972   // Store the return address to the appropriate stack slot.
4973   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4974 
4975   // Emit callseq_end just before tailcall node.
4976   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4977                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4978   InFlag = Chain.getValue(1);
4979 }
4980 
4981 // Is this global address that of a function that can be called by name? (as
4982 // opposed to something that must hold a descriptor for an indirect call).
4983 static bool isFunctionGlobalAddress(SDValue Callee) {
4984   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4985     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4986         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4987       return false;
4988 
4989     return G->getGlobal()->getValueType()->isFunctionTy();
4990   }
4991 
4992   return false;
4993 }
4994 
4995 SDValue PPCTargetLowering::LowerCallResult(
4996     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4997     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4998     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4999   SmallVector<CCValAssign, 16> RVLocs;
5000   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5001                     *DAG.getContext());
5002 
5003   CCRetInfo.AnalyzeCallResult(
5004       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5005                ? RetCC_PPC_Cold
5006                : RetCC_PPC);
5007 
5008   // Copy all of the result registers out of their specified physreg.
5009   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5010     CCValAssign &VA = RVLocs[i];
5011     assert(VA.isRegLoc() && "Can only return in registers!");
5012 
5013     SDValue Val;
5014 
5015     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5016       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5017                                       InFlag);
5018       Chain = Lo.getValue(1);
5019       InFlag = Lo.getValue(2);
5020       VA = RVLocs[++i]; // skip ahead to next loc
5021       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5022                                       InFlag);
5023       Chain = Hi.getValue(1);
5024       InFlag = Hi.getValue(2);
5025       if (!Subtarget.isLittleEndian())
5026         std::swap (Lo, Hi);
5027       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5028     } else {
5029       Val = DAG.getCopyFromReg(Chain, dl,
5030                                VA.getLocReg(), VA.getLocVT(), InFlag);
5031       Chain = Val.getValue(1);
5032       InFlag = Val.getValue(2);
5033     }
5034 
5035     switch (VA.getLocInfo()) {
5036     default: llvm_unreachable("Unknown loc info!");
5037     case CCValAssign::Full: break;
5038     case CCValAssign::AExt:
5039       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5040       break;
5041     case CCValAssign::ZExt:
5042       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5043                         DAG.getValueType(VA.getValVT()));
5044       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5045       break;
5046     case CCValAssign::SExt:
5047       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5048                         DAG.getValueType(VA.getValVT()));
5049       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5050       break;
5051     }
5052 
5053     InVals.push_back(Val);
5054   }
5055 
5056   return Chain;
5057 }
5058 
5059 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5060                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5061   // PatchPoint calls are not indirect.
5062   if (isPatchPoint)
5063     return false;
5064 
5065   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5066     return false;
5067 
5068   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5069   // becuase the immediate function pointer points to a descriptor instead of
5070   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5071   // pointer immediate points to the global entry point, while the BLA would
5072   // need to jump to the local entry point (see rL211174).
5073   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5074       isBLACompatibleAddress(Callee, DAG))
5075     return false;
5076 
5077   return true;
5078 }
5079 
5080 static unsigned getCallOpcode(bool isIndirectCall, bool isPatchPoint,
5081                               bool isTailCall, const Function &Caller,
5082                               const SDValue &Callee,
5083                               const PPCSubtarget &Subtarget,
5084                               const TargetMachine &TM) {
5085   if (isTailCall)
5086     return PPCISD::TC_RETURN;
5087 
5088   // This is a call through a function pointer.
5089   if (isIndirectCall) {
5090     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5091     // indirect calls. The save of the caller's TOC pointer to the stack will be
5092     // inserted into the DAG as part of call lowering. The restore of the TOC
5093     // pointer is modeled by using a pseudo instruction for the call opcode that
5094     // represents the 2 instruction sequence of an indirect branch and link,
5095     // immediately followed by a load of the TOC pointer from the the stack save
5096     // slot into gpr2.
5097     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5098       return PPCISD::BCTRL_LOAD_TOC;
5099 
5100     // An indirect call that does not need a TOC restore.
5101     return PPCISD::BCTRL;
5102   }
5103 
5104   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5105   // immediately following the call instruction if the caller and callee may
5106   // have different TOC bases. At link time if the linker determines the calls
5107   // may not share a TOC base, the call is redirected to a trampoline inserted
5108   // by the linker. The trampoline will (among other things) save the callers
5109   // TOC pointer at an ABI designated offset in the linkage area and the linker
5110   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5111   // into gpr2.
5112   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5113     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5114                                                   : PPCISD::CALL_NOP;
5115 
5116   return PPCISD::CALL;
5117 }
5118 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5119                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5120   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5121     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5122       return SDValue(Dest, 0);
5123 
5124   // Returns true if the callee is local, and false otherwise.
5125   auto isLocalCallee = [&]() {
5126     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5127     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5128     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5129 
5130     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5131            !dyn_cast_or_null<GlobalIFunc>(GV);
5132   };
5133 
5134   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5135   // a static relocation model causes some versions of GNU LD (2.17.50, at
5136   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5137   // built with secure-PLT.
5138   bool UsePlt =
5139       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5140       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5141 
5142   if (isFunctionGlobalAddress(Callee)) {
5143     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5144     if (!Subtarget.isAIXABI())
5145       return DAG.getTargetGlobalAddress(G->getGlobal(), dl,
5146                                         Callee.getValueType(), 0,
5147                                         UsePlt ? PPCII::MO_PLT : 0);
5148 
5149     // On AIX, direct function calls reference the symbol for the function's
5150     // entry point, which is named by prepending a "." before the function's
5151     // C-linkage name.
5152     auto &Context = DAG.getMachineFunction().getMMI().getContext();
5153 
5154     const GlobalObject *GO = cast<GlobalObject>(G->getGlobal());
5155     MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5156         Context.getOrCreateSymbol(Twine(".") + Twine(GO->getName())));
5157 
5158     if (GO && GO->isDeclaration() && !S->hasContainingCsect()) {
5159       // On AIX, an undefined symbol needs to be associated with a
5160       // MCSectionXCOFF to get the correct storage mapping class.
5161       // In this case, XCOFF::XMC_PR.
5162       const XCOFF::StorageClass SC =
5163           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5164       MCSectionXCOFF *Sec =
5165           Context.getXCOFFSection(S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5166                                   SC, SectionKind::getMetadata());
5167       S->setContainingCsect(Sec);
5168     }
5169 
5170     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5171     return DAG.getMCSymbol(S, PtrVT);
5172   }
5173 
5174   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
5175     return DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
5176                                        UsePlt ? PPCII::MO_PLT : 0);
5177 
5178   // No transformation needed.
5179   assert(Callee.getNode() && "What no callee?");
5180   return Callee;
5181 }
5182 
5183 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5184   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5185          "Expected a CALLSEQ_STARTSDNode.");
5186 
5187   // The last operand is the chain, except when the node has glue. If the node
5188   // has glue, then the last operand is the glue, and the chain is the second
5189   // last operand.
5190   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5191   if (LastValue.getValueType() != MVT::Glue)
5192     return LastValue;
5193 
5194   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5195 }
5196 
5197 // Creates the node that moves a functions address into the count register
5198 // to prepare for an indirect call instruction.
5199 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5200                                 SDValue &Glue, SDValue &Chain,
5201                                 const SDLoc &dl) {
5202   SDValue MTCTROps[] = {Chain, Callee, Glue};
5203   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5204   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5205                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5206   // The glue is the second value produced.
5207   Glue = Chain.getValue(1);
5208 }
5209 
5210 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5211                                           SDValue &Glue, SDValue &Chain,
5212                                           SDValue CallSeqStart,
5213                                           ImmutableCallSite CS, const SDLoc &dl,
5214                                           bool hasNest,
5215                                           const PPCSubtarget &Subtarget) {
5216   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5217   // entry point, but to the function descriptor (the function entry point
5218   // address is part of the function descriptor though).
5219   // The function descriptor is a three doubleword structure with the
5220   // following fields: function entry point, TOC base address and
5221   // environment pointer.
5222   // Thus for a call through a function pointer, the following actions need
5223   // to be performed:
5224   //   1. Save the TOC of the caller in the TOC save area of its stack
5225   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5226   //   2. Load the address of the function entry point from the function
5227   //      descriptor.
5228   //   3. Load the TOC of the callee from the function descriptor into r2.
5229   //   4. Load the environment pointer from the function descriptor into
5230   //      r11.
5231   //   5. Branch to the function entry point address.
5232   //   6. On return of the callee, the TOC of the caller needs to be
5233   //      restored (this is done in FinishCall()).
5234   //
5235   // The loads are scheduled at the beginning of the call sequence, and the
5236   // register copies are flagged together to ensure that no other
5237   // operations can be scheduled in between. E.g. without flagging the
5238   // copies together, a TOC access in the caller could be scheduled between
5239   // the assignment of the callee TOC and the branch to the callee, which leads
5240   // to incorrect code.
5241 
5242   // Start by loading the function address from the descriptor.
5243   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5244   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5245                       ? (MachineMemOperand::MODereferenceable |
5246                          MachineMemOperand::MOInvariant)
5247                       : MachineMemOperand::MONone;
5248 
5249   MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5250 
5251   // Registers used in building the DAG.
5252   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5253   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5254 
5255   // Offsets of descriptor members.
5256   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5257   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5258 
5259   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5260   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5261 
5262   // One load for the functions entry point address.
5263   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5264                                     Alignment, MMOFlags);
5265 
5266   // One for loading the TOC anchor for the module that contains the called
5267   // function.
5268   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5269   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5270   SDValue TOCPtr =
5271       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5272                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5273 
5274   // One for loading the environment pointer.
5275   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5276   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5277   SDValue LoadEnvPtr =
5278       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5279                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5280 
5281 
5282   // Then copy the newly loaded TOC anchor to the TOC pointer.
5283   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5284   Chain = TOCVal.getValue(0);
5285   Glue = TOCVal.getValue(1);
5286 
5287   // If the function call has an explicit 'nest' parameter, it takes the
5288   // place of the environment pointer.
5289   assert((!hasNest || !Subtarget.isAIXABI()) &&
5290          "Nest parameter is not supported on AIX.");
5291   if (!hasNest) {
5292     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5293     Chain = EnvVal.getValue(0);
5294     Glue = EnvVal.getValue(1);
5295   }
5296 
5297   // The rest of the indirect call sequence is the same as the non-descriptor
5298   // DAG.
5299   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5300 }
5301 
5302 static void
5303 buildCallOperands(SmallVectorImpl<SDValue> &Ops, CallingConv::ID CallConv,
5304                   const SDLoc &dl, bool isTailCall, bool isVarArg,
5305                   bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5306                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5307                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5308                   const PPCSubtarget &Subtarget, bool isIndirect) {
5309   const bool IsPPC64 = Subtarget.isPPC64();
5310   // MVT for a general purpose register.
5311   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5312 
5313   // First operand is always the chain.
5314   Ops.push_back(Chain);
5315 
5316   // If it's a direct call pass the callee as the second operand.
5317   if (!isIndirect)
5318     Ops.push_back(Callee);
5319   else {
5320     assert(!isPatchPoint && "Patch point call are not indirect.");
5321 
5322     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5323     // on the stack (this would have been done in `LowerCall_64SVR4` or
5324     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5325     // represents both the indirect branch and a load that restores the TOC
5326     // pointer from the linkage area. The operand for the TOC restore is an add
5327     // of the TOC save offset to the stack pointer. This must be the second
5328     // operand: after the chain input but before any other variadic arguments.
5329     if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5330       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5331 
5332       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5333       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5334       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5335       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5336       Ops.push_back(AddTOC);
5337     }
5338 
5339     // Add the register used for the environment pointer.
5340     if (Subtarget.usesFunctionDescriptors() && !hasNest)
5341       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5342                                     RegVT));
5343 
5344 
5345     // Add CTR register as callee so a bctr can be emitted later.
5346     if (isTailCall)
5347       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5348   }
5349 
5350   // If this is a tail call add stack pointer delta.
5351   if (isTailCall)
5352     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5353 
5354   // Add argument registers to the end of the list so that they are known live
5355   // into the call.
5356   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5357     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5358                                   RegsToPass[i].second.getValueType()));
5359 
5360   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5361   // no way to mark dependencies as implicit here.
5362   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5363   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && !isPatchPoint)
5364     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5365 
5366   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5367   if (isVarArg && Subtarget.is32BitELFABI())
5368     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5369 
5370   // Add a register mask operand representing the call-preserved registers.
5371   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5372   const uint32_t *Mask =
5373       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5374   assert(Mask && "Missing call preserved mask for calling convention");
5375   Ops.push_back(DAG.getRegisterMask(Mask));
5376 
5377   // If the glue is valid, it is the last operand.
5378   if (Glue.getNode())
5379     Ops.push_back(Glue);
5380 }
5381 
5382 SDValue PPCTargetLowering::FinishCall(
5383     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5384     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5385     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5386     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5387     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5388     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5389 
5390   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI())
5391     setUsesTOCBasePtr(DAG);
5392 
5393   const bool isIndirect = isIndirectCall(Callee, DAG, Subtarget, isPatchPoint);
5394   unsigned CallOpc = getCallOpcode(isIndirect, isPatchPoint, isTailCall,
5395                                    DAG.getMachineFunction().getFunction(),
5396                                    Callee, Subtarget, DAG.getTarget());
5397 
5398   if (!isIndirect)
5399     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5400   else if (Subtarget.usesFunctionDescriptors())
5401     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS,
5402                                   dl, hasNest, Subtarget);
5403   else
5404     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5405 
5406   // Build the operand list for the call instruction.
5407   SmallVector<SDValue, 8> Ops;
5408   buildCallOperands(Ops, CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5409                     hasNest, DAG, RegsToPass, Glue, Chain, Callee, SPDiff,
5410                     Subtarget, isIndirect);
5411 
5412   // Emit tail call.
5413   if (isTailCall) {
5414     assert(((Callee.getOpcode() == ISD::Register &&
5415              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5416             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5417             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5418             isa<ConstantSDNode>(Callee)) &&
5419            "Expecting a global address, external symbol, absolute value or "
5420            "register");
5421     assert(CallOpc == PPCISD::TC_RETURN &&
5422            "Unexpected call opcode for a tail call.");
5423     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5424     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5425   }
5426 
5427   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5428   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5429   Glue = Chain.getValue(1);
5430 
5431   // When performing tail call optimization the callee pops its arguments off
5432   // the stack. Account for this here so these bytes can be pushed back on in
5433   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5434   int BytesCalleePops = (CallConv == CallingConv::Fast &&
5435                          getTargetMachine().Options.GuaranteedTailCallOpt)
5436                             ? NumBytes
5437                             : 0;
5438 
5439   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5440                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5441                              Glue, dl);
5442   Glue = Chain.getValue(1);
5443 
5444   return LowerCallResult(Chain, Glue, CallConv, isVarArg, Ins, dl, DAG, InVals);
5445 }
5446 
5447 SDValue
5448 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5449                              SmallVectorImpl<SDValue> &InVals) const {
5450   SelectionDAG &DAG                     = CLI.DAG;
5451   SDLoc &dl                             = CLI.DL;
5452   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5453   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5454   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5455   SDValue Chain                         = CLI.Chain;
5456   SDValue Callee                        = CLI.Callee;
5457   bool &isTailCall                      = CLI.IsTailCall;
5458   CallingConv::ID CallConv              = CLI.CallConv;
5459   bool isVarArg                         = CLI.IsVarArg;
5460   bool isPatchPoint                     = CLI.IsPatchPoint;
5461   ImmutableCallSite CS                  = CLI.CS;
5462 
5463   if (isTailCall) {
5464     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5465       isTailCall = false;
5466     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5467       isTailCall =
5468         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5469                                                  isVarArg, Outs, Ins, DAG);
5470     else
5471       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5472                                                      Ins, DAG);
5473     if (isTailCall) {
5474       ++NumTailCalls;
5475       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5476         ++NumSiblingCalls;
5477 
5478       assert(isa<GlobalAddressSDNode>(Callee) &&
5479              "Callee should be an llvm::Function object.");
5480       LLVM_DEBUG(
5481           const GlobalValue *GV =
5482               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5483           const unsigned Width =
5484               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5485           dbgs() << "TCO caller: "
5486                  << left_justify(DAG.getMachineFunction().getName(), Width)
5487                  << ", callee linkage: " << GV->getVisibility() << ", "
5488                  << GV->getLinkage() << "\n");
5489     }
5490   }
5491 
5492   if (!isTailCall && CS && CS.isMustTailCall())
5493     report_fatal_error("failed to perform tail call elimination on a call "
5494                        "site marked musttail");
5495 
5496   // When long calls (i.e. indirect calls) are always used, calls are always
5497   // made via function pointer. If we have a function name, first translate it
5498   // into a pointer.
5499   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5500       !isTailCall)
5501     Callee = LowerGlobalAddress(Callee, DAG);
5502 
5503   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5504     return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5505                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5506                             dl, DAG, InVals, CS);
5507 
5508   if (Subtarget.isSVR4ABI())
5509     return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5510                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5511                             dl, DAG, InVals, CS);
5512 
5513   if (Subtarget.isAIXABI())
5514     return LowerCall_AIX(Chain, Callee, CallConv, isVarArg,
5515                          isTailCall, isPatchPoint, Outs, OutVals, Ins,
5516                          dl, DAG, InVals, CS);
5517 
5518   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5519                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5520                           dl, DAG, InVals, CS);
5521 }
5522 
5523 SDValue PPCTargetLowering::LowerCall_32SVR4(
5524     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5525     bool isTailCall, bool isPatchPoint,
5526     const SmallVectorImpl<ISD::OutputArg> &Outs,
5527     const SmallVectorImpl<SDValue> &OutVals,
5528     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5529     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5530     ImmutableCallSite CS) const {
5531   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5532   // of the 32-bit SVR4 ABI stack frame layout.
5533 
5534   assert((CallConv == CallingConv::C ||
5535           CallConv == CallingConv::Cold ||
5536           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5537 
5538   unsigned PtrByteSize = 4;
5539 
5540   MachineFunction &MF = DAG.getMachineFunction();
5541 
5542   // Mark this function as potentially containing a function that contains a
5543   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5544   // and restoring the callers stack pointer in this functions epilog. This is
5545   // done because by tail calling the called function might overwrite the value
5546   // in this function's (MF) stack pointer stack slot 0(SP).
5547   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5548       CallConv == CallingConv::Fast)
5549     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5550 
5551   // Count how many bytes are to be pushed on the stack, including the linkage
5552   // area, parameter list area and the part of the local variable space which
5553   // contains copies of aggregates which are passed by value.
5554 
5555   // Assign locations to all of the outgoing arguments.
5556   SmallVector<CCValAssign, 16> ArgLocs;
5557   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5558 
5559   // Reserve space for the linkage area on the stack.
5560   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5561                        PtrByteSize);
5562   if (useSoftFloat())
5563     CCInfo.PreAnalyzeCallOperands(Outs);
5564 
5565   if (isVarArg) {
5566     // Handle fixed and variable vector arguments differently.
5567     // Fixed vector arguments go into registers as long as registers are
5568     // available. Variable vector arguments always go into memory.
5569     unsigned NumArgs = Outs.size();
5570 
5571     for (unsigned i = 0; i != NumArgs; ++i) {
5572       MVT ArgVT = Outs[i].VT;
5573       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5574       bool Result;
5575 
5576       if (Outs[i].IsFixed) {
5577         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5578                                CCInfo);
5579       } else {
5580         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5581                                       ArgFlags, CCInfo);
5582       }
5583 
5584       if (Result) {
5585 #ifndef NDEBUG
5586         errs() << "Call operand #" << i << " has unhandled type "
5587              << EVT(ArgVT).getEVTString() << "\n";
5588 #endif
5589         llvm_unreachable(nullptr);
5590       }
5591     }
5592   } else {
5593     // All arguments are treated the same.
5594     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5595   }
5596   CCInfo.clearWasPPCF128();
5597 
5598   // Assign locations to all of the outgoing aggregate by value arguments.
5599   SmallVector<CCValAssign, 16> ByValArgLocs;
5600   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5601 
5602   // Reserve stack space for the allocations in CCInfo.
5603   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5604 
5605   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5606 
5607   // Size of the linkage area, parameter list area and the part of the local
5608   // space variable where copies of aggregates which are passed by value are
5609   // stored.
5610   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5611 
5612   // Calculate by how many bytes the stack has to be adjusted in case of tail
5613   // call optimization.
5614   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5615 
5616   // Adjust the stack pointer for the new arguments...
5617   // These operations are automatically eliminated by the prolog/epilog pass
5618   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5619   SDValue CallSeqStart = Chain;
5620 
5621   // Load the return address and frame pointer so it can be moved somewhere else
5622   // later.
5623   SDValue LROp, FPOp;
5624   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5625 
5626   // Set up a copy of the stack pointer for use loading and storing any
5627   // arguments that may not fit in the registers available for argument
5628   // passing.
5629   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5630 
5631   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5632   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5633   SmallVector<SDValue, 8> MemOpChains;
5634 
5635   bool seenFloatArg = false;
5636   // Walk the register/memloc assignments, inserting copies/loads.
5637   // i - Tracks the index into the list of registers allocated for the call
5638   // RealArgIdx - Tracks the index into the list of actual function arguments
5639   // j - Tracks the index into the list of byval arguments
5640   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5641        i != e;
5642        ++i, ++RealArgIdx) {
5643     CCValAssign &VA = ArgLocs[i];
5644     SDValue Arg = OutVals[RealArgIdx];
5645     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5646 
5647     if (Flags.isByVal()) {
5648       // Argument is an aggregate which is passed by value, thus we need to
5649       // create a copy of it in the local variable space of the current stack
5650       // frame (which is the stack frame of the caller) and pass the address of
5651       // this copy to the callee.
5652       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5653       CCValAssign &ByValVA = ByValArgLocs[j++];
5654       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5655 
5656       // Memory reserved in the local variable space of the callers stack frame.
5657       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5658 
5659       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5660       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5661                            StackPtr, PtrOff);
5662 
5663       // Create a copy of the argument in the local area of the current
5664       // stack frame.
5665       SDValue MemcpyCall =
5666         CreateCopyOfByValArgument(Arg, PtrOff,
5667                                   CallSeqStart.getNode()->getOperand(0),
5668                                   Flags, DAG, dl);
5669 
5670       // This must go outside the CALLSEQ_START..END.
5671       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5672                                                      SDLoc(MemcpyCall));
5673       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5674                              NewCallSeqStart.getNode());
5675       Chain = CallSeqStart = NewCallSeqStart;
5676 
5677       // Pass the address of the aggregate copy on the stack either in a
5678       // physical register or in the parameter list area of the current stack
5679       // frame to the callee.
5680       Arg = PtrOff;
5681     }
5682 
5683     // When useCRBits() is true, there can be i1 arguments.
5684     // It is because getRegisterType(MVT::i1) => MVT::i1,
5685     // and for other integer types getRegisterType() => MVT::i32.
5686     // Extend i1 and ensure callee will get i32.
5687     if (Arg.getValueType() == MVT::i1)
5688       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5689                         dl, MVT::i32, Arg);
5690 
5691     if (VA.isRegLoc()) {
5692       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5693       // Put argument in a physical register.
5694       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5695         bool IsLE = Subtarget.isLittleEndian();
5696         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5697                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5698         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5699         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5700                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5701         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5702                              SVal.getValue(0)));
5703       } else
5704         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5705     } else {
5706       // Put argument in the parameter list area of the current stack frame.
5707       assert(VA.isMemLoc());
5708       unsigned LocMemOffset = VA.getLocMemOffset();
5709 
5710       if (!isTailCall) {
5711         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5712         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5713                              StackPtr, PtrOff);
5714 
5715         MemOpChains.push_back(
5716             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5717       } else {
5718         // Calculate and remember argument location.
5719         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5720                                  TailCallArguments);
5721       }
5722     }
5723   }
5724 
5725   if (!MemOpChains.empty())
5726     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5727 
5728   // Build a sequence of copy-to-reg nodes chained together with token chain
5729   // and flag operands which copy the outgoing args into the appropriate regs.
5730   SDValue InFlag;
5731   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5732     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5733                              RegsToPass[i].second, InFlag);
5734     InFlag = Chain.getValue(1);
5735   }
5736 
5737   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5738   // registers.
5739   if (isVarArg) {
5740     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5741     SDValue Ops[] = { Chain, InFlag };
5742 
5743     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5744                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5745 
5746     InFlag = Chain.getValue(1);
5747   }
5748 
5749   if (isTailCall)
5750     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5751                     TailCallArguments);
5752 
5753   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5754                     /* unused except on PPC64 ELFv1 */ false, DAG,
5755                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5756                     NumBytes, Ins, InVals, CS);
5757 }
5758 
5759 // Copy an argument into memory, being careful to do this outside the
5760 // call sequence for the call to which the argument belongs.
5761 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5762     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5763     SelectionDAG &DAG, const SDLoc &dl) const {
5764   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5765                         CallSeqStart.getNode()->getOperand(0),
5766                         Flags, DAG, dl);
5767   // The MEMCPY must go outside the CALLSEQ_START..END.
5768   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5769   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5770                                                  SDLoc(MemcpyCall));
5771   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5772                          NewCallSeqStart.getNode());
5773   return NewCallSeqStart;
5774 }
5775 
5776 SDValue PPCTargetLowering::LowerCall_64SVR4(
5777     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5778     bool isTailCall, bool isPatchPoint,
5779     const SmallVectorImpl<ISD::OutputArg> &Outs,
5780     const SmallVectorImpl<SDValue> &OutVals,
5781     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5782     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5783     ImmutableCallSite CS) const {
5784   bool isELFv2ABI = Subtarget.isELFv2ABI();
5785   bool isLittleEndian = Subtarget.isLittleEndian();
5786   unsigned NumOps = Outs.size();
5787   bool hasNest = false;
5788   bool IsSibCall = false;
5789 
5790   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5791   unsigned PtrByteSize = 8;
5792 
5793   MachineFunction &MF = DAG.getMachineFunction();
5794 
5795   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5796     IsSibCall = true;
5797 
5798   // Mark this function as potentially containing a function that contains a
5799   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5800   // and restoring the callers stack pointer in this functions epilog. This is
5801   // done because by tail calling the called function might overwrite the value
5802   // in this function's (MF) stack pointer stack slot 0(SP).
5803   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5804       CallConv == CallingConv::Fast)
5805     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5806 
5807   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5808          "fastcc not supported on varargs functions");
5809 
5810   // Count how many bytes are to be pushed on the stack, including the linkage
5811   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5812   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5813   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5814   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5815   unsigned NumBytes = LinkageSize;
5816   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5817   unsigned &QFPR_idx = FPR_idx;
5818 
5819   static const MCPhysReg GPR[] = {
5820     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5821     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5822   };
5823   static const MCPhysReg VR[] = {
5824     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5825     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5826   };
5827 
5828   const unsigned NumGPRs = array_lengthof(GPR);
5829   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5830   const unsigned NumVRs  = array_lengthof(VR);
5831   const unsigned NumQFPRs = NumFPRs;
5832 
5833   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5834   // can be passed to the callee in registers.
5835   // For the fast calling convention, there is another check below.
5836   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5837   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5838   if (!HasParameterArea) {
5839     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5840     unsigned AvailableFPRs = NumFPRs;
5841     unsigned AvailableVRs = NumVRs;
5842     unsigned NumBytesTmp = NumBytes;
5843     for (unsigned i = 0; i != NumOps; ++i) {
5844       if (Outs[i].Flags.isNest()) continue;
5845       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5846                                 PtrByteSize, LinkageSize, ParamAreaSize,
5847                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5848                                 Subtarget.hasQPX()))
5849         HasParameterArea = true;
5850     }
5851   }
5852 
5853   // When using the fast calling convention, we don't provide backing for
5854   // arguments that will be in registers.
5855   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5856 
5857   // Avoid allocating parameter area for fastcc functions if all the arguments
5858   // can be passed in the registers.
5859   if (CallConv == CallingConv::Fast)
5860     HasParameterArea = false;
5861 
5862   // Add up all the space actually used.
5863   for (unsigned i = 0; i != NumOps; ++i) {
5864     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5865     EVT ArgVT = Outs[i].VT;
5866     EVT OrigVT = Outs[i].ArgVT;
5867 
5868     if (Flags.isNest())
5869       continue;
5870 
5871     if (CallConv == CallingConv::Fast) {
5872       if (Flags.isByVal()) {
5873         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5874         if (NumGPRsUsed > NumGPRs)
5875           HasParameterArea = true;
5876       } else {
5877         switch (ArgVT.getSimpleVT().SimpleTy) {
5878         default: llvm_unreachable("Unexpected ValueType for argument!");
5879         case MVT::i1:
5880         case MVT::i32:
5881         case MVT::i64:
5882           if (++NumGPRsUsed <= NumGPRs)
5883             continue;
5884           break;
5885         case MVT::v4i32:
5886         case MVT::v8i16:
5887         case MVT::v16i8:
5888         case MVT::v2f64:
5889         case MVT::v2i64:
5890         case MVT::v1i128:
5891         case MVT::f128:
5892           if (++NumVRsUsed <= NumVRs)
5893             continue;
5894           break;
5895         case MVT::v4f32:
5896           // When using QPX, this is handled like a FP register, otherwise, it
5897           // is an Altivec register.
5898           if (Subtarget.hasQPX()) {
5899             if (++NumFPRsUsed <= NumFPRs)
5900               continue;
5901           } else {
5902             if (++NumVRsUsed <= NumVRs)
5903               continue;
5904           }
5905           break;
5906         case MVT::f32:
5907         case MVT::f64:
5908         case MVT::v4f64: // QPX
5909         case MVT::v4i1:  // QPX
5910           if (++NumFPRsUsed <= NumFPRs)
5911             continue;
5912           break;
5913         }
5914         HasParameterArea = true;
5915       }
5916     }
5917 
5918     /* Respect alignment of argument on the stack.  */
5919     unsigned Align =
5920       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5921     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5922 
5923     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5924     if (Flags.isInConsecutiveRegsLast())
5925       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5926   }
5927 
5928   unsigned NumBytesActuallyUsed = NumBytes;
5929 
5930   // In the old ELFv1 ABI,
5931   // the prolog code of the callee may store up to 8 GPR argument registers to
5932   // the stack, allowing va_start to index over them in memory if its varargs.
5933   // Because we cannot tell if this is needed on the caller side, we have to
5934   // conservatively assume that it is needed.  As such, make sure we have at
5935   // least enough stack space for the caller to store the 8 GPRs.
5936   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5937   // really requires memory operands, e.g. a vararg function.
5938   if (HasParameterArea)
5939     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5940   else
5941     NumBytes = LinkageSize;
5942 
5943   // Tail call needs the stack to be aligned.
5944   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5945       CallConv == CallingConv::Fast)
5946     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5947 
5948   int SPDiff = 0;
5949 
5950   // Calculate by how many bytes the stack has to be adjusted in case of tail
5951   // call optimization.
5952   if (!IsSibCall)
5953     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5954 
5955   // To protect arguments on the stack from being clobbered in a tail call,
5956   // force all the loads to happen before doing any other lowering.
5957   if (isTailCall)
5958     Chain = DAG.getStackArgumentTokenFactor(Chain);
5959 
5960   // Adjust the stack pointer for the new arguments...
5961   // These operations are automatically eliminated by the prolog/epilog pass
5962   if (!IsSibCall)
5963     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5964   SDValue CallSeqStart = Chain;
5965 
5966   // Load the return address and frame pointer so it can be move somewhere else
5967   // later.
5968   SDValue LROp, FPOp;
5969   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5970 
5971   // Set up a copy of the stack pointer for use loading and storing any
5972   // arguments that may not fit in the registers available for argument
5973   // passing.
5974   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5975 
5976   // Figure out which arguments are going to go in registers, and which in
5977   // memory.  Also, if this is a vararg function, floating point operations
5978   // must be stored to our stack, and loaded into integer regs as well, if
5979   // any integer regs are available for argument passing.
5980   unsigned ArgOffset = LinkageSize;
5981 
5982   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5983   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5984 
5985   SmallVector<SDValue, 8> MemOpChains;
5986   for (unsigned i = 0; i != NumOps; ++i) {
5987     SDValue Arg = OutVals[i];
5988     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5989     EVT ArgVT = Outs[i].VT;
5990     EVT OrigVT = Outs[i].ArgVT;
5991 
5992     // PtrOff will be used to store the current argument to the stack if a
5993     // register cannot be found for it.
5994     SDValue PtrOff;
5995 
5996     // We re-align the argument offset for each argument, except when using the
5997     // fast calling convention, when we need to make sure we do that only when
5998     // we'll actually use a stack slot.
5999     auto ComputePtrOff = [&]() {
6000       /* Respect alignment of argument on the stack.  */
6001       unsigned Align =
6002         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6003       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
6004 
6005       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6006 
6007       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6008     };
6009 
6010     if (CallConv != CallingConv::Fast) {
6011       ComputePtrOff();
6012 
6013       /* Compute GPR index associated with argument offset.  */
6014       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6015       GPR_idx = std::min(GPR_idx, NumGPRs);
6016     }
6017 
6018     // Promote integers to 64-bit values.
6019     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6020       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6021       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6022       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6023     }
6024 
6025     // FIXME memcpy is used way more than necessary.  Correctness first.
6026     // Note: "by value" is code for passing a structure by value, not
6027     // basic types.
6028     if (Flags.isByVal()) {
6029       // Note: Size includes alignment padding, so
6030       //   struct x { short a; char b; }
6031       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6032       // These are the proper values we need for right-justifying the
6033       // aggregate in a parameter register.
6034       unsigned Size = Flags.getByValSize();
6035 
6036       // An empty aggregate parameter takes up no storage and no
6037       // registers.
6038       if (Size == 0)
6039         continue;
6040 
6041       if (CallConv == CallingConv::Fast)
6042         ComputePtrOff();
6043 
6044       // All aggregates smaller than 8 bytes must be passed right-justified.
6045       if (Size==1 || Size==2 || Size==4) {
6046         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6047         if (GPR_idx != NumGPRs) {
6048           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6049                                         MachinePointerInfo(), VT);
6050           MemOpChains.push_back(Load.getValue(1));
6051           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6052 
6053           ArgOffset += PtrByteSize;
6054           continue;
6055         }
6056       }
6057 
6058       if (GPR_idx == NumGPRs && Size < 8) {
6059         SDValue AddPtr = PtrOff;
6060         if (!isLittleEndian) {
6061           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6062                                           PtrOff.getValueType());
6063           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6064         }
6065         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6066                                                           CallSeqStart,
6067                                                           Flags, DAG, dl);
6068         ArgOffset += PtrByteSize;
6069         continue;
6070       }
6071       // Copy entire object into memory.  There are cases where gcc-generated
6072       // code assumes it is there, even if it could be put entirely into
6073       // registers.  (This is not what the doc says.)
6074 
6075       // FIXME: The above statement is likely due to a misunderstanding of the
6076       // documents.  All arguments must be copied into the parameter area BY
6077       // THE CALLEE in the event that the callee takes the address of any
6078       // formal argument.  That has not yet been implemented.  However, it is
6079       // reasonable to use the stack area as a staging area for the register
6080       // load.
6081 
6082       // Skip this for small aggregates, as we will use the same slot for a
6083       // right-justified copy, below.
6084       if (Size >= 8)
6085         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6086                                                           CallSeqStart,
6087                                                           Flags, DAG, dl);
6088 
6089       // When a register is available, pass a small aggregate right-justified.
6090       if (Size < 8 && GPR_idx != NumGPRs) {
6091         // The easiest way to get this right-justified in a register
6092         // is to copy the structure into the rightmost portion of a
6093         // local variable slot, then load the whole slot into the
6094         // register.
6095         // FIXME: The memcpy seems to produce pretty awful code for
6096         // small aggregates, particularly for packed ones.
6097         // FIXME: It would be preferable to use the slot in the
6098         // parameter save area instead of a new local variable.
6099         SDValue AddPtr = PtrOff;
6100         if (!isLittleEndian) {
6101           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6102           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6103         }
6104         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6105                                                           CallSeqStart,
6106                                                           Flags, DAG, dl);
6107 
6108         // Load the slot into the register.
6109         SDValue Load =
6110             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6111         MemOpChains.push_back(Load.getValue(1));
6112         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6113 
6114         // Done with this argument.
6115         ArgOffset += PtrByteSize;
6116         continue;
6117       }
6118 
6119       // For aggregates larger than PtrByteSize, copy the pieces of the
6120       // object that fit into registers from the parameter save area.
6121       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6122         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6123         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6124         if (GPR_idx != NumGPRs) {
6125           SDValue Load =
6126               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6127           MemOpChains.push_back(Load.getValue(1));
6128           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6129           ArgOffset += PtrByteSize;
6130         } else {
6131           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6132           break;
6133         }
6134       }
6135       continue;
6136     }
6137 
6138     switch (Arg.getSimpleValueType().SimpleTy) {
6139     default: llvm_unreachable("Unexpected ValueType for argument!");
6140     case MVT::i1:
6141     case MVT::i32:
6142     case MVT::i64:
6143       if (Flags.isNest()) {
6144         // The 'nest' parameter, if any, is passed in R11.
6145         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6146         hasNest = true;
6147         break;
6148       }
6149 
6150       // These can be scalar arguments or elements of an integer array type
6151       // passed directly.  Clang may use those instead of "byval" aggregate
6152       // types to avoid forcing arguments to memory unnecessarily.
6153       if (GPR_idx != NumGPRs) {
6154         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6155       } else {
6156         if (CallConv == CallingConv::Fast)
6157           ComputePtrOff();
6158 
6159         assert(HasParameterArea &&
6160                "Parameter area must exist to pass an argument in memory.");
6161         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6162                          true, isTailCall, false, MemOpChains,
6163                          TailCallArguments, dl);
6164         if (CallConv == CallingConv::Fast)
6165           ArgOffset += PtrByteSize;
6166       }
6167       if (CallConv != CallingConv::Fast)
6168         ArgOffset += PtrByteSize;
6169       break;
6170     case MVT::f32:
6171     case MVT::f64: {
6172       // These can be scalar arguments or elements of a float array type
6173       // passed directly.  The latter are used to implement ELFv2 homogenous
6174       // float aggregates.
6175 
6176       // Named arguments go into FPRs first, and once they overflow, the
6177       // remaining arguments go into GPRs and then the parameter save area.
6178       // Unnamed arguments for vararg functions always go to GPRs and
6179       // then the parameter save area.  For now, put all arguments to vararg
6180       // routines always in both locations (FPR *and* GPR or stack slot).
6181       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
6182       bool NeededLoad = false;
6183 
6184       // First load the argument into the next available FPR.
6185       if (FPR_idx != NumFPRs)
6186         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6187 
6188       // Next, load the argument into GPR or stack slot if needed.
6189       if (!NeedGPROrStack)
6190         ;
6191       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
6192         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6193         // once we support fp <-> gpr moves.
6194 
6195         // In the non-vararg case, this can only ever happen in the
6196         // presence of f32 array types, since otherwise we never run
6197         // out of FPRs before running out of GPRs.
6198         SDValue ArgVal;
6199 
6200         // Double values are always passed in a single GPR.
6201         if (Arg.getValueType() != MVT::f32) {
6202           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6203 
6204         // Non-array float values are extended and passed in a GPR.
6205         } else if (!Flags.isInConsecutiveRegs()) {
6206           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6207           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6208 
6209         // If we have an array of floats, we collect every odd element
6210         // together with its predecessor into one GPR.
6211         } else if (ArgOffset % PtrByteSize != 0) {
6212           SDValue Lo, Hi;
6213           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6214           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6215           if (!isLittleEndian)
6216             std::swap(Lo, Hi);
6217           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6218 
6219         // The final element, if even, goes into the first half of a GPR.
6220         } else if (Flags.isInConsecutiveRegsLast()) {
6221           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6222           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6223           if (!isLittleEndian)
6224             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6225                                  DAG.getConstant(32, dl, MVT::i32));
6226 
6227         // Non-final even elements are skipped; they will be handled
6228         // together the with subsequent argument on the next go-around.
6229         } else
6230           ArgVal = SDValue();
6231 
6232         if (ArgVal.getNode())
6233           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6234       } else {
6235         if (CallConv == CallingConv::Fast)
6236           ComputePtrOff();
6237 
6238         // Single-precision floating-point values are mapped to the
6239         // second (rightmost) word of the stack doubleword.
6240         if (Arg.getValueType() == MVT::f32 &&
6241             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6242           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6243           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6244         }
6245 
6246         assert(HasParameterArea &&
6247                "Parameter area must exist to pass an argument in memory.");
6248         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6249                          true, isTailCall, false, MemOpChains,
6250                          TailCallArguments, dl);
6251 
6252         NeededLoad = true;
6253       }
6254       // When passing an array of floats, the array occupies consecutive
6255       // space in the argument area; only round up to the next doubleword
6256       // at the end of the array.  Otherwise, each float takes 8 bytes.
6257       if (CallConv != CallingConv::Fast || NeededLoad) {
6258         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6259                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6260         if (Flags.isInConsecutiveRegsLast())
6261           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6262       }
6263       break;
6264     }
6265     case MVT::v4f32:
6266     case MVT::v4i32:
6267     case MVT::v8i16:
6268     case MVT::v16i8:
6269     case MVT::v2f64:
6270     case MVT::v2i64:
6271     case MVT::v1i128:
6272     case MVT::f128:
6273       if (!Subtarget.hasQPX()) {
6274       // These can be scalar arguments or elements of a vector array type
6275       // passed directly.  The latter are used to implement ELFv2 homogenous
6276       // vector aggregates.
6277 
6278       // For a varargs call, named arguments go into VRs or on the stack as
6279       // usual; unnamed arguments always go to the stack or the corresponding
6280       // GPRs when within range.  For now, we always put the value in both
6281       // locations (or even all three).
6282       if (isVarArg) {
6283         assert(HasParameterArea &&
6284                "Parameter area must exist if we have a varargs call.");
6285         // We could elide this store in the case where the object fits
6286         // entirely in R registers.  Maybe later.
6287         SDValue Store =
6288             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6289         MemOpChains.push_back(Store);
6290         if (VR_idx != NumVRs) {
6291           SDValue Load =
6292               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6293           MemOpChains.push_back(Load.getValue(1));
6294           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6295         }
6296         ArgOffset += 16;
6297         for (unsigned i=0; i<16; i+=PtrByteSize) {
6298           if (GPR_idx == NumGPRs)
6299             break;
6300           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6301                                    DAG.getConstant(i, dl, PtrVT));
6302           SDValue Load =
6303               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6304           MemOpChains.push_back(Load.getValue(1));
6305           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6306         }
6307         break;
6308       }
6309 
6310       // Non-varargs Altivec params go into VRs or on the stack.
6311       if (VR_idx != NumVRs) {
6312         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6313       } else {
6314         if (CallConv == CallingConv::Fast)
6315           ComputePtrOff();
6316 
6317         assert(HasParameterArea &&
6318                "Parameter area must exist to pass an argument in memory.");
6319         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6320                          true, isTailCall, true, MemOpChains,
6321                          TailCallArguments, dl);
6322         if (CallConv == CallingConv::Fast)
6323           ArgOffset += 16;
6324       }
6325 
6326       if (CallConv != CallingConv::Fast)
6327         ArgOffset += 16;
6328       break;
6329       } // not QPX
6330 
6331       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6332              "Invalid QPX parameter type");
6333 
6334       LLVM_FALLTHROUGH;
6335     case MVT::v4f64:
6336     case MVT::v4i1: {
6337       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6338       if (isVarArg) {
6339         assert(HasParameterArea &&
6340                "Parameter area must exist if we have a varargs call.");
6341         // We could elide this store in the case where the object fits
6342         // entirely in R registers.  Maybe later.
6343         SDValue Store =
6344             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6345         MemOpChains.push_back(Store);
6346         if (QFPR_idx != NumQFPRs) {
6347           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6348                                      PtrOff, MachinePointerInfo());
6349           MemOpChains.push_back(Load.getValue(1));
6350           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6351         }
6352         ArgOffset += (IsF32 ? 16 : 32);
6353         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6354           if (GPR_idx == NumGPRs)
6355             break;
6356           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6357                                    DAG.getConstant(i, dl, PtrVT));
6358           SDValue Load =
6359               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6360           MemOpChains.push_back(Load.getValue(1));
6361           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6362         }
6363         break;
6364       }
6365 
6366       // Non-varargs QPX params go into registers or on the stack.
6367       if (QFPR_idx != NumQFPRs) {
6368         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6369       } else {
6370         if (CallConv == CallingConv::Fast)
6371           ComputePtrOff();
6372 
6373         assert(HasParameterArea &&
6374                "Parameter area must exist to pass an argument in memory.");
6375         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6376                          true, isTailCall, true, MemOpChains,
6377                          TailCallArguments, dl);
6378         if (CallConv == CallingConv::Fast)
6379           ArgOffset += (IsF32 ? 16 : 32);
6380       }
6381 
6382       if (CallConv != CallingConv::Fast)
6383         ArgOffset += (IsF32 ? 16 : 32);
6384       break;
6385       }
6386     }
6387   }
6388 
6389   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6390          "mismatch in size of parameter area");
6391   (void)NumBytesActuallyUsed;
6392 
6393   if (!MemOpChains.empty())
6394     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6395 
6396   // Check if this is an indirect call (MTCTR/BCTRL).
6397   // See prepareDescriptorIndirectCall and buildCallOperands for more
6398   // information about calls through function pointers in the 64-bit SVR4 ABI.
6399   if (!isTailCall && !isPatchPoint &&
6400       !isFunctionGlobalAddress(Callee) &&
6401       !isa<ExternalSymbolSDNode>(Callee)) {
6402     // Load r2 into a virtual register and store it to the TOC save area.
6403     setUsesTOCBasePtr(DAG);
6404     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6405     // TOC save area offset.
6406     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6407     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6408     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6409     Chain = DAG.getStore(
6410         Val.getValue(1), dl, Val, AddPtr,
6411         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6412     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6413     // This does not mean the MTCTR instruction must use R12; it's easier
6414     // to model this as an extra parameter, so do that.
6415     if (isELFv2ABI && !isPatchPoint)
6416       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6417   }
6418 
6419   // Build a sequence of copy-to-reg nodes chained together with token chain
6420   // and flag operands which copy the outgoing args into the appropriate regs.
6421   SDValue InFlag;
6422   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6423     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6424                              RegsToPass[i].second, InFlag);
6425     InFlag = Chain.getValue(1);
6426   }
6427 
6428   if (isTailCall && !IsSibCall)
6429     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6430                     TailCallArguments);
6431 
6432   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6433                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6434                     SPDiff, NumBytes, Ins, InVals, CS);
6435 }
6436 
6437 SDValue PPCTargetLowering::LowerCall_Darwin(
6438     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6439     bool isTailCall, bool isPatchPoint,
6440     const SmallVectorImpl<ISD::OutputArg> &Outs,
6441     const SmallVectorImpl<SDValue> &OutVals,
6442     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6443     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6444     ImmutableCallSite CS) const {
6445   unsigned NumOps = Outs.size();
6446 
6447   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6448   bool isPPC64 = PtrVT == MVT::i64;
6449   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6450 
6451   MachineFunction &MF = DAG.getMachineFunction();
6452 
6453   // Mark this function as potentially containing a function that contains a
6454   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6455   // and restoring the callers stack pointer in this functions epilog. This is
6456   // done because by tail calling the called function might overwrite the value
6457   // in this function's (MF) stack pointer stack slot 0(SP).
6458   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6459       CallConv == CallingConv::Fast)
6460     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6461 
6462   // Count how many bytes are to be pushed on the stack, including the linkage
6463   // area, and parameter passing area.  We start with 24/48 bytes, which is
6464   // prereserved space for [SP][CR][LR][3 x unused].
6465   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6466   unsigned NumBytes = LinkageSize;
6467 
6468   // Add up all the space actually used.
6469   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6470   // they all go in registers, but we must reserve stack space for them for
6471   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6472   // assigned stack space in order, with padding so Altivec parameters are
6473   // 16-byte aligned.
6474   unsigned nAltivecParamsAtEnd = 0;
6475   for (unsigned i = 0; i != NumOps; ++i) {
6476     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6477     EVT ArgVT = Outs[i].VT;
6478     // Varargs Altivec parameters are padded to a 16 byte boundary.
6479     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6480         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6481         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6482       if (!isVarArg && !isPPC64) {
6483         // Non-varargs Altivec parameters go after all the non-Altivec
6484         // parameters; handle those later so we know how much padding we need.
6485         nAltivecParamsAtEnd++;
6486         continue;
6487       }
6488       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6489       NumBytes = ((NumBytes+15)/16)*16;
6490     }
6491     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6492   }
6493 
6494   // Allow for Altivec parameters at the end, if needed.
6495   if (nAltivecParamsAtEnd) {
6496     NumBytes = ((NumBytes+15)/16)*16;
6497     NumBytes += 16*nAltivecParamsAtEnd;
6498   }
6499 
6500   // The prolog code of the callee may store up to 8 GPR argument registers to
6501   // the stack, allowing va_start to index over them in memory if its varargs.
6502   // Because we cannot tell if this is needed on the caller side, we have to
6503   // conservatively assume that it is needed.  As such, make sure we have at
6504   // least enough stack space for the caller to store the 8 GPRs.
6505   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6506 
6507   // Tail call needs the stack to be aligned.
6508   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6509       CallConv == CallingConv::Fast)
6510     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6511 
6512   // Calculate by how many bytes the stack has to be adjusted in case of tail
6513   // call optimization.
6514   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6515 
6516   // To protect arguments on the stack from being clobbered in a tail call,
6517   // force all the loads to happen before doing any other lowering.
6518   if (isTailCall)
6519     Chain = DAG.getStackArgumentTokenFactor(Chain);
6520 
6521   // Adjust the stack pointer for the new arguments...
6522   // These operations are automatically eliminated by the prolog/epilog pass
6523   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6524   SDValue CallSeqStart = Chain;
6525 
6526   // Load the return address and frame pointer so it can be move somewhere else
6527   // later.
6528   SDValue LROp, FPOp;
6529   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6530 
6531   // Set up a copy of the stack pointer for use loading and storing any
6532   // arguments that may not fit in the registers available for argument
6533   // passing.
6534   SDValue StackPtr;
6535   if (isPPC64)
6536     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6537   else
6538     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6539 
6540   // Figure out which arguments are going to go in registers, and which in
6541   // memory.  Also, if this is a vararg function, floating point operations
6542   // must be stored to our stack, and loaded into integer regs as well, if
6543   // any integer regs are available for argument passing.
6544   unsigned ArgOffset = LinkageSize;
6545   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6546 
6547   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6548     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6549     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6550   };
6551   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6552     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6553     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6554   };
6555   static const MCPhysReg VR[] = {
6556     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6557     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6558   };
6559   const unsigned NumGPRs = array_lengthof(GPR_32);
6560   const unsigned NumFPRs = 13;
6561   const unsigned NumVRs  = array_lengthof(VR);
6562 
6563   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6564 
6565   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6566   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6567 
6568   SmallVector<SDValue, 8> MemOpChains;
6569   for (unsigned i = 0; i != NumOps; ++i) {
6570     SDValue Arg = OutVals[i];
6571     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6572 
6573     // PtrOff will be used to store the current argument to the stack if a
6574     // register cannot be found for it.
6575     SDValue PtrOff;
6576 
6577     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6578 
6579     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6580 
6581     // On PPC64, promote integers to 64-bit values.
6582     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6583       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6584       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6585       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6586     }
6587 
6588     // FIXME memcpy is used way more than necessary.  Correctness first.
6589     // Note: "by value" is code for passing a structure by value, not
6590     // basic types.
6591     if (Flags.isByVal()) {
6592       unsigned Size = Flags.getByValSize();
6593       // Very small objects are passed right-justified.  Everything else is
6594       // passed left-justified.
6595       if (Size==1 || Size==2) {
6596         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6597         if (GPR_idx != NumGPRs) {
6598           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6599                                         MachinePointerInfo(), VT);
6600           MemOpChains.push_back(Load.getValue(1));
6601           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6602 
6603           ArgOffset += PtrByteSize;
6604         } else {
6605           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6606                                           PtrOff.getValueType());
6607           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6608           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6609                                                             CallSeqStart,
6610                                                             Flags, DAG, dl);
6611           ArgOffset += PtrByteSize;
6612         }
6613         continue;
6614       }
6615       // Copy entire object into memory.  There are cases where gcc-generated
6616       // code assumes it is there, even if it could be put entirely into
6617       // registers.  (This is not what the doc says.)
6618       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6619                                                         CallSeqStart,
6620                                                         Flags, DAG, dl);
6621 
6622       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6623       // copy the pieces of the object that fit into registers from the
6624       // parameter save area.
6625       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6626         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6627         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6628         if (GPR_idx != NumGPRs) {
6629           SDValue Load =
6630               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6631           MemOpChains.push_back(Load.getValue(1));
6632           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6633           ArgOffset += PtrByteSize;
6634         } else {
6635           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6636           break;
6637         }
6638       }
6639       continue;
6640     }
6641 
6642     switch (Arg.getSimpleValueType().SimpleTy) {
6643     default: llvm_unreachable("Unexpected ValueType for argument!");
6644     case MVT::i1:
6645     case MVT::i32:
6646     case MVT::i64:
6647       if (GPR_idx != NumGPRs) {
6648         if (Arg.getValueType() == MVT::i1)
6649           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6650 
6651         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6652       } else {
6653         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6654                          isPPC64, isTailCall, false, MemOpChains,
6655                          TailCallArguments, dl);
6656       }
6657       ArgOffset += PtrByteSize;
6658       break;
6659     case MVT::f32:
6660     case MVT::f64:
6661       if (FPR_idx != NumFPRs) {
6662         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6663 
6664         if (isVarArg) {
6665           SDValue Store =
6666               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6667           MemOpChains.push_back(Store);
6668 
6669           // Float varargs are always shadowed in available integer registers
6670           if (GPR_idx != NumGPRs) {
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           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6677             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6678             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6679             SDValue Load =
6680                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6681             MemOpChains.push_back(Load.getValue(1));
6682             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6683           }
6684         } else {
6685           // If we have any FPRs remaining, we may also have GPRs remaining.
6686           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6687           // GPRs.
6688           if (GPR_idx != NumGPRs)
6689             ++GPR_idx;
6690           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6691               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6692             ++GPR_idx;
6693         }
6694       } else
6695         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6696                          isPPC64, isTailCall, false, MemOpChains,
6697                          TailCallArguments, dl);
6698       if (isPPC64)
6699         ArgOffset += 8;
6700       else
6701         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6702       break;
6703     case MVT::v4f32:
6704     case MVT::v4i32:
6705     case MVT::v8i16:
6706     case MVT::v16i8:
6707       if (isVarArg) {
6708         // These go aligned on the stack, or in the corresponding R registers
6709         // when within range.  The Darwin PPC ABI doc claims they also go in
6710         // V registers; in fact gcc does this only for arguments that are
6711         // prototyped, not for those that match the ...  We do it for all
6712         // arguments, seems to work.
6713         while (ArgOffset % 16 !=0) {
6714           ArgOffset += PtrByteSize;
6715           if (GPR_idx != NumGPRs)
6716             GPR_idx++;
6717         }
6718         // We could elide this store in the case where the object fits
6719         // entirely in R registers.  Maybe later.
6720         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6721                              DAG.getConstant(ArgOffset, dl, PtrVT));
6722         SDValue Store =
6723             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6724         MemOpChains.push_back(Store);
6725         if (VR_idx != NumVRs) {
6726           SDValue Load =
6727               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6728           MemOpChains.push_back(Load.getValue(1));
6729           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6730         }
6731         ArgOffset += 16;
6732         for (unsigned i=0; i<16; i+=PtrByteSize) {
6733           if (GPR_idx == NumGPRs)
6734             break;
6735           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6736                                    DAG.getConstant(i, dl, PtrVT));
6737           SDValue Load =
6738               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6739           MemOpChains.push_back(Load.getValue(1));
6740           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6741         }
6742         break;
6743       }
6744 
6745       // Non-varargs Altivec params generally go in registers, but have
6746       // stack space allocated at the end.
6747       if (VR_idx != NumVRs) {
6748         // Doesn't have GPR space allocated.
6749         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6750       } else if (nAltivecParamsAtEnd==0) {
6751         // We are emitting Altivec params in order.
6752         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6753                          isPPC64, isTailCall, true, MemOpChains,
6754                          TailCallArguments, dl);
6755         ArgOffset += 16;
6756       }
6757       break;
6758     }
6759   }
6760   // If all Altivec parameters fit in registers, as they usually do,
6761   // they get stack space following the non-Altivec parameters.  We
6762   // don't track this here because nobody below needs it.
6763   // If there are more Altivec parameters than fit in registers emit
6764   // the stores here.
6765   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6766     unsigned j = 0;
6767     // Offset is aligned; skip 1st 12 params which go in V registers.
6768     ArgOffset = ((ArgOffset+15)/16)*16;
6769     ArgOffset += 12*16;
6770     for (unsigned i = 0; i != NumOps; ++i) {
6771       SDValue Arg = OutVals[i];
6772       EVT ArgType = Outs[i].VT;
6773       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6774           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6775         if (++j > NumVRs) {
6776           SDValue PtrOff;
6777           // We are emitting Altivec params in order.
6778           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6779                            isPPC64, isTailCall, true, MemOpChains,
6780                            TailCallArguments, dl);
6781           ArgOffset += 16;
6782         }
6783       }
6784     }
6785   }
6786 
6787   if (!MemOpChains.empty())
6788     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6789 
6790   // On Darwin, R12 must contain the address of an indirect callee.  This does
6791   // not mean the MTCTR instruction must use R12; it's easier to model this as
6792   // an extra parameter, so do that.
6793   if (!isTailCall &&
6794       !isFunctionGlobalAddress(Callee) &&
6795       !isa<ExternalSymbolSDNode>(Callee) &&
6796       !isBLACompatibleAddress(Callee, DAG))
6797     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6798                                                    PPC::R12), Callee));
6799 
6800   // Build a sequence of copy-to-reg nodes chained together with token chain
6801   // and flag operands which copy the outgoing args into the appropriate regs.
6802   SDValue InFlag;
6803   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6804     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6805                              RegsToPass[i].second, InFlag);
6806     InFlag = Chain.getValue(1);
6807   }
6808 
6809   if (isTailCall)
6810     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6811                     TailCallArguments);
6812 
6813   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6814                     /* unused except on PPC64 ELFv1 */ false, DAG,
6815                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6816                     NumBytes, Ins, InVals, CS);
6817 }
6818 
6819 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6820                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6821                    CCState &State) {
6822 
6823   if (ValVT == MVT::f128)
6824     report_fatal_error("f128 is unimplemented on AIX.");
6825 
6826   if (ArgFlags.isByVal())
6827     report_fatal_error("Passing structure by value is unimplemented.");
6828 
6829   if (ArgFlags.isNest())
6830     report_fatal_error("Nest arguments are unimplemented.");
6831 
6832   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6833       State.getMachineFunction().getSubtarget());
6834   const bool IsPPC64 = Subtarget.isPPC64();
6835   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6836 
6837   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6838                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6839                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6840   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6841                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6842                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6843 
6844   // Arguments always reserve parameter save area.
6845   switch (ValVT.SimpleTy) {
6846   default:
6847     report_fatal_error("Unhandled value type for argument.");
6848   case MVT::i64:
6849     // i64 arguments should have been split to i32 for PPC32.
6850     assert(IsPPC64 && "PPC32 should have split i64 values.");
6851     LLVM_FALLTHROUGH;
6852   case MVT::i1:
6853   case MVT::i32:
6854     State.AllocateStack(PtrByteSize, PtrByteSize);
6855     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6856       MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6857       // Promote integers if needed.
6858       if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6859         LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6860                                     : CCValAssign::LocInfo::ZExt;
6861       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6862     }
6863     else
6864       report_fatal_error("Handling of placing parameters on the stack is "
6865                          "unimplemented!");
6866     return false;
6867 
6868   case MVT::f32:
6869   case MVT::f64: {
6870     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6871     const unsigned StoreSize = LocVT.getStoreSize();
6872     // Floats are always 4-byte aligned in the PSA on AIX.
6873     // This includes f64 in 64-bit mode for ABI compatibility.
6874     State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6875     if (unsigned Reg = State.AllocateReg(FPR))
6876       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::f64, LocInfo));
6877     else
6878       report_fatal_error("Handling of placing parameters on the stack is "
6879                          "unimplemented!");
6880 
6881     // f32 reserves 1 GPR in both PPC32 and PPC64.
6882     // f64 reserves 2 GPRs in PPC32 and 1 GPR in PPC64.
6883     for (unsigned i = 0; i < StoreSize; i += PtrByteSize)
6884       State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32);
6885     return false;
6886   }
6887   }
6888 }
6889 
6890 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6891                                                     bool IsPPC64) {
6892   assert((IsPPC64 || SVT != MVT::i64) &&
6893          "i64 should have been split for 32-bit codegen.");
6894 
6895   switch (SVT) {
6896   default:
6897     report_fatal_error("Unexpected value type for formal argument");
6898   case MVT::i1:
6899   case MVT::i32:
6900   case MVT::i64:
6901     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6902   case MVT::f32:
6903     return &PPC::F4RCRegClass;
6904   case MVT::f64:
6905     return &PPC::F8RCRegClass;
6906   }
6907 }
6908 
6909 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6910                                         SelectionDAG &DAG, SDValue ArgValue,
6911                                         MVT LocVT, const SDLoc &dl) {
6912   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6913   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6914 
6915   if (Flags.isSExt())
6916     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6917                            DAG.getValueType(ValVT));
6918   else if (Flags.isZExt())
6919     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6920                            DAG.getValueType(ValVT));
6921 
6922   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6923 }
6924 
6925 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6926     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6927     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6928     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6929 
6930   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6931           CallConv == CallingConv::Fast) &&
6932          "Unexpected calling convention!");
6933 
6934   if (isVarArg)
6935     report_fatal_error("This call type is unimplemented on AIX.");
6936 
6937   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6938     report_fatal_error("Tail call support is unimplemented on AIX.");
6939 
6940   if (useSoftFloat())
6941     report_fatal_error("Soft float support is unimplemented on AIX.");
6942 
6943   const PPCSubtarget &Subtarget =
6944       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6945   if (Subtarget.hasQPX())
6946     report_fatal_error("QPX support is not supported on AIX.");
6947 
6948   const bool IsPPC64 = Subtarget.isPPC64();
6949   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6950 
6951   // Assign locations to all of the incoming arguments.
6952   SmallVector<CCValAssign, 16> ArgLocs;
6953   MachineFunction &MF = DAG.getMachineFunction();
6954   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6955 
6956   // Reserve space for the linkage area on the stack.
6957   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6958   // On AIX a minimum of 8 words is saved to the parameter save area.
6959   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
6960   CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize);
6961   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6962 
6963   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
6964     CCValAssign &VA = ArgLocs[i];
6965     SDValue ArgValue;
6966     ISD::ArgFlagsTy Flags = Ins[i].Flags;
6967     if (VA.isRegLoc()) {
6968       EVT ValVT = VA.getValVT();
6969       MVT LocVT = VA.getLocVT();
6970       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
6971       unsigned VReg =
6972           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
6973       ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6974       if (ValVT.isScalarInteger() &&
6975           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
6976         ArgValue =
6977             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
6978       }
6979       InVals.push_back(ArgValue);
6980     } else {
6981       report_fatal_error("Handling of formal arguments on the stack is "
6982                          "unimplemented!");
6983     }
6984   }
6985 
6986   // Area that is at least reserved in the caller of this function.
6987   unsigned MinReservedArea = CCInfo.getNextStackOffset();
6988 
6989   // Set the size that is at least reserved in caller of this function. Tail
6990   // call optimized function's reserved stack space needs to be aligned so
6991   // that taking the difference between two stack areas will result in an
6992   // aligned stack.
6993   MinReservedArea =
6994       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
6995   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6996   FuncInfo->setMinReservedArea(MinReservedArea);
6997 
6998   return Chain;
6999 }
7000 
7001 SDValue PPCTargetLowering::LowerCall_AIX(
7002     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
7003     bool isTailCall, bool isPatchPoint,
7004     const SmallVectorImpl<ISD::OutputArg> &Outs,
7005     const SmallVectorImpl<SDValue> &OutVals,
7006     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7007     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7008     ImmutableCallSite CS) const {
7009 
7010   assert((CallConv == CallingConv::C ||
7011           CallConv == CallingConv::Cold ||
7012           CallConv == CallingConv::Fast) && "Unexpected calling convention!");
7013 
7014   if (isVarArg || isPatchPoint)
7015     report_fatal_error("This call type is unimplemented on AIX.");
7016 
7017   const PPCSubtarget& Subtarget =
7018       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7019   if (Subtarget.hasQPX())
7020     report_fatal_error("QPX is not supported on AIX.");
7021   if (Subtarget.hasAltivec())
7022     report_fatal_error("Altivec support is unimplemented on AIX.");
7023 
7024   MachineFunction &MF = DAG.getMachineFunction();
7025   SmallVector<CCValAssign, 16> ArgLocs;
7026   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7027 
7028   // Reserve space for the linkage save area (LSA) on the stack.
7029   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7030   //   [SP][CR][LR][2 x reserved][TOC].
7031   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7032   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7033   const unsigned PtrByteSize = Subtarget.isPPC64() ? 8 : 4;
7034   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7035   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7036 
7037   // The prolog code of the callee may store up to 8 GPR argument registers to
7038   // the stack, allowing va_start to index over them in memory if the callee
7039   // is variadic.
7040   // Because we cannot tell if this is needed on the caller side, we have to
7041   // conservatively assume that it is needed.  As such, make sure we have at
7042   // least enough stack space for the caller to store the 8 GPRs.
7043   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7044   const unsigned NumBytes = LinkageSize + MinParameterSaveAreaSize;
7045 
7046   // Adjust the stack pointer for the new arguments...
7047   // These operations are automatically eliminated by the prolog/epilog pass.
7048   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7049   SDValue CallSeqStart = Chain;
7050 
7051   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7052 
7053   for (CCValAssign &VA : ArgLocs) {
7054     SDValue Arg = OutVals[VA.getValNo()];
7055 
7056     switch (VA.getLocInfo()) {
7057     default: report_fatal_error("Unexpected argument extension type.");
7058     case CCValAssign::Full: break;
7059     case CCValAssign::ZExt:
7060       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7061       break;
7062     case CCValAssign::SExt:
7063       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7064       break;
7065     }
7066 
7067     if (VA.isRegLoc())
7068       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7069 
7070     if (VA.isMemLoc())
7071       report_fatal_error("Handling of placing parameters on the stack is "
7072                          "unimplemented!");
7073   }
7074 
7075   // For indirect calls, we need to save the TOC base to the stack for
7076   // restoration after the call.
7077   if (!isTailCall && !isPatchPoint &&
7078       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) {
7079     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7080     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7081     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7082     const unsigned TOCSaveOffset =
7083         Subtarget.getFrameLowering()->getTOCSaveOffset();
7084 
7085     setUsesTOCBasePtr(DAG);
7086     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7087     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7088     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7089     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7090     Chain = DAG.getStore(
7091         Val.getValue(1), dl, Val, AddPtr,
7092         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7093   }
7094 
7095   // Build a sequence of copy-to-reg nodes chained together with token chain
7096   // and flag operands which copy the outgoing args into the appropriate regs.
7097   SDValue InFlag;
7098   for (auto Reg : RegsToPass) {
7099     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7100     InFlag = Chain.getValue(1);
7101   }
7102 
7103   const int SPDiff = 0;
7104   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
7105                     /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass,
7106                     InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins,
7107                     InVals, CS);
7108 }
7109 
7110 bool
7111 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7112                                   MachineFunction &MF, bool isVarArg,
7113                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7114                                   LLVMContext &Context) const {
7115   SmallVector<CCValAssign, 16> RVLocs;
7116   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7117   return CCInfo.CheckReturn(
7118       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7119                 ? RetCC_PPC_Cold
7120                 : RetCC_PPC);
7121 }
7122 
7123 SDValue
7124 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7125                                bool isVarArg,
7126                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7127                                const SmallVectorImpl<SDValue> &OutVals,
7128                                const SDLoc &dl, SelectionDAG &DAG) const {
7129   SmallVector<CCValAssign, 16> RVLocs;
7130   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7131                  *DAG.getContext());
7132   CCInfo.AnalyzeReturn(Outs,
7133                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7134                            ? RetCC_PPC_Cold
7135                            : RetCC_PPC);
7136 
7137   SDValue Flag;
7138   SmallVector<SDValue, 4> RetOps(1, Chain);
7139 
7140   // Copy the result values into the output registers.
7141   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7142     CCValAssign &VA = RVLocs[i];
7143     assert(VA.isRegLoc() && "Can only return in registers!");
7144 
7145     SDValue Arg = OutVals[RealResIdx];
7146 
7147     switch (VA.getLocInfo()) {
7148     default: llvm_unreachable("Unknown loc info!");
7149     case CCValAssign::Full: break;
7150     case CCValAssign::AExt:
7151       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7152       break;
7153     case CCValAssign::ZExt:
7154       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7155       break;
7156     case CCValAssign::SExt:
7157       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7158       break;
7159     }
7160     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7161       bool isLittleEndian = Subtarget.isLittleEndian();
7162       // Legalize ret f64 -> ret 2 x i32.
7163       SDValue SVal =
7164           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7165                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7166       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7167       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7168       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7169                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7170       Flag = Chain.getValue(1);
7171       VA = RVLocs[++i]; // skip ahead to next loc
7172       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7173     } else
7174       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7175     Flag = Chain.getValue(1);
7176     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7177   }
7178 
7179   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7180   const MCPhysReg *I =
7181     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7182   if (I) {
7183     for (; *I; ++I) {
7184 
7185       if (PPC::G8RCRegClass.contains(*I))
7186         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7187       else if (PPC::F8RCRegClass.contains(*I))
7188         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7189       else if (PPC::CRRCRegClass.contains(*I))
7190         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7191       else if (PPC::VRRCRegClass.contains(*I))
7192         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7193       else
7194         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7195     }
7196   }
7197 
7198   RetOps[0] = Chain;  // Update chain.
7199 
7200   // Add the flag if we have it.
7201   if (Flag.getNode())
7202     RetOps.push_back(Flag);
7203 
7204   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7205 }
7206 
7207 SDValue
7208 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7209                                                 SelectionDAG &DAG) const {
7210   SDLoc dl(Op);
7211 
7212   // Get the correct type for integers.
7213   EVT IntVT = Op.getValueType();
7214 
7215   // Get the inputs.
7216   SDValue Chain = Op.getOperand(0);
7217   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7218   // Build a DYNAREAOFFSET node.
7219   SDValue Ops[2] = {Chain, FPSIdx};
7220   SDVTList VTs = DAG.getVTList(IntVT);
7221   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7222 }
7223 
7224 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7225                                              SelectionDAG &DAG) const {
7226   // When we pop the dynamic allocation we need to restore the SP link.
7227   SDLoc dl(Op);
7228 
7229   // Get the correct type for pointers.
7230   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7231 
7232   // Construct the stack pointer operand.
7233   bool isPPC64 = Subtarget.isPPC64();
7234   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7235   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7236 
7237   // Get the operands for the STACKRESTORE.
7238   SDValue Chain = Op.getOperand(0);
7239   SDValue SaveSP = Op.getOperand(1);
7240 
7241   // Load the old link SP.
7242   SDValue LoadLinkSP =
7243       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7244 
7245   // Restore the stack pointer.
7246   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7247 
7248   // Store the old link SP.
7249   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7250 }
7251 
7252 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7253   MachineFunction &MF = DAG.getMachineFunction();
7254   bool isPPC64 = Subtarget.isPPC64();
7255   EVT PtrVT = getPointerTy(MF.getDataLayout());
7256 
7257   // Get current frame pointer save index.  The users of this index will be
7258   // primarily DYNALLOC instructions.
7259   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7260   int RASI = FI->getReturnAddrSaveIndex();
7261 
7262   // If the frame pointer save index hasn't been defined yet.
7263   if (!RASI) {
7264     // Find out what the fix offset of the frame pointer save area.
7265     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7266     // Allocate the frame index for frame pointer save area.
7267     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7268     // Save the result.
7269     FI->setReturnAddrSaveIndex(RASI);
7270   }
7271   return DAG.getFrameIndex(RASI, PtrVT);
7272 }
7273 
7274 SDValue
7275 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7276   MachineFunction &MF = DAG.getMachineFunction();
7277   bool isPPC64 = Subtarget.isPPC64();
7278   EVT PtrVT = getPointerTy(MF.getDataLayout());
7279 
7280   // Get current frame pointer save index.  The users of this index will be
7281   // primarily DYNALLOC instructions.
7282   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7283   int FPSI = FI->getFramePointerSaveIndex();
7284 
7285   // If the frame pointer save index hasn't been defined yet.
7286   if (!FPSI) {
7287     // Find out what the fix offset of the frame pointer save area.
7288     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7289     // Allocate the frame index for frame pointer save area.
7290     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7291     // Save the result.
7292     FI->setFramePointerSaveIndex(FPSI);
7293   }
7294   return DAG.getFrameIndex(FPSI, PtrVT);
7295 }
7296 
7297 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7298                                                    SelectionDAG &DAG) const {
7299   // Get the inputs.
7300   SDValue Chain = Op.getOperand(0);
7301   SDValue Size  = Op.getOperand(1);
7302   SDLoc dl(Op);
7303 
7304   // Get the correct type for pointers.
7305   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7306   // Negate the size.
7307   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7308                                 DAG.getConstant(0, dl, PtrVT), Size);
7309   // Construct a node for the frame pointer save index.
7310   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7311   // Build a DYNALLOC node.
7312   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7313   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7314   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7315 }
7316 
7317 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7318                                                      SelectionDAG &DAG) const {
7319   MachineFunction &MF = DAG.getMachineFunction();
7320 
7321   bool isPPC64 = Subtarget.isPPC64();
7322   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7323 
7324   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7325   return DAG.getFrameIndex(FI, PtrVT);
7326 }
7327 
7328 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7329                                                SelectionDAG &DAG) const {
7330   SDLoc DL(Op);
7331   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7332                      DAG.getVTList(MVT::i32, MVT::Other),
7333                      Op.getOperand(0), Op.getOperand(1));
7334 }
7335 
7336 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7337                                                 SelectionDAG &DAG) const {
7338   SDLoc DL(Op);
7339   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7340                      Op.getOperand(0), Op.getOperand(1));
7341 }
7342 
7343 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7344   if (Op.getValueType().isVector())
7345     return LowerVectorLoad(Op, DAG);
7346 
7347   assert(Op.getValueType() == MVT::i1 &&
7348          "Custom lowering only for i1 loads");
7349 
7350   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7351 
7352   SDLoc dl(Op);
7353   LoadSDNode *LD = cast<LoadSDNode>(Op);
7354 
7355   SDValue Chain = LD->getChain();
7356   SDValue BasePtr = LD->getBasePtr();
7357   MachineMemOperand *MMO = LD->getMemOperand();
7358 
7359   SDValue NewLD =
7360       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7361                      BasePtr, MVT::i8, MMO);
7362   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7363 
7364   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7365   return DAG.getMergeValues(Ops, dl);
7366 }
7367 
7368 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7369   if (Op.getOperand(1).getValueType().isVector())
7370     return LowerVectorStore(Op, DAG);
7371 
7372   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7373          "Custom lowering only for i1 stores");
7374 
7375   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7376 
7377   SDLoc dl(Op);
7378   StoreSDNode *ST = cast<StoreSDNode>(Op);
7379 
7380   SDValue Chain = ST->getChain();
7381   SDValue BasePtr = ST->getBasePtr();
7382   SDValue Value = ST->getValue();
7383   MachineMemOperand *MMO = ST->getMemOperand();
7384 
7385   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7386                       Value);
7387   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7388 }
7389 
7390 // FIXME: Remove this once the ANDI glue bug is fixed:
7391 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7392   assert(Op.getValueType() == MVT::i1 &&
7393          "Custom lowering only for i1 results");
7394 
7395   SDLoc DL(Op);
7396   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
7397                      Op.getOperand(0));
7398 }
7399 
7400 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7401                                                SelectionDAG &DAG) const {
7402 
7403   // Implements a vector truncate that fits in a vector register as a shuffle.
7404   // We want to legalize vector truncates down to where the source fits in
7405   // a vector register (and target is therefore smaller than vector register
7406   // size).  At that point legalization will try to custom lower the sub-legal
7407   // result and get here - where we can contain the truncate as a single target
7408   // operation.
7409 
7410   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7411   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7412   //
7413   // We will implement it for big-endian ordering as this (where x denotes
7414   // undefined):
7415   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7416   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7417   //
7418   // The same operation in little-endian ordering will be:
7419   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7420   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7421 
7422   assert(Op.getValueType().isVector() && "Vector type expected.");
7423 
7424   SDLoc DL(Op);
7425   SDValue N1 = Op.getOperand(0);
7426   unsigned SrcSize = N1.getValueType().getSizeInBits();
7427   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7428   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7429 
7430   EVT TrgVT = Op.getValueType();
7431   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7432   EVT EltVT = TrgVT.getVectorElementType();
7433   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7434   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7435 
7436   // First list the elements we want to keep.
7437   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7438   SmallVector<int, 16> ShuffV;
7439   if (Subtarget.isLittleEndian())
7440     for (unsigned i = 0; i < TrgNumElts; ++i)
7441       ShuffV.push_back(i * SizeMult);
7442   else
7443     for (unsigned i = 1; i <= TrgNumElts; ++i)
7444       ShuffV.push_back(i * SizeMult - 1);
7445 
7446   // Populate the remaining elements with undefs.
7447   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7448     // ShuffV.push_back(i + WideNumElts);
7449     ShuffV.push_back(WideNumElts + 1);
7450 
7451   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7452   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7453 }
7454 
7455 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7456 /// possible.
7457 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7458   // Not FP? Not a fsel.
7459   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7460       !Op.getOperand(2).getValueType().isFloatingPoint())
7461     return Op;
7462 
7463   bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath;
7464   bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath;
7465   // We might be able to do better than this under some circumstances, but in
7466   // general, fsel-based lowering of select is a finite-math-only optimization.
7467   // For more information, see section F.3 of the 2.06 ISA specification.
7468   // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the
7469   // presence of infinities.
7470   if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs))
7471     return Op;
7472   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7473 
7474   EVT ResVT = Op.getValueType();
7475   EVT CmpVT = Op.getOperand(0).getValueType();
7476   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7477   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7478   SDLoc dl(Op);
7479 
7480   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7481     switch (CC) {
7482     default:
7483       // Not a min/max but with finite math, we may still be able to use fsel.
7484       if (HasNoInfs && HasNoNaNs)
7485         break;
7486       return Op;
7487     case ISD::SETOGT:
7488     case ISD::SETGT:
7489       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7490     case ISD::SETOLT:
7491     case ISD::SETLT:
7492       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7493     }
7494   }
7495 
7496   // TODO: Propagate flags from the select rather than global settings.
7497   SDNodeFlags Flags;
7498   Flags.setNoInfs(true);
7499   Flags.setNoNaNs(true);
7500 
7501   // If the RHS of the comparison is a 0.0, we don't need to do the
7502   // subtraction at all.
7503   SDValue Sel1;
7504   if (isFloatingPointZero(RHS))
7505     switch (CC) {
7506     default: break;       // SETUO etc aren't handled by fsel.
7507     case ISD::SETNE:
7508       std::swap(TV, FV);
7509       LLVM_FALLTHROUGH;
7510     case ISD::SETEQ:
7511       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7512         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7513       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7514       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7515         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7516       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7517                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7518     case ISD::SETULT:
7519     case ISD::SETLT:
7520       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7521       LLVM_FALLTHROUGH;
7522     case ISD::SETOGE:
7523     case ISD::SETGE:
7524       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7525         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7526       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7527     case ISD::SETUGT:
7528     case ISD::SETGT:
7529       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7530       LLVM_FALLTHROUGH;
7531     case ISD::SETOLE:
7532     case ISD::SETLE:
7533       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7534         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7535       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7536                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7537     }
7538 
7539   SDValue Cmp;
7540   switch (CC) {
7541   default: break;       // SETUO etc aren't handled by fsel.
7542   case ISD::SETNE:
7543     std::swap(TV, FV);
7544     LLVM_FALLTHROUGH;
7545   case ISD::SETEQ:
7546     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7547     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7548       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7549     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7550     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7551       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7552     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7553                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7554   case ISD::SETULT:
7555   case ISD::SETLT:
7556     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7557     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7558       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7559     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7560   case ISD::SETOGE:
7561   case ISD::SETGE:
7562     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7563     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7564       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7565     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7566   case ISD::SETUGT:
7567   case ISD::SETGT:
7568     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7569     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7570       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7571     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7572   case ISD::SETOLE:
7573   case ISD::SETLE:
7574     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7575     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7576       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7577     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7578   }
7579   return Op;
7580 }
7581 
7582 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7583                                                SelectionDAG &DAG,
7584                                                const SDLoc &dl) const {
7585   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7586   SDValue Src = Op.getOperand(0);
7587   if (Src.getValueType() == MVT::f32)
7588     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7589 
7590   SDValue Tmp;
7591   switch (Op.getSimpleValueType().SimpleTy) {
7592   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7593   case MVT::i32:
7594     Tmp = DAG.getNode(
7595         Op.getOpcode() == ISD::FP_TO_SINT
7596             ? PPCISD::FCTIWZ
7597             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7598         dl, MVT::f64, Src);
7599     break;
7600   case MVT::i64:
7601     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7602            "i64 FP_TO_UINT is supported only with FPCVT");
7603     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7604                                                         PPCISD::FCTIDUZ,
7605                       dl, MVT::f64, Src);
7606     break;
7607   }
7608 
7609   // Convert the FP value to an int value through memory.
7610   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7611     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7612   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7613   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7614   MachinePointerInfo MPI =
7615       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7616 
7617   // Emit a store to the stack slot.
7618   SDValue Chain;
7619   if (i32Stack) {
7620     MachineFunction &MF = DAG.getMachineFunction();
7621     MachineMemOperand *MMO =
7622       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7623     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7624     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7625               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7626   } else
7627     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7628 
7629   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7630   // add in a bias on big endian.
7631   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7632     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7633                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7634     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7635   }
7636 
7637   RLI.Chain = Chain;
7638   RLI.Ptr = FIPtr;
7639   RLI.MPI = MPI;
7640 }
7641 
7642 /// Custom lowers floating point to integer conversions to use
7643 /// the direct move instructions available in ISA 2.07 to avoid the
7644 /// need for load/store combinations.
7645 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7646                                                     SelectionDAG &DAG,
7647                                                     const SDLoc &dl) const {
7648   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7649   SDValue Src = Op.getOperand(0);
7650 
7651   if (Src.getValueType() == MVT::f32)
7652     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7653 
7654   SDValue Tmp;
7655   switch (Op.getSimpleValueType().SimpleTy) {
7656   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7657   case MVT::i32:
7658     Tmp = DAG.getNode(
7659         Op.getOpcode() == ISD::FP_TO_SINT
7660             ? PPCISD::FCTIWZ
7661             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7662         dl, MVT::f64, Src);
7663     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7664     break;
7665   case MVT::i64:
7666     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7667            "i64 FP_TO_UINT is supported only with FPCVT");
7668     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7669                                                         PPCISD::FCTIDUZ,
7670                       dl, MVT::f64, Src);
7671     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7672     break;
7673   }
7674   return Tmp;
7675 }
7676 
7677 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7678                                           const SDLoc &dl) const {
7679 
7680   // FP to INT conversions are legal for f128.
7681   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7682     return Op;
7683 
7684   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7685   // PPC (the libcall is not available).
7686   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7687     if (Op.getValueType() == MVT::i32) {
7688       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7689         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7690                                  MVT::f64, Op.getOperand(0),
7691                                  DAG.getIntPtrConstant(0, dl));
7692         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7693                                  MVT::f64, Op.getOperand(0),
7694                                  DAG.getIntPtrConstant(1, dl));
7695 
7696         // Add the two halves of the long double in round-to-zero mode.
7697         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7698 
7699         // Now use a smaller FP_TO_SINT.
7700         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7701       }
7702       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7703         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7704         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7705         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7706         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7707         // FIXME: generated code sucks.
7708         // TODO: Are there fast-math-flags to propagate to this FSUB?
7709         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7710                                    Op.getOperand(0), Tmp);
7711         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7712         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7713                            DAG.getConstant(0x80000000, dl, MVT::i32));
7714         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7715                                     Op.getOperand(0));
7716         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7717                                ISD::SETGE);
7718       }
7719     }
7720 
7721     return SDValue();
7722   }
7723 
7724   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7725     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7726 
7727   ReuseLoadInfo RLI;
7728   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7729 
7730   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7731                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7732 }
7733 
7734 // We're trying to insert a regular store, S, and then a load, L. If the
7735 // incoming value, O, is a load, we might just be able to have our load use the
7736 // address used by O. However, we don't know if anything else will store to
7737 // that address before we can load from it. To prevent this situation, we need
7738 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7739 // the same chain operand as O, we create a token factor from the chain results
7740 // of O and L, and we replace all uses of O's chain result with that token
7741 // factor (see spliceIntoChain below for this last part).
7742 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7743                                             ReuseLoadInfo &RLI,
7744                                             SelectionDAG &DAG,
7745                                             ISD::LoadExtType ET) const {
7746   SDLoc dl(Op);
7747   if (ET == ISD::NON_EXTLOAD &&
7748       (Op.getOpcode() == ISD::FP_TO_UINT ||
7749        Op.getOpcode() == ISD::FP_TO_SINT) &&
7750       isOperationLegalOrCustom(Op.getOpcode(),
7751                                Op.getOperand(0).getValueType())) {
7752 
7753     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7754     return true;
7755   }
7756 
7757   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7758   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7759       LD->isNonTemporal())
7760     return false;
7761   if (LD->getMemoryVT() != MemVT)
7762     return false;
7763 
7764   RLI.Ptr = LD->getBasePtr();
7765   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7766     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7767            "Non-pre-inc AM on PPC?");
7768     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7769                           LD->getOffset());
7770   }
7771 
7772   RLI.Chain = LD->getChain();
7773   RLI.MPI = LD->getPointerInfo();
7774   RLI.IsDereferenceable = LD->isDereferenceable();
7775   RLI.IsInvariant = LD->isInvariant();
7776   RLI.Alignment = LD->getAlignment();
7777   RLI.AAInfo = LD->getAAInfo();
7778   RLI.Ranges = LD->getRanges();
7779 
7780   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7781   return true;
7782 }
7783 
7784 // Given the head of the old chain, ResChain, insert a token factor containing
7785 // it and NewResChain, and make users of ResChain now be users of that token
7786 // factor.
7787 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7788 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7789                                         SDValue NewResChain,
7790                                         SelectionDAG &DAG) const {
7791   if (!ResChain)
7792     return;
7793 
7794   SDLoc dl(NewResChain);
7795 
7796   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7797                            NewResChain, DAG.getUNDEF(MVT::Other));
7798   assert(TF.getNode() != NewResChain.getNode() &&
7799          "A new TF really is required here");
7800 
7801   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7802   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7803 }
7804 
7805 /// Analyze profitability of direct move
7806 /// prefer float load to int load plus direct move
7807 /// when there is no integer use of int load
7808 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7809   SDNode *Origin = Op.getOperand(0).getNode();
7810   if (Origin->getOpcode() != ISD::LOAD)
7811     return true;
7812 
7813   // If there is no LXSIBZX/LXSIHZX, like Power8,
7814   // prefer direct move if the memory size is 1 or 2 bytes.
7815   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7816   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7817     return true;
7818 
7819   for (SDNode::use_iterator UI = Origin->use_begin(),
7820                             UE = Origin->use_end();
7821        UI != UE; ++UI) {
7822 
7823     // Only look at the users of the loaded value.
7824     if (UI.getUse().get().getResNo() != 0)
7825       continue;
7826 
7827     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7828         UI->getOpcode() != ISD::UINT_TO_FP)
7829       return true;
7830   }
7831 
7832   return false;
7833 }
7834 
7835 /// Custom lowers integer to floating point conversions to use
7836 /// the direct move instructions available in ISA 2.07 to avoid the
7837 /// need for load/store combinations.
7838 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7839                                                     SelectionDAG &DAG,
7840                                                     const SDLoc &dl) const {
7841   assert((Op.getValueType() == MVT::f32 ||
7842           Op.getValueType() == MVT::f64) &&
7843          "Invalid floating point type as target of conversion");
7844   assert(Subtarget.hasFPCVT() &&
7845          "Int to FP conversions with direct moves require FPCVT");
7846   SDValue FP;
7847   SDValue Src = Op.getOperand(0);
7848   bool SinglePrec = Op.getValueType() == MVT::f32;
7849   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7850   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7851   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7852                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7853 
7854   if (WordInt) {
7855     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7856                      dl, MVT::f64, Src);
7857     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7858   }
7859   else {
7860     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7861     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7862   }
7863 
7864   return FP;
7865 }
7866 
7867 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7868 
7869   EVT VecVT = Vec.getValueType();
7870   assert(VecVT.isVector() && "Expected a vector type.");
7871   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7872 
7873   EVT EltVT = VecVT.getVectorElementType();
7874   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7875   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7876 
7877   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7878   SmallVector<SDValue, 16> Ops(NumConcat);
7879   Ops[0] = Vec;
7880   SDValue UndefVec = DAG.getUNDEF(VecVT);
7881   for (unsigned i = 1; i < NumConcat; ++i)
7882     Ops[i] = UndefVec;
7883 
7884   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7885 }
7886 
7887 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7888                                                 const SDLoc &dl) const {
7889 
7890   unsigned Opc = Op.getOpcode();
7891   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7892          "Unexpected conversion type");
7893   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7894          "Supports conversions to v2f64/v4f32 only.");
7895 
7896   bool SignedConv = Opc == ISD::SINT_TO_FP;
7897   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7898 
7899   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7900   EVT WideVT = Wide.getValueType();
7901   unsigned WideNumElts = WideVT.getVectorNumElements();
7902   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7903 
7904   SmallVector<int, 16> ShuffV;
7905   for (unsigned i = 0; i < WideNumElts; ++i)
7906     ShuffV.push_back(i + WideNumElts);
7907 
7908   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7909   int SaveElts = FourEltRes ? 4 : 2;
7910   if (Subtarget.isLittleEndian())
7911     for (int i = 0; i < SaveElts; i++)
7912       ShuffV[i * Stride] = i;
7913   else
7914     for (int i = 1; i <= SaveElts; i++)
7915       ShuffV[i * Stride - 1] = i - 1;
7916 
7917   SDValue ShuffleSrc2 =
7918       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7919   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7920   unsigned ExtendOp =
7921       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7922 
7923   SDValue Extend;
7924   if (!Subtarget.hasP9Altivec() && SignedConv) {
7925     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7926     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7927                          DAG.getValueType(Op.getOperand(0).getValueType()));
7928   } else
7929     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7930 
7931   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7932 }
7933 
7934 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7935                                           SelectionDAG &DAG) const {
7936   SDLoc dl(Op);
7937 
7938   EVT InVT = Op.getOperand(0).getValueType();
7939   EVT OutVT = Op.getValueType();
7940   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7941       isOperationCustom(Op.getOpcode(), InVT))
7942     return LowerINT_TO_FPVector(Op, DAG, dl);
7943 
7944   // Conversions to f128 are legal.
7945   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7946     return Op;
7947 
7948   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7949     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7950       return SDValue();
7951 
7952     SDValue Value = Op.getOperand(0);
7953     // The values are now known to be -1 (false) or 1 (true). To convert this
7954     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7955     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7956     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7957 
7958     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7959 
7960     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7961 
7962     if (Op.getValueType() != MVT::v4f64)
7963       Value = DAG.getNode(ISD::FP_ROUND, dl,
7964                           Op.getValueType(), Value,
7965                           DAG.getIntPtrConstant(1, dl));
7966     return Value;
7967   }
7968 
7969   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7970   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7971     return SDValue();
7972 
7973   if (Op.getOperand(0).getValueType() == MVT::i1)
7974     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7975                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7976                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7977 
7978   // If we have direct moves, we can do all the conversion, skip the store/load
7979   // however, without FPCVT we can't do most conversions.
7980   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7981       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7982     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7983 
7984   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7985          "UINT_TO_FP is supported only with FPCVT");
7986 
7987   // If we have FCFIDS, then use it when converting to single-precision.
7988   // Otherwise, convert to double-precision and then round.
7989   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7990                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7991                                                             : PPCISD::FCFIDS)
7992                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7993                                                             : PPCISD::FCFID);
7994   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7995                   ? MVT::f32
7996                   : MVT::f64;
7997 
7998   if (Op.getOperand(0).getValueType() == MVT::i64) {
7999     SDValue SINT = Op.getOperand(0);
8000     // When converting to single-precision, we actually need to convert
8001     // to double-precision first and then round to single-precision.
8002     // To avoid double-rounding effects during that operation, we have
8003     // to prepare the input operand.  Bits that might be truncated when
8004     // converting to double-precision are replaced by a bit that won't
8005     // be lost at this stage, but is below the single-precision rounding
8006     // position.
8007     //
8008     // However, if -enable-unsafe-fp-math is in effect, accept double
8009     // rounding to avoid the extra overhead.
8010     if (Op.getValueType() == MVT::f32 &&
8011         !Subtarget.hasFPCVT() &&
8012         !DAG.getTarget().Options.UnsafeFPMath) {
8013 
8014       // Twiddle input to make sure the low 11 bits are zero.  (If this
8015       // is the case, we are guaranteed the value will fit into the 53 bit
8016       // mantissa of an IEEE double-precision value without rounding.)
8017       // If any of those low 11 bits were not zero originally, make sure
8018       // bit 12 (value 2048) is set instead, so that the final rounding
8019       // to single-precision gets the correct result.
8020       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8021                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8022       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8023                           Round, DAG.getConstant(2047, dl, MVT::i64));
8024       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8025       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8026                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8027 
8028       // However, we cannot use that value unconditionally: if the magnitude
8029       // of the input value is small, the bit-twiddling we did above might
8030       // end up visibly changing the output.  Fortunately, in that case, we
8031       // don't need to twiddle bits since the original input will convert
8032       // exactly to double-precision floating-point already.  Therefore,
8033       // construct a conditional to use the original value if the top 11
8034       // bits are all sign-bit copies, and use the rounded value computed
8035       // above otherwise.
8036       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8037                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8038       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8039                          Cond, DAG.getConstant(1, dl, MVT::i64));
8040       Cond = DAG.getSetCC(dl, MVT::i32,
8041                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8042 
8043       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8044     }
8045 
8046     ReuseLoadInfo RLI;
8047     SDValue Bits;
8048 
8049     MachineFunction &MF = DAG.getMachineFunction();
8050     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8051       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8052                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8053       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8054     } else if (Subtarget.hasLFIWAX() &&
8055                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8056       MachineMemOperand *MMO =
8057         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8058                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8059       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8060       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8061                                      DAG.getVTList(MVT::f64, MVT::Other),
8062                                      Ops, MVT::i32, MMO);
8063       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8064     } else if (Subtarget.hasFPCVT() &&
8065                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8066       MachineMemOperand *MMO =
8067         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8068                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8069       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8070       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8071                                      DAG.getVTList(MVT::f64, MVT::Other),
8072                                      Ops, MVT::i32, MMO);
8073       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8074     } else if (((Subtarget.hasLFIWAX() &&
8075                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8076                 (Subtarget.hasFPCVT() &&
8077                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8078                SINT.getOperand(0).getValueType() == MVT::i32) {
8079       MachineFrameInfo &MFI = MF.getFrameInfo();
8080       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8081 
8082       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8083       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8084 
8085       SDValue Store =
8086           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8087                        MachinePointerInfo::getFixedStack(
8088                            DAG.getMachineFunction(), FrameIdx));
8089 
8090       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8091              "Expected an i32 store");
8092 
8093       RLI.Ptr = FIdx;
8094       RLI.Chain = Store;
8095       RLI.MPI =
8096           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8097       RLI.Alignment = 4;
8098 
8099       MachineMemOperand *MMO =
8100         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8101                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8102       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8103       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8104                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8105                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8106                                      Ops, MVT::i32, MMO);
8107     } else
8108       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8109 
8110     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8111 
8112     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8113       FP = DAG.getNode(ISD::FP_ROUND, dl,
8114                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8115     return FP;
8116   }
8117 
8118   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8119          "Unhandled INT_TO_FP type in custom expander!");
8120   // Since we only generate this in 64-bit mode, we can take advantage of
8121   // 64-bit registers.  In particular, sign extend the input value into the
8122   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8123   // then lfd it and fcfid it.
8124   MachineFunction &MF = DAG.getMachineFunction();
8125   MachineFrameInfo &MFI = MF.getFrameInfo();
8126   EVT PtrVT = getPointerTy(MF.getDataLayout());
8127 
8128   SDValue Ld;
8129   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8130     ReuseLoadInfo RLI;
8131     bool ReusingLoad;
8132     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8133                                             DAG))) {
8134       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8135       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8136 
8137       SDValue Store =
8138           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8139                        MachinePointerInfo::getFixedStack(
8140                            DAG.getMachineFunction(), FrameIdx));
8141 
8142       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8143              "Expected an i32 store");
8144 
8145       RLI.Ptr = FIdx;
8146       RLI.Chain = Store;
8147       RLI.MPI =
8148           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8149       RLI.Alignment = 4;
8150     }
8151 
8152     MachineMemOperand *MMO =
8153       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8154                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8155     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8156     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8157                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8158                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8159                                  Ops, MVT::i32, MMO);
8160     if (ReusingLoad)
8161       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8162   } else {
8163     assert(Subtarget.isPPC64() &&
8164            "i32->FP without LFIWAX supported only on PPC64");
8165 
8166     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8167     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8168 
8169     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8170                                 Op.getOperand(0));
8171 
8172     // STD the extended value into the stack slot.
8173     SDValue Store = DAG.getStore(
8174         DAG.getEntryNode(), dl, Ext64, FIdx,
8175         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8176 
8177     // Load the value as a double.
8178     Ld = DAG.getLoad(
8179         MVT::f64, dl, Store, FIdx,
8180         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8181   }
8182 
8183   // FCFID it and return it.
8184   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8185   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8186     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8187                      DAG.getIntPtrConstant(0, dl));
8188   return FP;
8189 }
8190 
8191 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8192                                             SelectionDAG &DAG) const {
8193   SDLoc dl(Op);
8194   /*
8195    The rounding mode is in bits 30:31 of FPSR, and has the following
8196    settings:
8197      00 Round to nearest
8198      01 Round to 0
8199      10 Round to +inf
8200      11 Round to -inf
8201 
8202   FLT_ROUNDS, on the other hand, expects the following:
8203     -1 Undefined
8204      0 Round to 0
8205      1 Round to nearest
8206      2 Round to +inf
8207      3 Round to -inf
8208 
8209   To perform the conversion, we do:
8210     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8211   */
8212 
8213   MachineFunction &MF = DAG.getMachineFunction();
8214   EVT VT = Op.getValueType();
8215   EVT PtrVT = getPointerTy(MF.getDataLayout());
8216 
8217   // Save FP Control Word to register
8218   EVT NodeTys[] = {
8219     MVT::f64,    // return register
8220     MVT::Glue    // unused in this context
8221   };
8222   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
8223 
8224   // Save FP register to stack slot
8225   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8226   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8227   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
8228                                MachinePointerInfo());
8229 
8230   // Load FP Control Word from low 32 bits of stack slot.
8231   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8232   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8233   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
8234 
8235   // Transform as necessary
8236   SDValue CWD1 =
8237     DAG.getNode(ISD::AND, dl, MVT::i32,
8238                 CWD, DAG.getConstant(3, dl, MVT::i32));
8239   SDValue CWD2 =
8240     DAG.getNode(ISD::SRL, dl, MVT::i32,
8241                 DAG.getNode(ISD::AND, dl, MVT::i32,
8242                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8243                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8244                             DAG.getConstant(3, dl, MVT::i32)),
8245                 DAG.getConstant(1, dl, MVT::i32));
8246 
8247   SDValue RetVal =
8248     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8249 
8250   return DAG.getNode((VT.getSizeInBits() < 16 ?
8251                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
8252 }
8253 
8254 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8255   EVT VT = Op.getValueType();
8256   unsigned BitWidth = VT.getSizeInBits();
8257   SDLoc dl(Op);
8258   assert(Op.getNumOperands() == 3 &&
8259          VT == Op.getOperand(1).getValueType() &&
8260          "Unexpected SHL!");
8261 
8262   // Expand into a bunch of logical ops.  Note that these ops
8263   // depend on the PPC behavior for oversized shift amounts.
8264   SDValue Lo = Op.getOperand(0);
8265   SDValue Hi = Op.getOperand(1);
8266   SDValue Amt = Op.getOperand(2);
8267   EVT AmtVT = Amt.getValueType();
8268 
8269   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8270                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8271   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8272   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8273   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8274   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8275                              DAG.getConstant(-BitWidth, dl, AmtVT));
8276   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8277   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8278   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8279   SDValue OutOps[] = { OutLo, OutHi };
8280   return DAG.getMergeValues(OutOps, dl);
8281 }
8282 
8283 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8284   EVT VT = Op.getValueType();
8285   SDLoc dl(Op);
8286   unsigned BitWidth = VT.getSizeInBits();
8287   assert(Op.getNumOperands() == 3 &&
8288          VT == Op.getOperand(1).getValueType() &&
8289          "Unexpected SRL!");
8290 
8291   // Expand into a bunch of logical ops.  Note that these ops
8292   // depend on the PPC behavior for oversized shift amounts.
8293   SDValue Lo = Op.getOperand(0);
8294   SDValue Hi = Op.getOperand(1);
8295   SDValue Amt = Op.getOperand(2);
8296   EVT AmtVT = Amt.getValueType();
8297 
8298   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8299                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8300   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8301   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8302   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8303   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8304                              DAG.getConstant(-BitWidth, dl, AmtVT));
8305   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8306   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8307   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8308   SDValue OutOps[] = { OutLo, OutHi };
8309   return DAG.getMergeValues(OutOps, dl);
8310 }
8311 
8312 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8313   SDLoc dl(Op);
8314   EVT VT = Op.getValueType();
8315   unsigned BitWidth = VT.getSizeInBits();
8316   assert(Op.getNumOperands() == 3 &&
8317          VT == Op.getOperand(1).getValueType() &&
8318          "Unexpected SRA!");
8319 
8320   // Expand into a bunch of logical ops, followed by a select_cc.
8321   SDValue Lo = Op.getOperand(0);
8322   SDValue Hi = Op.getOperand(1);
8323   SDValue Amt = Op.getOperand(2);
8324   EVT AmtVT = Amt.getValueType();
8325 
8326   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8327                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8328   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8329   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8330   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8331   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8332                              DAG.getConstant(-BitWidth, dl, AmtVT));
8333   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8334   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8335   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8336                                   Tmp4, Tmp6, ISD::SETLE);
8337   SDValue OutOps[] = { OutLo, OutHi };
8338   return DAG.getMergeValues(OutOps, dl);
8339 }
8340 
8341 //===----------------------------------------------------------------------===//
8342 // Vector related lowering.
8343 //
8344 
8345 /// BuildSplatI - Build a canonical splati of Val with an element size of
8346 /// SplatSize.  Cast the result to VT.
8347 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8348                            SelectionDAG &DAG, const SDLoc &dl) {
8349   static const MVT VTys[] = { // canonical VT to use for each size.
8350     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8351   };
8352 
8353   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8354 
8355   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8356   if (Val == -1)
8357     SplatSize = 1;
8358 
8359   EVT CanonicalVT = VTys[SplatSize-1];
8360 
8361   // Build a canonical splat for this value.
8362   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8363 }
8364 
8365 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8366 /// specified intrinsic ID.
8367 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8368                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8369   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8370   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8371                      DAG.getConstant(IID, dl, MVT::i32), Op);
8372 }
8373 
8374 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8375 /// specified intrinsic ID.
8376 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8377                                 SelectionDAG &DAG, const SDLoc &dl,
8378                                 EVT DestVT = MVT::Other) {
8379   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8380   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8381                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8382 }
8383 
8384 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8385 /// specified intrinsic ID.
8386 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8387                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8388                                 EVT DestVT = MVT::Other) {
8389   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8390   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8391                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8392 }
8393 
8394 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8395 /// amount.  The result has the specified value type.
8396 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8397                            SelectionDAG &DAG, const SDLoc &dl) {
8398   // Force LHS/RHS to be the right type.
8399   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8400   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8401 
8402   int Ops[16];
8403   for (unsigned i = 0; i != 16; ++i)
8404     Ops[i] = i + Amt;
8405   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8406   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8407 }
8408 
8409 /// Do we have an efficient pattern in a .td file for this node?
8410 ///
8411 /// \param V - pointer to the BuildVectorSDNode being matched
8412 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8413 ///
8414 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8415 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8416 /// the opposite is true (expansion is beneficial) are:
8417 /// - The node builds a vector out of integers that are not 32 or 64-bits
8418 /// - The node builds a vector out of constants
8419 /// - The node is a "load-and-splat"
8420 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8421 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8422                                             bool HasDirectMove,
8423                                             bool HasP8Vector) {
8424   EVT VecVT = V->getValueType(0);
8425   bool RightType = VecVT == MVT::v2f64 ||
8426     (HasP8Vector && VecVT == MVT::v4f32) ||
8427     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8428   if (!RightType)
8429     return false;
8430 
8431   bool IsSplat = true;
8432   bool IsLoad = false;
8433   SDValue Op0 = V->getOperand(0);
8434 
8435   // This function is called in a block that confirms the node is not a constant
8436   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8437   // different constants.
8438   if (V->isConstant())
8439     return false;
8440   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8441     if (V->getOperand(i).isUndef())
8442       return false;
8443     // We want to expand nodes that represent load-and-splat even if the
8444     // loaded value is a floating point truncation or conversion to int.
8445     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8446         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8447          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8448         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8449          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8450         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8451          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8452       IsLoad = true;
8453     // If the operands are different or the input is not a load and has more
8454     // uses than just this BV node, then it isn't a splat.
8455     if (V->getOperand(i) != Op0 ||
8456         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8457       IsSplat = false;
8458   }
8459   return !(IsSplat && IsLoad);
8460 }
8461 
8462 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8463 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8464 
8465   SDLoc dl(Op);
8466   SDValue Op0 = Op->getOperand(0);
8467 
8468   if (!EnableQuadPrecision ||
8469       (Op.getValueType() != MVT::f128 ) ||
8470       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8471       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8472       (Op0.getOperand(1).getValueType() != MVT::i64))
8473     return SDValue();
8474 
8475   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8476                      Op0.getOperand(1));
8477 }
8478 
8479 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8480   const SDValue *InputLoad = &Op;
8481   if (InputLoad->getOpcode() == ISD::BITCAST)
8482     InputLoad = &InputLoad->getOperand(0);
8483   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8484     InputLoad = &InputLoad->getOperand(0);
8485   if (InputLoad->getOpcode() != ISD::LOAD)
8486     return nullptr;
8487   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8488   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8489 }
8490 
8491 // If this is a case we can't handle, return null and let the default
8492 // expansion code take care of it.  If we CAN select this case, and if it
8493 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8494 // this case more efficiently than a constant pool load, lower it to the
8495 // sequence of ops that should be used.
8496 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8497                                              SelectionDAG &DAG) const {
8498   SDLoc dl(Op);
8499   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8500   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8501 
8502   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8503     // We first build an i32 vector, load it into a QPX register,
8504     // then convert it to a floating-point vector and compare it
8505     // to a zero vector to get the boolean result.
8506     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8507     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8508     MachinePointerInfo PtrInfo =
8509         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8510     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8511     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8512 
8513     assert(BVN->getNumOperands() == 4 &&
8514       "BUILD_VECTOR for v4i1 does not have 4 operands");
8515 
8516     bool IsConst = true;
8517     for (unsigned i = 0; i < 4; ++i) {
8518       if (BVN->getOperand(i).isUndef()) continue;
8519       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8520         IsConst = false;
8521         break;
8522       }
8523     }
8524 
8525     if (IsConst) {
8526       Constant *One =
8527         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8528       Constant *NegOne =
8529         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8530 
8531       Constant *CV[4];
8532       for (unsigned i = 0; i < 4; ++i) {
8533         if (BVN->getOperand(i).isUndef())
8534           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8535         else if (isNullConstant(BVN->getOperand(i)))
8536           CV[i] = NegOne;
8537         else
8538           CV[i] = One;
8539       }
8540 
8541       Constant *CP = ConstantVector::get(CV);
8542       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8543                                           16 /* alignment */);
8544 
8545       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8546       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8547       return DAG.getMemIntrinsicNode(
8548           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8549           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8550     }
8551 
8552     SmallVector<SDValue, 4> Stores;
8553     for (unsigned i = 0; i < 4; ++i) {
8554       if (BVN->getOperand(i).isUndef()) continue;
8555 
8556       unsigned Offset = 4*i;
8557       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8558       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8559 
8560       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8561       if (StoreSize > 4) {
8562         Stores.push_back(
8563             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8564                               PtrInfo.getWithOffset(Offset), MVT::i32));
8565       } else {
8566         SDValue StoreValue = BVN->getOperand(i);
8567         if (StoreSize < 4)
8568           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8569 
8570         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8571                                       PtrInfo.getWithOffset(Offset)));
8572       }
8573     }
8574 
8575     SDValue StoreChain;
8576     if (!Stores.empty())
8577       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8578     else
8579       StoreChain = DAG.getEntryNode();
8580 
8581     // Now load from v4i32 into the QPX register; this will extend it to
8582     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8583     // is typed as v4f64 because the QPX register integer states are not
8584     // explicitly represented.
8585 
8586     SDValue Ops[] = {StoreChain,
8587                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8588                      FIdx};
8589     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8590 
8591     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8592       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8593     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8594       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8595       LoadedVect);
8596 
8597     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8598 
8599     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8600   }
8601 
8602   // All other QPX vectors are handled by generic code.
8603   if (Subtarget.hasQPX())
8604     return SDValue();
8605 
8606   // Check if this is a splat of a constant value.
8607   APInt APSplatBits, APSplatUndef;
8608   unsigned SplatBitSize;
8609   bool HasAnyUndefs;
8610   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8611                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8612       SplatBitSize > 32) {
8613 
8614     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
8615     // Handle load-and-splat patterns as we have instructions that will do this
8616     // in one go.
8617     if (InputLoad && DAG.isSplatValue(Op, true)) {
8618       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8619 
8620       // We have handling for 4 and 8 byte elements.
8621       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8622 
8623       // Checking for a single use of this load, we have to check for vector
8624       // width (128 bits) / ElementSize uses (since each operand of the
8625       // BUILD_VECTOR is a separate use of the value.
8626       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8627           ((Subtarget.hasVSX() && ElementSize == 64) ||
8628            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8629         SDValue Ops[] = {
8630           LD->getChain(),    // Chain
8631           LD->getBasePtr(),  // Ptr
8632           DAG.getValueType(Op.getValueType()) // VT
8633         };
8634         return
8635           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8636                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8637                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8638       }
8639     }
8640 
8641     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8642     // lowered to VSX instructions under certain conditions.
8643     // Without VSX, there is no pattern more efficient than expanding the node.
8644     if (Subtarget.hasVSX() &&
8645         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8646                                         Subtarget.hasP8Vector()))
8647       return Op;
8648     return SDValue();
8649   }
8650 
8651   unsigned SplatBits = APSplatBits.getZExtValue();
8652   unsigned SplatUndef = APSplatUndef.getZExtValue();
8653   unsigned SplatSize = SplatBitSize / 8;
8654 
8655   // First, handle single instruction cases.
8656 
8657   // All zeros?
8658   if (SplatBits == 0) {
8659     // Canonicalize all zero vectors to be v4i32.
8660     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8661       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8662       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8663     }
8664     return Op;
8665   }
8666 
8667   // We have XXSPLTIB for constant splats one byte wide
8668   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
8669   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
8670   if (Subtarget.hasP9Vector() && SplatSize == 1)
8671     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
8672 
8673   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8674   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8675                     (32-SplatBitSize));
8676   if (SextVal >= -16 && SextVal <= 15)
8677     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8678 
8679   // Two instruction sequences.
8680 
8681   // If this value is in the range [-32,30] and is even, use:
8682   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8683   // If this value is in the range [17,31] and is odd, use:
8684   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8685   // If this value is in the range [-31,-17] and is odd, use:
8686   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8687   // Note the last two are three-instruction sequences.
8688   if (SextVal >= -32 && SextVal <= 31) {
8689     // To avoid having these optimizations undone by constant folding,
8690     // we convert to a pseudo that will be expanded later into one of
8691     // the above forms.
8692     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8693     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8694               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8695     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8696     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8697     if (VT == Op.getValueType())
8698       return RetVal;
8699     else
8700       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8701   }
8702 
8703   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8704   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8705   // for fneg/fabs.
8706   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8707     // Make -1 and vspltisw -1:
8708     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8709 
8710     // Make the VSLW intrinsic, computing 0x8000_0000.
8711     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8712                                    OnesV, DAG, dl);
8713 
8714     // xor by OnesV to invert it.
8715     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8716     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8717   }
8718 
8719   // Check to see if this is a wide variety of vsplti*, binop self cases.
8720   static const signed char SplatCsts[] = {
8721     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8722     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8723   };
8724 
8725   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8726     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8727     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8728     int i = SplatCsts[idx];
8729 
8730     // Figure out what shift amount will be used by altivec if shifted by i in
8731     // this splat size.
8732     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8733 
8734     // vsplti + shl self.
8735     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8736       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8737       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8738         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8739         Intrinsic::ppc_altivec_vslw
8740       };
8741       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8742       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8743     }
8744 
8745     // vsplti + srl self.
8746     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8747       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8748       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8749         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8750         Intrinsic::ppc_altivec_vsrw
8751       };
8752       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8753       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8754     }
8755 
8756     // vsplti + sra self.
8757     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8758       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8759       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8760         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8761         Intrinsic::ppc_altivec_vsraw
8762       };
8763       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8764       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8765     }
8766 
8767     // vsplti + rol self.
8768     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8769                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8770       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8771       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8772         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8773         Intrinsic::ppc_altivec_vrlw
8774       };
8775       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8776       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8777     }
8778 
8779     // t = vsplti c, result = vsldoi t, t, 1
8780     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8781       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8782       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8783       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8784     }
8785     // t = vsplti c, result = vsldoi t, t, 2
8786     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8787       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8788       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8789       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8790     }
8791     // t = vsplti c, result = vsldoi t, t, 3
8792     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8793       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8794       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8795       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8796     }
8797   }
8798 
8799   return SDValue();
8800 }
8801 
8802 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8803 /// the specified operations to build the shuffle.
8804 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8805                                       SDValue RHS, SelectionDAG &DAG,
8806                                       const SDLoc &dl) {
8807   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8808   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8809   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8810 
8811   enum {
8812     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8813     OP_VMRGHW,
8814     OP_VMRGLW,
8815     OP_VSPLTISW0,
8816     OP_VSPLTISW1,
8817     OP_VSPLTISW2,
8818     OP_VSPLTISW3,
8819     OP_VSLDOI4,
8820     OP_VSLDOI8,
8821     OP_VSLDOI12
8822   };
8823 
8824   if (OpNum == OP_COPY) {
8825     if (LHSID == (1*9+2)*9+3) return LHS;
8826     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8827     return RHS;
8828   }
8829 
8830   SDValue OpLHS, OpRHS;
8831   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8832   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8833 
8834   int ShufIdxs[16];
8835   switch (OpNum) {
8836   default: llvm_unreachable("Unknown i32 permute!");
8837   case OP_VMRGHW:
8838     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8839     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8840     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8841     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8842     break;
8843   case OP_VMRGLW:
8844     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8845     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8846     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8847     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8848     break;
8849   case OP_VSPLTISW0:
8850     for (unsigned i = 0; i != 16; ++i)
8851       ShufIdxs[i] = (i&3)+0;
8852     break;
8853   case OP_VSPLTISW1:
8854     for (unsigned i = 0; i != 16; ++i)
8855       ShufIdxs[i] = (i&3)+4;
8856     break;
8857   case OP_VSPLTISW2:
8858     for (unsigned i = 0; i != 16; ++i)
8859       ShufIdxs[i] = (i&3)+8;
8860     break;
8861   case OP_VSPLTISW3:
8862     for (unsigned i = 0; i != 16; ++i)
8863       ShufIdxs[i] = (i&3)+12;
8864     break;
8865   case OP_VSLDOI4:
8866     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8867   case OP_VSLDOI8:
8868     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8869   case OP_VSLDOI12:
8870     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8871   }
8872   EVT VT = OpLHS.getValueType();
8873   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8874   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8875   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8876   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8877 }
8878 
8879 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8880 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8881 /// SDValue.
8882 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8883                                            SelectionDAG &DAG) const {
8884   const unsigned BytesInVector = 16;
8885   bool IsLE = Subtarget.isLittleEndian();
8886   SDLoc dl(N);
8887   SDValue V1 = N->getOperand(0);
8888   SDValue V2 = N->getOperand(1);
8889   unsigned ShiftElts = 0, InsertAtByte = 0;
8890   bool Swap = false;
8891 
8892   // Shifts required to get the byte we want at element 7.
8893   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8894                                    0, 15, 14, 13, 12, 11, 10, 9};
8895   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8896                                 1, 2,  3,  4,  5,  6,  7,  8};
8897 
8898   ArrayRef<int> Mask = N->getMask();
8899   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8900 
8901   // For each mask element, find out if we're just inserting something
8902   // from V2 into V1 or vice versa.
8903   // Possible permutations inserting an element from V2 into V1:
8904   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8905   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8906   //   ...
8907   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8908   // Inserting from V1 into V2 will be similar, except mask range will be
8909   // [16,31].
8910 
8911   bool FoundCandidate = false;
8912   // If both vector operands for the shuffle are the same vector, the mask
8913   // will contain only elements from the first one and the second one will be
8914   // undef.
8915   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8916   // Go through the mask of half-words to find an element that's being moved
8917   // from one vector to the other.
8918   for (unsigned i = 0; i < BytesInVector; ++i) {
8919     unsigned CurrentElement = Mask[i];
8920     // If 2nd operand is undefined, we should only look for element 7 in the
8921     // Mask.
8922     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8923       continue;
8924 
8925     bool OtherElementsInOrder = true;
8926     // Examine the other elements in the Mask to see if they're in original
8927     // order.
8928     for (unsigned j = 0; j < BytesInVector; ++j) {
8929       if (j == i)
8930         continue;
8931       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8932       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8933       // in which we always assume we're always picking from the 1st operand.
8934       int MaskOffset =
8935           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8936       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8937         OtherElementsInOrder = false;
8938         break;
8939       }
8940     }
8941     // If other elements are in original order, we record the number of shifts
8942     // we need to get the element we want into element 7. Also record which byte
8943     // in the vector we should insert into.
8944     if (OtherElementsInOrder) {
8945       // If 2nd operand is undefined, we assume no shifts and no swapping.
8946       if (V2.isUndef()) {
8947         ShiftElts = 0;
8948         Swap = false;
8949       } else {
8950         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8951         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8952                          : BigEndianShifts[CurrentElement & 0xF];
8953         Swap = CurrentElement < BytesInVector;
8954       }
8955       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8956       FoundCandidate = true;
8957       break;
8958     }
8959   }
8960 
8961   if (!FoundCandidate)
8962     return SDValue();
8963 
8964   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8965   // optionally with VECSHL if shift is required.
8966   if (Swap)
8967     std::swap(V1, V2);
8968   if (V2.isUndef())
8969     V2 = V1;
8970   if (ShiftElts) {
8971     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8972                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8973     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8974                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8975   }
8976   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8977                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8978 }
8979 
8980 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8981 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8982 /// SDValue.
8983 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8984                                            SelectionDAG &DAG) const {
8985   const unsigned NumHalfWords = 8;
8986   const unsigned BytesInVector = NumHalfWords * 2;
8987   // Check that the shuffle is on half-words.
8988   if (!isNByteElemShuffleMask(N, 2, 1))
8989     return SDValue();
8990 
8991   bool IsLE = Subtarget.isLittleEndian();
8992   SDLoc dl(N);
8993   SDValue V1 = N->getOperand(0);
8994   SDValue V2 = N->getOperand(1);
8995   unsigned ShiftElts = 0, InsertAtByte = 0;
8996   bool Swap = false;
8997 
8998   // Shifts required to get the half-word we want at element 3.
8999   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9000   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9001 
9002   uint32_t Mask = 0;
9003   uint32_t OriginalOrderLow = 0x1234567;
9004   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9005   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9006   // 32-bit space, only need 4-bit nibbles per element.
9007   for (unsigned i = 0; i < NumHalfWords; ++i) {
9008     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9009     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9010   }
9011 
9012   // For each mask element, find out if we're just inserting something
9013   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9014   // from V2 into V1:
9015   //   X, 1, 2, 3, 4, 5, 6, 7
9016   //   0, X, 2, 3, 4, 5, 6, 7
9017   //   0, 1, X, 3, 4, 5, 6, 7
9018   //   0, 1, 2, X, 4, 5, 6, 7
9019   //   0, 1, 2, 3, X, 5, 6, 7
9020   //   0, 1, 2, 3, 4, X, 6, 7
9021   //   0, 1, 2, 3, 4, 5, X, 7
9022   //   0, 1, 2, 3, 4, 5, 6, X
9023   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9024 
9025   bool FoundCandidate = false;
9026   // Go through the mask of half-words to find an element that's being moved
9027   // from one vector to the other.
9028   for (unsigned i = 0; i < NumHalfWords; ++i) {
9029     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9030     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9031     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9032     uint32_t TargetOrder = 0x0;
9033 
9034     // If both vector operands for the shuffle are the same vector, the mask
9035     // will contain only elements from the first one and the second one will be
9036     // undef.
9037     if (V2.isUndef()) {
9038       ShiftElts = 0;
9039       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9040       TargetOrder = OriginalOrderLow;
9041       Swap = false;
9042       // Skip if not the correct element or mask of other elements don't equal
9043       // to our expected order.
9044       if (MaskOneElt == VINSERTHSrcElem &&
9045           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9046         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9047         FoundCandidate = true;
9048         break;
9049       }
9050     } else { // If both operands are defined.
9051       // Target order is [8,15] if the current mask is between [0,7].
9052       TargetOrder =
9053           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9054       // Skip if mask of other elements don't equal our expected order.
9055       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9056         // We only need the last 3 bits for the number of shifts.
9057         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9058                          : BigEndianShifts[MaskOneElt & 0x7];
9059         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9060         Swap = MaskOneElt < NumHalfWords;
9061         FoundCandidate = true;
9062         break;
9063       }
9064     }
9065   }
9066 
9067   if (!FoundCandidate)
9068     return SDValue();
9069 
9070   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9071   // optionally with VECSHL if shift is required.
9072   if (Swap)
9073     std::swap(V1, V2);
9074   if (V2.isUndef())
9075     V2 = V1;
9076   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9077   if (ShiftElts) {
9078     // Double ShiftElts because we're left shifting on v16i8 type.
9079     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9080                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9081     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9082     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9083                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9084     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9085   }
9086   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9087   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9088                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9089   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9090 }
9091 
9092 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9093 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9094 /// return the code it can be lowered into.  Worst case, it can always be
9095 /// lowered into a vperm.
9096 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9097                                                SelectionDAG &DAG) const {
9098   SDLoc dl(Op);
9099   SDValue V1 = Op.getOperand(0);
9100   SDValue V2 = Op.getOperand(1);
9101   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9102   EVT VT = Op.getValueType();
9103   bool isLittleEndian = Subtarget.isLittleEndian();
9104 
9105   unsigned ShiftElts, InsertAtByte;
9106   bool Swap = false;
9107 
9108   // If this is a load-and-splat, we can do that with a single instruction
9109   // in some cases. However if the load has multiple uses, we don't want to
9110   // combine it because that will just produce multiple loads.
9111   const SDValue *InputLoad = getNormalLoadInput(V1);
9112   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9113       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9114       InputLoad->hasOneUse()) {
9115     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9116     int SplatIdx =
9117       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9118 
9119     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9120     // For 4-byte load-and-splat, we need Power9.
9121     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9122       uint64_t Offset = 0;
9123       if (IsFourByte)
9124         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9125       else
9126         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9127       SDValue BasePtr = LD->getBasePtr();
9128       if (Offset != 0)
9129         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9130                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9131       SDValue Ops[] = {
9132         LD->getChain(),    // Chain
9133         BasePtr,           // BasePtr
9134         DAG.getValueType(Op.getValueType()) // VT
9135       };
9136       SDVTList VTL =
9137         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9138       SDValue LdSplt =
9139         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9140                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9141       if (LdSplt.getValueType() != SVOp->getValueType(0))
9142         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9143       return LdSplt;
9144     }
9145   }
9146   if (Subtarget.hasP9Vector() &&
9147       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9148                            isLittleEndian)) {
9149     if (Swap)
9150       std::swap(V1, V2);
9151     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9152     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9153     if (ShiftElts) {
9154       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9155                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9156       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9157                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9158       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9159     }
9160     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9161                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9162     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9163   }
9164 
9165   if (Subtarget.hasP9Altivec()) {
9166     SDValue NewISDNode;
9167     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9168       return NewISDNode;
9169 
9170     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9171       return NewISDNode;
9172   }
9173 
9174   if (Subtarget.hasVSX() &&
9175       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9176     if (Swap)
9177       std::swap(V1, V2);
9178     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9179     SDValue Conv2 =
9180         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9181 
9182     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9183                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9184     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9185   }
9186 
9187   if (Subtarget.hasVSX() &&
9188     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9189     if (Swap)
9190       std::swap(V1, V2);
9191     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9192     SDValue Conv2 =
9193         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9194 
9195     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9196                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9197     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9198   }
9199 
9200   if (Subtarget.hasP9Vector()) {
9201      if (PPC::isXXBRHShuffleMask(SVOp)) {
9202       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9203       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9204       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9205     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9206       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9207       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9208       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9209     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9210       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9211       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9212       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9213     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9214       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9215       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9216       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9217     }
9218   }
9219 
9220   if (Subtarget.hasVSX()) {
9221     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9222       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9223 
9224       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9225       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9226                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9227       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9228     }
9229 
9230     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9231     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9232       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9233       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9234       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9235     }
9236   }
9237 
9238   if (Subtarget.hasQPX()) {
9239     if (VT.getVectorNumElements() != 4)
9240       return SDValue();
9241 
9242     if (V2.isUndef()) V2 = V1;
9243 
9244     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9245     if (AlignIdx != -1) {
9246       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9247                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9248     } else if (SVOp->isSplat()) {
9249       int SplatIdx = SVOp->getSplatIndex();
9250       if (SplatIdx >= 4) {
9251         std::swap(V1, V2);
9252         SplatIdx -= 4;
9253       }
9254 
9255       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9256                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9257     }
9258 
9259     // Lower this into a qvgpci/qvfperm pair.
9260 
9261     // Compute the qvgpci literal
9262     unsigned idx = 0;
9263     for (unsigned i = 0; i < 4; ++i) {
9264       int m = SVOp->getMaskElt(i);
9265       unsigned mm = m >= 0 ? (unsigned) m : i;
9266       idx |= mm << (3-i)*3;
9267     }
9268 
9269     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9270                              DAG.getConstant(idx, dl, MVT::i32));
9271     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9272   }
9273 
9274   // Cases that are handled by instructions that take permute immediates
9275   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9276   // selected by the instruction selector.
9277   if (V2.isUndef()) {
9278     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9279         PPC::isSplatShuffleMask(SVOp, 2) ||
9280         PPC::isSplatShuffleMask(SVOp, 4) ||
9281         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9282         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9283         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9284         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9285         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9286         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9287         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9288         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9289         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9290         (Subtarget.hasP8Altivec() && (
9291          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9292          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9293          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9294       return Op;
9295     }
9296   }
9297 
9298   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9299   // and produce a fixed permutation.  If any of these match, do not lower to
9300   // VPERM.
9301   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9302   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9303       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9304       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9305       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9306       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9307       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9308       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9309       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9310       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9311       (Subtarget.hasP8Altivec() && (
9312        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9313        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9314        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9315     return Op;
9316 
9317   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9318   // perfect shuffle table to emit an optimal matching sequence.
9319   ArrayRef<int> PermMask = SVOp->getMask();
9320 
9321   unsigned PFIndexes[4];
9322   bool isFourElementShuffle = true;
9323   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9324     unsigned EltNo = 8;   // Start out undef.
9325     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9326       if (PermMask[i*4+j] < 0)
9327         continue;   // Undef, ignore it.
9328 
9329       unsigned ByteSource = PermMask[i*4+j];
9330       if ((ByteSource & 3) != j) {
9331         isFourElementShuffle = false;
9332         break;
9333       }
9334 
9335       if (EltNo == 8) {
9336         EltNo = ByteSource/4;
9337       } else if (EltNo != ByteSource/4) {
9338         isFourElementShuffle = false;
9339         break;
9340       }
9341     }
9342     PFIndexes[i] = EltNo;
9343   }
9344 
9345   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9346   // perfect shuffle vector to determine if it is cost effective to do this as
9347   // discrete instructions, or whether we should use a vperm.
9348   // For now, we skip this for little endian until such time as we have a
9349   // little-endian perfect shuffle table.
9350   if (isFourElementShuffle && !isLittleEndian) {
9351     // Compute the index in the perfect shuffle table.
9352     unsigned PFTableIndex =
9353       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9354 
9355     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9356     unsigned Cost  = (PFEntry >> 30);
9357 
9358     // Determining when to avoid vperm is tricky.  Many things affect the cost
9359     // of vperm, particularly how many times the perm mask needs to be computed.
9360     // For example, if the perm mask can be hoisted out of a loop or is already
9361     // used (perhaps because there are multiple permutes with the same shuffle
9362     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9363     // the loop requires an extra register.
9364     //
9365     // As a compromise, we only emit discrete instructions if the shuffle can be
9366     // generated in 3 or fewer operations.  When we have loop information
9367     // available, if this block is within a loop, we should avoid using vperm
9368     // for 3-operation perms and use a constant pool load instead.
9369     if (Cost < 3)
9370       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9371   }
9372 
9373   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9374   // vector that will get spilled to the constant pool.
9375   if (V2.isUndef()) V2 = V1;
9376 
9377   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9378   // that it is in input element units, not in bytes.  Convert now.
9379 
9380   // For little endian, the order of the input vectors is reversed, and
9381   // the permutation mask is complemented with respect to 31.  This is
9382   // necessary to produce proper semantics with the big-endian-biased vperm
9383   // instruction.
9384   EVT EltVT = V1.getValueType().getVectorElementType();
9385   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9386 
9387   SmallVector<SDValue, 16> ResultMask;
9388   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9389     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9390 
9391     for (unsigned j = 0; j != BytesPerElement; ++j)
9392       if (isLittleEndian)
9393         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9394                                              dl, MVT::i32));
9395       else
9396         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9397                                              MVT::i32));
9398   }
9399 
9400   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9401   if (isLittleEndian)
9402     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9403                        V2, V1, VPermMask);
9404   else
9405     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9406                        V1, V2, VPermMask);
9407 }
9408 
9409 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9410 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9411 /// information about the intrinsic.
9412 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9413                                  bool &isDot, const PPCSubtarget &Subtarget) {
9414   unsigned IntrinsicID =
9415       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9416   CompareOpc = -1;
9417   isDot = false;
9418   switch (IntrinsicID) {
9419   default:
9420     return false;
9421   // Comparison predicates.
9422   case Intrinsic::ppc_altivec_vcmpbfp_p:
9423     CompareOpc = 966;
9424     isDot = true;
9425     break;
9426   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9427     CompareOpc = 198;
9428     isDot = true;
9429     break;
9430   case Intrinsic::ppc_altivec_vcmpequb_p:
9431     CompareOpc = 6;
9432     isDot = true;
9433     break;
9434   case Intrinsic::ppc_altivec_vcmpequh_p:
9435     CompareOpc = 70;
9436     isDot = true;
9437     break;
9438   case Intrinsic::ppc_altivec_vcmpequw_p:
9439     CompareOpc = 134;
9440     isDot = true;
9441     break;
9442   case Intrinsic::ppc_altivec_vcmpequd_p:
9443     if (Subtarget.hasP8Altivec()) {
9444       CompareOpc = 199;
9445       isDot = true;
9446     } else
9447       return false;
9448     break;
9449   case Intrinsic::ppc_altivec_vcmpneb_p:
9450   case Intrinsic::ppc_altivec_vcmpneh_p:
9451   case Intrinsic::ppc_altivec_vcmpnew_p:
9452   case Intrinsic::ppc_altivec_vcmpnezb_p:
9453   case Intrinsic::ppc_altivec_vcmpnezh_p:
9454   case Intrinsic::ppc_altivec_vcmpnezw_p:
9455     if (Subtarget.hasP9Altivec()) {
9456       switch (IntrinsicID) {
9457       default:
9458         llvm_unreachable("Unknown comparison intrinsic.");
9459       case Intrinsic::ppc_altivec_vcmpneb_p:
9460         CompareOpc = 7;
9461         break;
9462       case Intrinsic::ppc_altivec_vcmpneh_p:
9463         CompareOpc = 71;
9464         break;
9465       case Intrinsic::ppc_altivec_vcmpnew_p:
9466         CompareOpc = 135;
9467         break;
9468       case Intrinsic::ppc_altivec_vcmpnezb_p:
9469         CompareOpc = 263;
9470         break;
9471       case Intrinsic::ppc_altivec_vcmpnezh_p:
9472         CompareOpc = 327;
9473         break;
9474       case Intrinsic::ppc_altivec_vcmpnezw_p:
9475         CompareOpc = 391;
9476         break;
9477       }
9478       isDot = true;
9479     } else
9480       return false;
9481     break;
9482   case Intrinsic::ppc_altivec_vcmpgefp_p:
9483     CompareOpc = 454;
9484     isDot = true;
9485     break;
9486   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9487     CompareOpc = 710;
9488     isDot = true;
9489     break;
9490   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9491     CompareOpc = 774;
9492     isDot = true;
9493     break;
9494   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9495     CompareOpc = 838;
9496     isDot = true;
9497     break;
9498   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9499     CompareOpc = 902;
9500     isDot = true;
9501     break;
9502   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9503     if (Subtarget.hasP8Altivec()) {
9504       CompareOpc = 967;
9505       isDot = true;
9506     } else
9507       return false;
9508     break;
9509   case Intrinsic::ppc_altivec_vcmpgtub_p:
9510     CompareOpc = 518;
9511     isDot = true;
9512     break;
9513   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9514     CompareOpc = 582;
9515     isDot = true;
9516     break;
9517   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9518     CompareOpc = 646;
9519     isDot = true;
9520     break;
9521   case Intrinsic::ppc_altivec_vcmpgtud_p:
9522     if (Subtarget.hasP8Altivec()) {
9523       CompareOpc = 711;
9524       isDot = true;
9525     } else
9526       return false;
9527     break;
9528 
9529   // VSX predicate comparisons use the same infrastructure
9530   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9531   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9532   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9533   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9534   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9535   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9536     if (Subtarget.hasVSX()) {
9537       switch (IntrinsicID) {
9538       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9539         CompareOpc = 99;
9540         break;
9541       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9542         CompareOpc = 115;
9543         break;
9544       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9545         CompareOpc = 107;
9546         break;
9547       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9548         CompareOpc = 67;
9549         break;
9550       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9551         CompareOpc = 83;
9552         break;
9553       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9554         CompareOpc = 75;
9555         break;
9556       }
9557       isDot = true;
9558     } else
9559       return false;
9560     break;
9561 
9562   // Normal Comparisons.
9563   case Intrinsic::ppc_altivec_vcmpbfp:
9564     CompareOpc = 966;
9565     break;
9566   case Intrinsic::ppc_altivec_vcmpeqfp:
9567     CompareOpc = 198;
9568     break;
9569   case Intrinsic::ppc_altivec_vcmpequb:
9570     CompareOpc = 6;
9571     break;
9572   case Intrinsic::ppc_altivec_vcmpequh:
9573     CompareOpc = 70;
9574     break;
9575   case Intrinsic::ppc_altivec_vcmpequw:
9576     CompareOpc = 134;
9577     break;
9578   case Intrinsic::ppc_altivec_vcmpequd:
9579     if (Subtarget.hasP8Altivec())
9580       CompareOpc = 199;
9581     else
9582       return false;
9583     break;
9584   case Intrinsic::ppc_altivec_vcmpneb:
9585   case Intrinsic::ppc_altivec_vcmpneh:
9586   case Intrinsic::ppc_altivec_vcmpnew:
9587   case Intrinsic::ppc_altivec_vcmpnezb:
9588   case Intrinsic::ppc_altivec_vcmpnezh:
9589   case Intrinsic::ppc_altivec_vcmpnezw:
9590     if (Subtarget.hasP9Altivec())
9591       switch (IntrinsicID) {
9592       default:
9593         llvm_unreachable("Unknown comparison intrinsic.");
9594       case Intrinsic::ppc_altivec_vcmpneb:
9595         CompareOpc = 7;
9596         break;
9597       case Intrinsic::ppc_altivec_vcmpneh:
9598         CompareOpc = 71;
9599         break;
9600       case Intrinsic::ppc_altivec_vcmpnew:
9601         CompareOpc = 135;
9602         break;
9603       case Intrinsic::ppc_altivec_vcmpnezb:
9604         CompareOpc = 263;
9605         break;
9606       case Intrinsic::ppc_altivec_vcmpnezh:
9607         CompareOpc = 327;
9608         break;
9609       case Intrinsic::ppc_altivec_vcmpnezw:
9610         CompareOpc = 391;
9611         break;
9612       }
9613     else
9614       return false;
9615     break;
9616   case Intrinsic::ppc_altivec_vcmpgefp:
9617     CompareOpc = 454;
9618     break;
9619   case Intrinsic::ppc_altivec_vcmpgtfp:
9620     CompareOpc = 710;
9621     break;
9622   case Intrinsic::ppc_altivec_vcmpgtsb:
9623     CompareOpc = 774;
9624     break;
9625   case Intrinsic::ppc_altivec_vcmpgtsh:
9626     CompareOpc = 838;
9627     break;
9628   case Intrinsic::ppc_altivec_vcmpgtsw:
9629     CompareOpc = 902;
9630     break;
9631   case Intrinsic::ppc_altivec_vcmpgtsd:
9632     if (Subtarget.hasP8Altivec())
9633       CompareOpc = 967;
9634     else
9635       return false;
9636     break;
9637   case Intrinsic::ppc_altivec_vcmpgtub:
9638     CompareOpc = 518;
9639     break;
9640   case Intrinsic::ppc_altivec_vcmpgtuh:
9641     CompareOpc = 582;
9642     break;
9643   case Intrinsic::ppc_altivec_vcmpgtuw:
9644     CompareOpc = 646;
9645     break;
9646   case Intrinsic::ppc_altivec_vcmpgtud:
9647     if (Subtarget.hasP8Altivec())
9648       CompareOpc = 711;
9649     else
9650       return false;
9651     break;
9652   }
9653   return true;
9654 }
9655 
9656 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9657 /// lower, do it, otherwise return null.
9658 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9659                                                    SelectionDAG &DAG) const {
9660   unsigned IntrinsicID =
9661     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9662 
9663   SDLoc dl(Op);
9664 
9665   if (IntrinsicID == Intrinsic::thread_pointer) {
9666     // Reads the thread pointer register, used for __builtin_thread_pointer.
9667     if (Subtarget.isPPC64())
9668       return DAG.getRegister(PPC::X13, MVT::i64);
9669     return DAG.getRegister(PPC::R2, MVT::i32);
9670   }
9671 
9672   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9673   // opcode number of the comparison.
9674   int CompareOpc;
9675   bool isDot;
9676   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9677     return SDValue();    // Don't custom lower most intrinsics.
9678 
9679   // If this is a non-dot comparison, make the VCMP node and we are done.
9680   if (!isDot) {
9681     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9682                               Op.getOperand(1), Op.getOperand(2),
9683                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9684     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9685   }
9686 
9687   // Create the PPCISD altivec 'dot' comparison node.
9688   SDValue Ops[] = {
9689     Op.getOperand(2),  // LHS
9690     Op.getOperand(3),  // RHS
9691     DAG.getConstant(CompareOpc, dl, MVT::i32)
9692   };
9693   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9694   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9695 
9696   // Now that we have the comparison, emit a copy from the CR to a GPR.
9697   // This is flagged to the above dot comparison.
9698   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9699                                 DAG.getRegister(PPC::CR6, MVT::i32),
9700                                 CompNode.getValue(1));
9701 
9702   // Unpack the result based on how the target uses it.
9703   unsigned BitNo;   // Bit # of CR6.
9704   bool InvertBit;   // Invert result?
9705   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9706   default:  // Can't happen, don't crash on invalid number though.
9707   case 0:   // Return the value of the EQ bit of CR6.
9708     BitNo = 0; InvertBit = false;
9709     break;
9710   case 1:   // Return the inverted value of the EQ bit of CR6.
9711     BitNo = 0; InvertBit = true;
9712     break;
9713   case 2:   // Return the value of the LT bit of CR6.
9714     BitNo = 2; InvertBit = false;
9715     break;
9716   case 3:   // Return the inverted value of the LT bit of CR6.
9717     BitNo = 2; InvertBit = true;
9718     break;
9719   }
9720 
9721   // Shift the bit into the low position.
9722   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9723                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9724   // Isolate the bit.
9725   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9726                       DAG.getConstant(1, dl, MVT::i32));
9727 
9728   // If we are supposed to, toggle the bit.
9729   if (InvertBit)
9730     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9731                         DAG.getConstant(1, dl, MVT::i32));
9732   return Flags;
9733 }
9734 
9735 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9736                                                SelectionDAG &DAG) const {
9737   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9738   // the beginning of the argument list.
9739   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9740   SDLoc DL(Op);
9741   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9742   case Intrinsic::ppc_cfence: {
9743     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9744     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9745     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9746                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9747                                                   Op.getOperand(ArgStart + 1)),
9748                                       Op.getOperand(0)),
9749                    0);
9750   }
9751   default:
9752     break;
9753   }
9754   return SDValue();
9755 }
9756 
9757 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9758   // Check for a DIV with the same operands as this REM.
9759   for (auto UI : Op.getOperand(1)->uses()) {
9760     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9761         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9762       if (UI->getOperand(0) == Op.getOperand(0) &&
9763           UI->getOperand(1) == Op.getOperand(1))
9764         return SDValue();
9765   }
9766   return Op;
9767 }
9768 
9769 // Lower scalar BSWAP64 to xxbrd.
9770 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9771   SDLoc dl(Op);
9772   // MTVSRDD
9773   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9774                    Op.getOperand(0));
9775   // XXBRD
9776   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
9777   // MFVSRD
9778   int VectorIndex = 0;
9779   if (Subtarget.isLittleEndian())
9780     VectorIndex = 1;
9781   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9782                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9783   return Op;
9784 }
9785 
9786 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9787 // compared to a value that is atomically loaded (atomic loads zero-extend).
9788 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9789                                                 SelectionDAG &DAG) const {
9790   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9791          "Expecting an atomic compare-and-swap here.");
9792   SDLoc dl(Op);
9793   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9794   EVT MemVT = AtomicNode->getMemoryVT();
9795   if (MemVT.getSizeInBits() >= 32)
9796     return Op;
9797 
9798   SDValue CmpOp = Op.getOperand(2);
9799   // If this is already correctly zero-extended, leave it alone.
9800   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9801   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9802     return Op;
9803 
9804   // Clear the high bits of the compare operand.
9805   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9806   SDValue NewCmpOp =
9807     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9808                 DAG.getConstant(MaskVal, dl, MVT::i32));
9809 
9810   // Replace the existing compare operand with the properly zero-extended one.
9811   SmallVector<SDValue, 4> Ops;
9812   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9813     Ops.push_back(AtomicNode->getOperand(i));
9814   Ops[2] = NewCmpOp;
9815   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9816   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9817   auto NodeTy =
9818     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9819   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9820 }
9821 
9822 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9823                                                  SelectionDAG &DAG) const {
9824   SDLoc dl(Op);
9825   // Create a stack slot that is 16-byte aligned.
9826   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9827   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9828   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9829   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9830 
9831   // Store the input value into Value#0 of the stack slot.
9832   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9833                                MachinePointerInfo());
9834   // Load it out.
9835   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9836 }
9837 
9838 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9839                                                   SelectionDAG &DAG) const {
9840   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9841          "Should only be called for ISD::INSERT_VECTOR_ELT");
9842 
9843   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9844   // We have legal lowering for constant indices but not for variable ones.
9845   if (!C)
9846     return SDValue();
9847 
9848   EVT VT = Op.getValueType();
9849   SDLoc dl(Op);
9850   SDValue V1 = Op.getOperand(0);
9851   SDValue V2 = Op.getOperand(1);
9852   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9853   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9854     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9855     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9856     unsigned InsertAtElement = C->getZExtValue();
9857     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9858     if (Subtarget.isLittleEndian()) {
9859       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9860     }
9861     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9862                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9863   }
9864   return Op;
9865 }
9866 
9867 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9868                                                    SelectionDAG &DAG) const {
9869   SDLoc dl(Op);
9870   SDNode *N = Op.getNode();
9871 
9872   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9873          "Unknown extract_vector_elt type");
9874 
9875   SDValue Value = N->getOperand(0);
9876 
9877   // The first part of this is like the store lowering except that we don't
9878   // need to track the chain.
9879 
9880   // The values are now known to be -1 (false) or 1 (true). To convert this
9881   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9882   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9883   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9884 
9885   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9886   // understand how to form the extending load.
9887   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9888 
9889   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9890 
9891   // Now convert to an integer and store.
9892   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9893     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9894     Value);
9895 
9896   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9897   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9898   MachinePointerInfo PtrInfo =
9899       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9900   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9901   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9902 
9903   SDValue StoreChain = DAG.getEntryNode();
9904   SDValue Ops[] = {StoreChain,
9905                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9906                    Value, FIdx};
9907   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9908 
9909   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9910     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9911 
9912   // Extract the value requested.
9913   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9914   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9915   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9916 
9917   SDValue IntVal =
9918       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9919 
9920   if (!Subtarget.useCRBits())
9921     return IntVal;
9922 
9923   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9924 }
9925 
9926 /// Lowering for QPX v4i1 loads
9927 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9928                                            SelectionDAG &DAG) const {
9929   SDLoc dl(Op);
9930   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9931   SDValue LoadChain = LN->getChain();
9932   SDValue BasePtr = LN->getBasePtr();
9933 
9934   if (Op.getValueType() == MVT::v4f64 ||
9935       Op.getValueType() == MVT::v4f32) {
9936     EVT MemVT = LN->getMemoryVT();
9937     unsigned Alignment = LN->getAlignment();
9938 
9939     // If this load is properly aligned, then it is legal.
9940     if (Alignment >= MemVT.getStoreSize())
9941       return Op;
9942 
9943     EVT ScalarVT = Op.getValueType().getScalarType(),
9944         ScalarMemVT = MemVT.getScalarType();
9945     unsigned Stride = ScalarMemVT.getStoreSize();
9946 
9947     SDValue Vals[4], LoadChains[4];
9948     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9949       SDValue Load;
9950       if (ScalarVT != ScalarMemVT)
9951         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9952                               BasePtr,
9953                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9954                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9955                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9956       else
9957         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9958                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9959                            MinAlign(Alignment, Idx * Stride),
9960                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9961 
9962       if (Idx == 0 && LN->isIndexed()) {
9963         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9964                "Unknown addressing mode on vector load");
9965         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9966                                   LN->getAddressingMode());
9967       }
9968 
9969       Vals[Idx] = Load;
9970       LoadChains[Idx] = Load.getValue(1);
9971 
9972       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9973                             DAG.getConstant(Stride, dl,
9974                                             BasePtr.getValueType()));
9975     }
9976 
9977     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9978     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9979 
9980     if (LN->isIndexed()) {
9981       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9982       return DAG.getMergeValues(RetOps, dl);
9983     }
9984 
9985     SDValue RetOps[] = { Value, TF };
9986     return DAG.getMergeValues(RetOps, dl);
9987   }
9988 
9989   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9990   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9991 
9992   // To lower v4i1 from a byte array, we load the byte elements of the
9993   // vector and then reuse the BUILD_VECTOR logic.
9994 
9995   SDValue VectElmts[4], VectElmtChains[4];
9996   for (unsigned i = 0; i < 4; ++i) {
9997     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9998     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9999 
10000     VectElmts[i] = DAG.getExtLoad(
10001         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10002         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10003         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10004     VectElmtChains[i] = VectElmts[i].getValue(1);
10005   }
10006 
10007   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10008   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10009 
10010   SDValue RVals[] = { Value, LoadChain };
10011   return DAG.getMergeValues(RVals, dl);
10012 }
10013 
10014 /// Lowering for QPX v4i1 stores
10015 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10016                                             SelectionDAG &DAG) const {
10017   SDLoc dl(Op);
10018   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10019   SDValue StoreChain = SN->getChain();
10020   SDValue BasePtr = SN->getBasePtr();
10021   SDValue Value = SN->getValue();
10022 
10023   if (Value.getValueType() == MVT::v4f64 ||
10024       Value.getValueType() == MVT::v4f32) {
10025     EVT MemVT = SN->getMemoryVT();
10026     unsigned Alignment = SN->getAlignment();
10027 
10028     // If this store is properly aligned, then it is legal.
10029     if (Alignment >= MemVT.getStoreSize())
10030       return Op;
10031 
10032     EVT ScalarVT = Value.getValueType().getScalarType(),
10033         ScalarMemVT = MemVT.getScalarType();
10034     unsigned Stride = ScalarMemVT.getStoreSize();
10035 
10036     SDValue Stores[4];
10037     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10038       SDValue Ex = DAG.getNode(
10039           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10040           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
10041       SDValue Store;
10042       if (ScalarVT != ScalarMemVT)
10043         Store =
10044             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10045                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10046                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10047                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10048       else
10049         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10050                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10051                              MinAlign(Alignment, Idx * Stride),
10052                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10053 
10054       if (Idx == 0 && SN->isIndexed()) {
10055         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10056                "Unknown addressing mode on vector store");
10057         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10058                                     SN->getAddressingMode());
10059       }
10060 
10061       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10062                             DAG.getConstant(Stride, dl,
10063                                             BasePtr.getValueType()));
10064       Stores[Idx] = Store;
10065     }
10066 
10067     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10068 
10069     if (SN->isIndexed()) {
10070       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10071       return DAG.getMergeValues(RetOps, dl);
10072     }
10073 
10074     return TF;
10075   }
10076 
10077   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10078   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10079 
10080   // The values are now known to be -1 (false) or 1 (true). To convert this
10081   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10082   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10083   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10084 
10085   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10086   // understand how to form the extending load.
10087   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10088 
10089   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10090 
10091   // Now convert to an integer and store.
10092   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10093     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10094     Value);
10095 
10096   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10097   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10098   MachinePointerInfo PtrInfo =
10099       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10100   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10101   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10102 
10103   SDValue Ops[] = {StoreChain,
10104                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10105                    Value, FIdx};
10106   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10107 
10108   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10109     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10110 
10111   // Move data into the byte array.
10112   SDValue Loads[4], LoadChains[4];
10113   for (unsigned i = 0; i < 4; ++i) {
10114     unsigned Offset = 4*i;
10115     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10116     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10117 
10118     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10119                            PtrInfo.getWithOffset(Offset));
10120     LoadChains[i] = Loads[i].getValue(1);
10121   }
10122 
10123   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10124 
10125   SDValue Stores[4];
10126   for (unsigned i = 0; i < 4; ++i) {
10127     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10128     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10129 
10130     Stores[i] = DAG.getTruncStore(
10131         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10132         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10133         SN->getAAInfo());
10134   }
10135 
10136   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10137 
10138   return StoreChain;
10139 }
10140 
10141 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10142   SDLoc dl(Op);
10143   if (Op.getValueType() == MVT::v4i32) {
10144     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10145 
10146     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10147     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10148 
10149     SDValue RHSSwap =   // = vrlw RHS, 16
10150       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10151 
10152     // Shrinkify inputs to v8i16.
10153     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10154     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10155     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10156 
10157     // Low parts multiplied together, generating 32-bit results (we ignore the
10158     // top parts).
10159     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10160                                         LHS, RHS, DAG, dl, MVT::v4i32);
10161 
10162     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10163                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10164     // Shift the high parts up 16 bits.
10165     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10166                               Neg16, DAG, dl);
10167     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10168   } else if (Op.getValueType() == MVT::v8i16) {
10169     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10170 
10171     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
10172 
10173     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
10174                             LHS, RHS, Zero, DAG, dl);
10175   } else if (Op.getValueType() == MVT::v16i8) {
10176     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10177     bool isLittleEndian = Subtarget.isLittleEndian();
10178 
10179     // Multiply the even 8-bit parts, producing 16-bit sums.
10180     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10181                                            LHS, RHS, DAG, dl, MVT::v8i16);
10182     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10183 
10184     // Multiply the odd 8-bit parts, producing 16-bit sums.
10185     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10186                                           LHS, RHS, DAG, dl, MVT::v8i16);
10187     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10188 
10189     // Merge the results together.  Because vmuleub and vmuloub are
10190     // instructions with a big-endian bias, we must reverse the
10191     // element numbering and reverse the meaning of "odd" and "even"
10192     // when generating little endian code.
10193     int Ops[16];
10194     for (unsigned i = 0; i != 8; ++i) {
10195       if (isLittleEndian) {
10196         Ops[i*2  ] = 2*i;
10197         Ops[i*2+1] = 2*i+16;
10198       } else {
10199         Ops[i*2  ] = 2*i+1;
10200         Ops[i*2+1] = 2*i+1+16;
10201       }
10202     }
10203     if (isLittleEndian)
10204       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10205     else
10206       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10207   } else {
10208     llvm_unreachable("Unknown mul to lower!");
10209   }
10210 }
10211 
10212 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10213 
10214   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10215 
10216   EVT VT = Op.getValueType();
10217   assert(VT.isVector() &&
10218          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10219   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10220           VT == MVT::v16i8) &&
10221          "Unexpected vector element type!");
10222   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10223          "Current subtarget doesn't support smax v2i64!");
10224 
10225   // For vector abs, it can be lowered to:
10226   // abs x
10227   // ==>
10228   // y = -x
10229   // smax(x, y)
10230 
10231   SDLoc dl(Op);
10232   SDValue X = Op.getOperand(0);
10233   SDValue Zero = DAG.getConstant(0, dl, VT);
10234   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10235 
10236   // SMAX patch https://reviews.llvm.org/D47332
10237   // hasn't landed yet, so use intrinsic first here.
10238   // TODO: Should use SMAX directly once SMAX patch landed
10239   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10240   if (VT == MVT::v2i64)
10241     BifID = Intrinsic::ppc_altivec_vmaxsd;
10242   else if (VT == MVT::v8i16)
10243     BifID = Intrinsic::ppc_altivec_vmaxsh;
10244   else if (VT == MVT::v16i8)
10245     BifID = Intrinsic::ppc_altivec_vmaxsb;
10246 
10247   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10248 }
10249 
10250 // Custom lowering for fpext vf32 to v2f64
10251 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10252 
10253   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10254          "Should only be called for ISD::FP_EXTEND");
10255 
10256   // We only want to custom lower an extend from v2f32 to v2f64.
10257   if (Op.getValueType() != MVT::v2f64 ||
10258       Op.getOperand(0).getValueType() != MVT::v2f32)
10259     return SDValue();
10260 
10261   SDLoc dl(Op);
10262   SDValue Op0 = Op.getOperand(0);
10263 
10264   switch (Op0.getOpcode()) {
10265   default:
10266     return SDValue();
10267   case ISD::EXTRACT_SUBVECTOR: {
10268     assert(Op0.getNumOperands() == 2 &&
10269            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10270            "Node should have 2 operands with second one being a constant!");
10271 
10272     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10273       return SDValue();
10274 
10275     // Custom lower is only done for high or low doubleword.
10276     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10277     if (Idx % 2 != 0)
10278       return SDValue();
10279 
10280     // Since input is v4f32, at this point Idx is either 0 or 2.
10281     // Shift to get the doubleword position we want.
10282     int DWord = Idx >> 1;
10283 
10284     // High and low word positions are different on little endian.
10285     if (Subtarget.isLittleEndian())
10286       DWord ^= 0x1;
10287 
10288     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10289                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10290   }
10291   case ISD::FADD:
10292   case ISD::FMUL:
10293   case ISD::FSUB: {
10294     SDValue NewLoad[2];
10295     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10296       // Ensure both input are loads.
10297       SDValue LdOp = Op0.getOperand(i);
10298       if (LdOp.getOpcode() != ISD::LOAD)
10299         return SDValue();
10300       // Generate new load node.
10301       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10302       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10303       NewLoad[i] = DAG.getMemIntrinsicNode(
10304           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10305           LD->getMemoryVT(), LD->getMemOperand());
10306     }
10307     SDValue NewOp =
10308         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10309                     NewLoad[1], Op0.getNode()->getFlags());
10310     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10311                        DAG.getConstant(0, dl, MVT::i32));
10312   }
10313   case ISD::LOAD: {
10314     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10315     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10316     SDValue NewLd = DAG.getMemIntrinsicNode(
10317         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10318         LD->getMemoryVT(), LD->getMemOperand());
10319     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10320                        DAG.getConstant(0, dl, MVT::i32));
10321   }
10322   }
10323   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10324 }
10325 
10326 /// LowerOperation - Provide custom lowering hooks for some operations.
10327 ///
10328 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10329   switch (Op.getOpcode()) {
10330   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10331   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10332   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10333   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10334   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10335   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10336   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10337   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10338   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10339 
10340   // Variable argument lowering.
10341   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10342   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10343   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10344 
10345   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10346   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10347   case ISD::GET_DYNAMIC_AREA_OFFSET:
10348     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10349 
10350   // Exception handling lowering.
10351   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10352   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10353   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10354 
10355   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10356   case ISD::STORE:              return LowerSTORE(Op, DAG);
10357   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10358   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10359   case ISD::FP_TO_UINT:
10360   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10361   case ISD::UINT_TO_FP:
10362   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10363   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10364 
10365   // Lower 64-bit shifts.
10366   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10367   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10368   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10369 
10370   // Vector-related lowering.
10371   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10372   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10373   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10374   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10375   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10376   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10377   case ISD::MUL:                return LowerMUL(Op, DAG);
10378   case ISD::ABS:                return LowerABS(Op, DAG);
10379   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10380 
10381   // For counter-based loop handling.
10382   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10383 
10384   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10385 
10386   // Frame & Return address.
10387   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10388   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10389 
10390   case ISD::INTRINSIC_VOID:
10391     return LowerINTRINSIC_VOID(Op, DAG);
10392   case ISD::SREM:
10393   case ISD::UREM:
10394     return LowerREM(Op, DAG);
10395   case ISD::BSWAP:
10396     return LowerBSWAP(Op, DAG);
10397   case ISD::ATOMIC_CMP_SWAP:
10398     return LowerATOMIC_CMP_SWAP(Op, DAG);
10399   }
10400 }
10401 
10402 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10403                                            SmallVectorImpl<SDValue>&Results,
10404                                            SelectionDAG &DAG) const {
10405   SDLoc dl(N);
10406   switch (N->getOpcode()) {
10407   default:
10408     llvm_unreachable("Do not know how to custom type legalize this operation!");
10409   case ISD::READCYCLECOUNTER: {
10410     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10411     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10412 
10413     Results.push_back(RTB);
10414     Results.push_back(RTB.getValue(1));
10415     Results.push_back(RTB.getValue(2));
10416     break;
10417   }
10418   case ISD::INTRINSIC_W_CHAIN: {
10419     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10420         Intrinsic::loop_decrement)
10421       break;
10422 
10423     assert(N->getValueType(0) == MVT::i1 &&
10424            "Unexpected result type for CTR decrement intrinsic");
10425     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10426                                  N->getValueType(0));
10427     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10428     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10429                                  N->getOperand(1));
10430 
10431     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10432     Results.push_back(NewInt.getValue(1));
10433     break;
10434   }
10435   case ISD::VAARG: {
10436     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10437       return;
10438 
10439     EVT VT = N->getValueType(0);
10440 
10441     if (VT == MVT::i64) {
10442       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10443 
10444       Results.push_back(NewNode);
10445       Results.push_back(NewNode.getValue(1));
10446     }
10447     return;
10448   }
10449   case ISD::FP_TO_SINT:
10450   case ISD::FP_TO_UINT:
10451     // LowerFP_TO_INT() can only handle f32 and f64.
10452     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10453       return;
10454     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10455     return;
10456   case ISD::TRUNCATE: {
10457     EVT TrgVT = N->getValueType(0);
10458     EVT OpVT = N->getOperand(0).getValueType();
10459     if (TrgVT.isVector() &&
10460         isOperationCustom(N->getOpcode(), TrgVT) &&
10461         OpVT.getSizeInBits() <= 128 &&
10462         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10463       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10464     return;
10465   }
10466   case ISD::BITCAST:
10467     // Don't handle bitcast here.
10468     return;
10469   }
10470 }
10471 
10472 //===----------------------------------------------------------------------===//
10473 //  Other Lowering Code
10474 //===----------------------------------------------------------------------===//
10475 
10476 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10477   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10478   Function *Func = Intrinsic::getDeclaration(M, Id);
10479   return Builder.CreateCall(Func, {});
10480 }
10481 
10482 // The mappings for emitLeading/TrailingFence is taken from
10483 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10484 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10485                                                  Instruction *Inst,
10486                                                  AtomicOrdering Ord) const {
10487   if (Ord == AtomicOrdering::SequentiallyConsistent)
10488     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10489   if (isReleaseOrStronger(Ord))
10490     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10491   return nullptr;
10492 }
10493 
10494 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10495                                                   Instruction *Inst,
10496                                                   AtomicOrdering Ord) const {
10497   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10498     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10499     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10500     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10501     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10502       return Builder.CreateCall(
10503           Intrinsic::getDeclaration(
10504               Builder.GetInsertBlock()->getParent()->getParent(),
10505               Intrinsic::ppc_cfence, {Inst->getType()}),
10506           {Inst});
10507     // FIXME: Can use isync for rmw operation.
10508     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10509   }
10510   return nullptr;
10511 }
10512 
10513 MachineBasicBlock *
10514 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10515                                     unsigned AtomicSize,
10516                                     unsigned BinOpcode,
10517                                     unsigned CmpOpcode,
10518                                     unsigned CmpPred) const {
10519   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10520   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10521 
10522   auto LoadMnemonic = PPC::LDARX;
10523   auto StoreMnemonic = PPC::STDCX;
10524   switch (AtomicSize) {
10525   default:
10526     llvm_unreachable("Unexpected size of atomic entity");
10527   case 1:
10528     LoadMnemonic = PPC::LBARX;
10529     StoreMnemonic = PPC::STBCX;
10530     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10531     break;
10532   case 2:
10533     LoadMnemonic = PPC::LHARX;
10534     StoreMnemonic = PPC::STHCX;
10535     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10536     break;
10537   case 4:
10538     LoadMnemonic = PPC::LWARX;
10539     StoreMnemonic = PPC::STWCX;
10540     break;
10541   case 8:
10542     LoadMnemonic = PPC::LDARX;
10543     StoreMnemonic = PPC::STDCX;
10544     break;
10545   }
10546 
10547   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10548   MachineFunction *F = BB->getParent();
10549   MachineFunction::iterator It = ++BB->getIterator();
10550 
10551   Register dest = MI.getOperand(0).getReg();
10552   Register ptrA = MI.getOperand(1).getReg();
10553   Register ptrB = MI.getOperand(2).getReg();
10554   Register incr = MI.getOperand(3).getReg();
10555   DebugLoc dl = MI.getDebugLoc();
10556 
10557   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10558   MachineBasicBlock *loop2MBB =
10559     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10560   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10561   F->insert(It, loopMBB);
10562   if (CmpOpcode)
10563     F->insert(It, loop2MBB);
10564   F->insert(It, exitMBB);
10565   exitMBB->splice(exitMBB->begin(), BB,
10566                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10567   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10568 
10569   MachineRegisterInfo &RegInfo = F->getRegInfo();
10570   Register TmpReg = (!BinOpcode) ? incr :
10571     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10572                                            : &PPC::GPRCRegClass);
10573 
10574   //  thisMBB:
10575   //   ...
10576   //   fallthrough --> loopMBB
10577   BB->addSuccessor(loopMBB);
10578 
10579   //  loopMBB:
10580   //   l[wd]arx dest, ptr
10581   //   add r0, dest, incr
10582   //   st[wd]cx. r0, ptr
10583   //   bne- loopMBB
10584   //   fallthrough --> exitMBB
10585 
10586   // For max/min...
10587   //  loopMBB:
10588   //   l[wd]arx dest, ptr
10589   //   cmpl?[wd] incr, dest
10590   //   bgt exitMBB
10591   //  loop2MBB:
10592   //   st[wd]cx. dest, ptr
10593   //   bne- loopMBB
10594   //   fallthrough --> exitMBB
10595 
10596   BB = loopMBB;
10597   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10598     .addReg(ptrA).addReg(ptrB);
10599   if (BinOpcode)
10600     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10601   if (CmpOpcode) {
10602     // Signed comparisons of byte or halfword values must be sign-extended.
10603     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10604       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10605       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10606               ExtReg).addReg(dest);
10607       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10608         .addReg(incr).addReg(ExtReg);
10609     } else
10610       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10611         .addReg(incr).addReg(dest);
10612 
10613     BuildMI(BB, dl, TII->get(PPC::BCC))
10614       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10615     BB->addSuccessor(loop2MBB);
10616     BB->addSuccessor(exitMBB);
10617     BB = loop2MBB;
10618   }
10619   BuildMI(BB, dl, TII->get(StoreMnemonic))
10620     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10621   BuildMI(BB, dl, TII->get(PPC::BCC))
10622     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10623   BB->addSuccessor(loopMBB);
10624   BB->addSuccessor(exitMBB);
10625 
10626   //  exitMBB:
10627   //   ...
10628   BB = exitMBB;
10629   return BB;
10630 }
10631 
10632 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10633     MachineInstr &MI, MachineBasicBlock *BB,
10634     bool is8bit, // operation
10635     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10636   // If we support part-word atomic mnemonics, just use them
10637   if (Subtarget.hasPartwordAtomics())
10638     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10639                             CmpPred);
10640 
10641   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10642   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10643   // In 64 bit mode we have to use 64 bits for addresses, even though the
10644   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10645   // registers without caring whether they're 32 or 64, but here we're
10646   // doing actual arithmetic on the addresses.
10647   bool is64bit = Subtarget.isPPC64();
10648   bool isLittleEndian = Subtarget.isLittleEndian();
10649   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10650 
10651   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10652   MachineFunction *F = BB->getParent();
10653   MachineFunction::iterator It = ++BB->getIterator();
10654 
10655   Register dest = MI.getOperand(0).getReg();
10656   Register ptrA = MI.getOperand(1).getReg();
10657   Register ptrB = MI.getOperand(2).getReg();
10658   Register incr = MI.getOperand(3).getReg();
10659   DebugLoc dl = MI.getDebugLoc();
10660 
10661   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10662   MachineBasicBlock *loop2MBB =
10663       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10664   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10665   F->insert(It, loopMBB);
10666   if (CmpOpcode)
10667     F->insert(It, loop2MBB);
10668   F->insert(It, exitMBB);
10669   exitMBB->splice(exitMBB->begin(), BB,
10670                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10671   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10672 
10673   MachineRegisterInfo &RegInfo = F->getRegInfo();
10674   const TargetRegisterClass *RC =
10675       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10676   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10677 
10678   Register PtrReg = RegInfo.createVirtualRegister(RC);
10679   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10680   Register ShiftReg =
10681       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10682   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10683   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10684   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10685   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10686   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10687   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10688   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10689   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10690   Register Ptr1Reg;
10691   Register TmpReg =
10692       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10693 
10694   //  thisMBB:
10695   //   ...
10696   //   fallthrough --> loopMBB
10697   BB->addSuccessor(loopMBB);
10698 
10699   // The 4-byte load must be aligned, while a char or short may be
10700   // anywhere in the word.  Hence all this nasty bookkeeping code.
10701   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10702   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10703   //   xori shift, shift1, 24 [16]
10704   //   rlwinm ptr, ptr1, 0, 0, 29
10705   //   slw incr2, incr, shift
10706   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10707   //   slw mask, mask2, shift
10708   //  loopMBB:
10709   //   lwarx tmpDest, ptr
10710   //   add tmp, tmpDest, incr2
10711   //   andc tmp2, tmpDest, mask
10712   //   and tmp3, tmp, mask
10713   //   or tmp4, tmp3, tmp2
10714   //   stwcx. tmp4, ptr
10715   //   bne- loopMBB
10716   //   fallthrough --> exitMBB
10717   //   srw dest, tmpDest, shift
10718   if (ptrA != ZeroReg) {
10719     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10720     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10721         .addReg(ptrA)
10722         .addReg(ptrB);
10723   } else {
10724     Ptr1Reg = ptrB;
10725   }
10726   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10727   // mode.
10728   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10729       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10730       .addImm(3)
10731       .addImm(27)
10732       .addImm(is8bit ? 28 : 27);
10733   if (!isLittleEndian)
10734     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10735         .addReg(Shift1Reg)
10736         .addImm(is8bit ? 24 : 16);
10737   if (is64bit)
10738     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10739         .addReg(Ptr1Reg)
10740         .addImm(0)
10741         .addImm(61);
10742   else
10743     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10744         .addReg(Ptr1Reg)
10745         .addImm(0)
10746         .addImm(0)
10747         .addImm(29);
10748   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10749   if (is8bit)
10750     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10751   else {
10752     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10753     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10754         .addReg(Mask3Reg)
10755         .addImm(65535);
10756   }
10757   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10758       .addReg(Mask2Reg)
10759       .addReg(ShiftReg);
10760 
10761   BB = loopMBB;
10762   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10763       .addReg(ZeroReg)
10764       .addReg(PtrReg);
10765   if (BinOpcode)
10766     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10767         .addReg(Incr2Reg)
10768         .addReg(TmpDestReg);
10769   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10770       .addReg(TmpDestReg)
10771       .addReg(MaskReg);
10772   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10773   if (CmpOpcode) {
10774     // For unsigned comparisons, we can directly compare the shifted values.
10775     // For signed comparisons we shift and sign extend.
10776     Register SReg = RegInfo.createVirtualRegister(GPRC);
10777     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10778         .addReg(TmpDestReg)
10779         .addReg(MaskReg);
10780     unsigned ValueReg = SReg;
10781     unsigned CmpReg = Incr2Reg;
10782     if (CmpOpcode == PPC::CMPW) {
10783       ValueReg = RegInfo.createVirtualRegister(GPRC);
10784       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10785           .addReg(SReg)
10786           .addReg(ShiftReg);
10787       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10788       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10789           .addReg(ValueReg);
10790       ValueReg = ValueSReg;
10791       CmpReg = incr;
10792     }
10793     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10794         .addReg(CmpReg)
10795         .addReg(ValueReg);
10796     BuildMI(BB, dl, TII->get(PPC::BCC))
10797         .addImm(CmpPred)
10798         .addReg(PPC::CR0)
10799         .addMBB(exitMBB);
10800     BB->addSuccessor(loop2MBB);
10801     BB->addSuccessor(exitMBB);
10802     BB = loop2MBB;
10803   }
10804   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10805   BuildMI(BB, dl, TII->get(PPC::STWCX))
10806       .addReg(Tmp4Reg)
10807       .addReg(ZeroReg)
10808       .addReg(PtrReg);
10809   BuildMI(BB, dl, TII->get(PPC::BCC))
10810       .addImm(PPC::PRED_NE)
10811       .addReg(PPC::CR0)
10812       .addMBB(loopMBB);
10813   BB->addSuccessor(loopMBB);
10814   BB->addSuccessor(exitMBB);
10815 
10816   //  exitMBB:
10817   //   ...
10818   BB = exitMBB;
10819   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10820       .addReg(TmpDestReg)
10821       .addReg(ShiftReg);
10822   return BB;
10823 }
10824 
10825 llvm::MachineBasicBlock *
10826 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10827                                     MachineBasicBlock *MBB) const {
10828   DebugLoc DL = MI.getDebugLoc();
10829   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10830   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10831 
10832   MachineFunction *MF = MBB->getParent();
10833   MachineRegisterInfo &MRI = MF->getRegInfo();
10834 
10835   const BasicBlock *BB = MBB->getBasicBlock();
10836   MachineFunction::iterator I = ++MBB->getIterator();
10837 
10838   Register DstReg = MI.getOperand(0).getReg();
10839   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10840   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10841   Register mainDstReg = MRI.createVirtualRegister(RC);
10842   Register restoreDstReg = MRI.createVirtualRegister(RC);
10843 
10844   MVT PVT = getPointerTy(MF->getDataLayout());
10845   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10846          "Invalid Pointer Size!");
10847   // For v = setjmp(buf), we generate
10848   //
10849   // thisMBB:
10850   //  SjLjSetup mainMBB
10851   //  bl mainMBB
10852   //  v_restore = 1
10853   //  b sinkMBB
10854   //
10855   // mainMBB:
10856   //  buf[LabelOffset] = LR
10857   //  v_main = 0
10858   //
10859   // sinkMBB:
10860   //  v = phi(main, restore)
10861   //
10862 
10863   MachineBasicBlock *thisMBB = MBB;
10864   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10865   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10866   MF->insert(I, mainMBB);
10867   MF->insert(I, sinkMBB);
10868 
10869   MachineInstrBuilder MIB;
10870 
10871   // Transfer the remainder of BB and its successor edges to sinkMBB.
10872   sinkMBB->splice(sinkMBB->begin(), MBB,
10873                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10874   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10875 
10876   // Note that the structure of the jmp_buf used here is not compatible
10877   // with that used by libc, and is not designed to be. Specifically, it
10878   // stores only those 'reserved' registers that LLVM does not otherwise
10879   // understand how to spill. Also, by convention, by the time this
10880   // intrinsic is called, Clang has already stored the frame address in the
10881   // first slot of the buffer and stack address in the third. Following the
10882   // X86 target code, we'll store the jump address in the second slot. We also
10883   // need to save the TOC pointer (R2) to handle jumps between shared
10884   // libraries, and that will be stored in the fourth slot. The thread
10885   // identifier (R13) is not affected.
10886 
10887   // thisMBB:
10888   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10889   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10890   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10891 
10892   // Prepare IP either in reg.
10893   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10894   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10895   Register BufReg = MI.getOperand(1).getReg();
10896 
10897   if (Subtarget.is64BitELFABI()) {
10898     setUsesTOCBasePtr(*MBB->getParent());
10899     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10900               .addReg(PPC::X2)
10901               .addImm(TOCOffset)
10902               .addReg(BufReg)
10903               .cloneMemRefs(MI);
10904   }
10905 
10906   // Naked functions never have a base pointer, and so we use r1. For all
10907   // other functions, this decision must be delayed until during PEI.
10908   unsigned BaseReg;
10909   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10910     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10911   else
10912     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10913 
10914   MIB = BuildMI(*thisMBB, MI, DL,
10915                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10916             .addReg(BaseReg)
10917             .addImm(BPOffset)
10918             .addReg(BufReg)
10919             .cloneMemRefs(MI);
10920 
10921   // Setup
10922   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10923   MIB.addRegMask(TRI->getNoPreservedMask());
10924 
10925   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10926 
10927   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10928           .addMBB(mainMBB);
10929   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10930 
10931   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10932   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10933 
10934   // mainMBB:
10935   //  mainDstReg = 0
10936   MIB =
10937       BuildMI(mainMBB, DL,
10938               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10939 
10940   // Store IP
10941   if (Subtarget.isPPC64()) {
10942     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10943             .addReg(LabelReg)
10944             .addImm(LabelOffset)
10945             .addReg(BufReg);
10946   } else {
10947     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10948             .addReg(LabelReg)
10949             .addImm(LabelOffset)
10950             .addReg(BufReg);
10951   }
10952   MIB.cloneMemRefs(MI);
10953 
10954   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10955   mainMBB->addSuccessor(sinkMBB);
10956 
10957   // sinkMBB:
10958   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10959           TII->get(PPC::PHI), DstReg)
10960     .addReg(mainDstReg).addMBB(mainMBB)
10961     .addReg(restoreDstReg).addMBB(thisMBB);
10962 
10963   MI.eraseFromParent();
10964   return sinkMBB;
10965 }
10966 
10967 MachineBasicBlock *
10968 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10969                                      MachineBasicBlock *MBB) const {
10970   DebugLoc DL = MI.getDebugLoc();
10971   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10972 
10973   MachineFunction *MF = MBB->getParent();
10974   MachineRegisterInfo &MRI = MF->getRegInfo();
10975 
10976   MVT PVT = getPointerTy(MF->getDataLayout());
10977   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10978          "Invalid Pointer Size!");
10979 
10980   const TargetRegisterClass *RC =
10981     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10982   Register Tmp = MRI.createVirtualRegister(RC);
10983   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10984   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10985   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10986   unsigned BP =
10987       (PVT == MVT::i64)
10988           ? PPC::X30
10989           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10990                                                               : PPC::R30);
10991 
10992   MachineInstrBuilder MIB;
10993 
10994   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10995   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10996   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10997   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10998 
10999   Register BufReg = MI.getOperand(0).getReg();
11000 
11001   // Reload FP (the jumped-to function may not have had a
11002   // frame pointer, and if so, then its r31 will be restored
11003   // as necessary).
11004   if (PVT == MVT::i64) {
11005     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11006             .addImm(0)
11007             .addReg(BufReg);
11008   } else {
11009     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11010             .addImm(0)
11011             .addReg(BufReg);
11012   }
11013   MIB.cloneMemRefs(MI);
11014 
11015   // Reload IP
11016   if (PVT == MVT::i64) {
11017     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11018             .addImm(LabelOffset)
11019             .addReg(BufReg);
11020   } else {
11021     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11022             .addImm(LabelOffset)
11023             .addReg(BufReg);
11024   }
11025   MIB.cloneMemRefs(MI);
11026 
11027   // Reload SP
11028   if (PVT == MVT::i64) {
11029     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11030             .addImm(SPOffset)
11031             .addReg(BufReg);
11032   } else {
11033     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11034             .addImm(SPOffset)
11035             .addReg(BufReg);
11036   }
11037   MIB.cloneMemRefs(MI);
11038 
11039   // Reload BP
11040   if (PVT == MVT::i64) {
11041     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11042             .addImm(BPOffset)
11043             .addReg(BufReg);
11044   } else {
11045     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11046             .addImm(BPOffset)
11047             .addReg(BufReg);
11048   }
11049   MIB.cloneMemRefs(MI);
11050 
11051   // Reload TOC
11052   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11053     setUsesTOCBasePtr(*MBB->getParent());
11054     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11055               .addImm(TOCOffset)
11056               .addReg(BufReg)
11057               .cloneMemRefs(MI);
11058   }
11059 
11060   // Jump
11061   BuildMI(*MBB, MI, DL,
11062           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11063   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11064 
11065   MI.eraseFromParent();
11066   return MBB;
11067 }
11068 
11069 MachineBasicBlock *
11070 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11071                                                MachineBasicBlock *BB) const {
11072   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11073       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11074     if (Subtarget.is64BitELFABI() &&
11075         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11076       // Call lowering should have added an r2 operand to indicate a dependence
11077       // on the TOC base pointer value. It can't however, because there is no
11078       // way to mark the dependence as implicit there, and so the stackmap code
11079       // will confuse it with a regular operand. Instead, add the dependence
11080       // here.
11081       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11082     }
11083 
11084     return emitPatchPoint(MI, BB);
11085   }
11086 
11087   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11088       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11089     return emitEHSjLjSetJmp(MI, BB);
11090   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11091              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11092     return emitEHSjLjLongJmp(MI, BB);
11093   }
11094 
11095   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11096 
11097   // To "insert" these instructions we actually have to insert their
11098   // control-flow patterns.
11099   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11100   MachineFunction::iterator It = ++BB->getIterator();
11101 
11102   MachineFunction *F = BB->getParent();
11103 
11104   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11105       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11106       MI.getOpcode() == PPC::SELECT_I8) {
11107     SmallVector<MachineOperand, 2> Cond;
11108     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11109         MI.getOpcode() == PPC::SELECT_CC_I8)
11110       Cond.push_back(MI.getOperand(4));
11111     else
11112       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11113     Cond.push_back(MI.getOperand(1));
11114 
11115     DebugLoc dl = MI.getDebugLoc();
11116     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11117                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11118   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11119              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11120              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11121              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11122              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11123              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11124              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11125              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11126              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11127              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11128              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11129              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11130              MI.getOpcode() == PPC::SELECT_F4 ||
11131              MI.getOpcode() == PPC::SELECT_F8 ||
11132              MI.getOpcode() == PPC::SELECT_F16 ||
11133              MI.getOpcode() == PPC::SELECT_QFRC ||
11134              MI.getOpcode() == PPC::SELECT_QSRC ||
11135              MI.getOpcode() == PPC::SELECT_QBRC ||
11136              MI.getOpcode() == PPC::SELECT_SPE ||
11137              MI.getOpcode() == PPC::SELECT_SPE4 ||
11138              MI.getOpcode() == PPC::SELECT_VRRC ||
11139              MI.getOpcode() == PPC::SELECT_VSFRC ||
11140              MI.getOpcode() == PPC::SELECT_VSSRC ||
11141              MI.getOpcode() == PPC::SELECT_VSRC) {
11142     // The incoming instruction knows the destination vreg to set, the
11143     // condition code register to branch on, the true/false values to
11144     // select between, and a branch opcode to use.
11145 
11146     //  thisMBB:
11147     //  ...
11148     //   TrueVal = ...
11149     //   cmpTY ccX, r1, r2
11150     //   bCC copy1MBB
11151     //   fallthrough --> copy0MBB
11152     MachineBasicBlock *thisMBB = BB;
11153     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11154     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11155     DebugLoc dl = MI.getDebugLoc();
11156     F->insert(It, copy0MBB);
11157     F->insert(It, sinkMBB);
11158 
11159     // Transfer the remainder of BB and its successor edges to sinkMBB.
11160     sinkMBB->splice(sinkMBB->begin(), BB,
11161                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11162     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11163 
11164     // Next, add the true and fallthrough blocks as its successors.
11165     BB->addSuccessor(copy0MBB);
11166     BB->addSuccessor(sinkMBB);
11167 
11168     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11169         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11170         MI.getOpcode() == PPC::SELECT_F16 ||
11171         MI.getOpcode() == PPC::SELECT_SPE4 ||
11172         MI.getOpcode() == PPC::SELECT_SPE ||
11173         MI.getOpcode() == PPC::SELECT_QFRC ||
11174         MI.getOpcode() == PPC::SELECT_QSRC ||
11175         MI.getOpcode() == PPC::SELECT_QBRC ||
11176         MI.getOpcode() == PPC::SELECT_VRRC ||
11177         MI.getOpcode() == PPC::SELECT_VSFRC ||
11178         MI.getOpcode() == PPC::SELECT_VSSRC ||
11179         MI.getOpcode() == PPC::SELECT_VSRC) {
11180       BuildMI(BB, dl, TII->get(PPC::BC))
11181           .addReg(MI.getOperand(1).getReg())
11182           .addMBB(sinkMBB);
11183     } else {
11184       unsigned SelectPred = MI.getOperand(4).getImm();
11185       BuildMI(BB, dl, TII->get(PPC::BCC))
11186           .addImm(SelectPred)
11187           .addReg(MI.getOperand(1).getReg())
11188           .addMBB(sinkMBB);
11189     }
11190 
11191     //  copy0MBB:
11192     //   %FalseValue = ...
11193     //   # fallthrough to sinkMBB
11194     BB = copy0MBB;
11195 
11196     // Update machine-CFG edges
11197     BB->addSuccessor(sinkMBB);
11198 
11199     //  sinkMBB:
11200     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11201     //  ...
11202     BB = sinkMBB;
11203     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11204         .addReg(MI.getOperand(3).getReg())
11205         .addMBB(copy0MBB)
11206         .addReg(MI.getOperand(2).getReg())
11207         .addMBB(thisMBB);
11208   } else if (MI.getOpcode() == PPC::ReadTB) {
11209     // To read the 64-bit time-base register on a 32-bit target, we read the
11210     // two halves. Should the counter have wrapped while it was being read, we
11211     // need to try again.
11212     // ...
11213     // readLoop:
11214     // mfspr Rx,TBU # load from TBU
11215     // mfspr Ry,TB  # load from TB
11216     // mfspr Rz,TBU # load from TBU
11217     // cmpw crX,Rx,Rz # check if 'old'='new'
11218     // bne readLoop   # branch if they're not equal
11219     // ...
11220 
11221     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11222     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11223     DebugLoc dl = MI.getDebugLoc();
11224     F->insert(It, readMBB);
11225     F->insert(It, sinkMBB);
11226 
11227     // Transfer the remainder of BB and its successor edges to sinkMBB.
11228     sinkMBB->splice(sinkMBB->begin(), BB,
11229                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11230     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11231 
11232     BB->addSuccessor(readMBB);
11233     BB = readMBB;
11234 
11235     MachineRegisterInfo &RegInfo = F->getRegInfo();
11236     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11237     Register LoReg = MI.getOperand(0).getReg();
11238     Register HiReg = MI.getOperand(1).getReg();
11239 
11240     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11241     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11242     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11243 
11244     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11245 
11246     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11247         .addReg(HiReg)
11248         .addReg(ReadAgainReg);
11249     BuildMI(BB, dl, TII->get(PPC::BCC))
11250         .addImm(PPC::PRED_NE)
11251         .addReg(CmpReg)
11252         .addMBB(readMBB);
11253 
11254     BB->addSuccessor(readMBB);
11255     BB->addSuccessor(sinkMBB);
11256   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11257     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11258   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11259     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11260   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11261     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11262   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11263     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11264 
11265   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11266     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11267   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11268     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11269   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11270     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11271   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11272     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11273 
11274   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11275     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11276   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11277     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11278   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11279     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11280   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11281     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11282 
11283   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11284     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11285   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11286     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11287   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11288     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11289   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11290     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11291 
11292   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11293     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11294   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11295     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11296   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11297     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11298   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11299     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11300 
11301   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11302     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11303   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11304     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11305   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11306     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11307   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11308     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11309 
11310   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11311     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11312   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11313     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11314   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11315     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11316   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11317     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11318 
11319   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11320     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11321   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11322     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11323   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11324     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11325   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11326     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11327 
11328   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11329     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11330   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11331     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11332   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11333     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11334   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11335     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11336 
11337   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11338     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11339   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11340     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11341   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11342     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11343   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11344     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11345 
11346   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11347     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11348   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11349     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11350   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11351     BB = EmitAtomicBinary(MI, BB, 4, 0);
11352   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11353     BB = EmitAtomicBinary(MI, BB, 8, 0);
11354   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11355            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11356            (Subtarget.hasPartwordAtomics() &&
11357             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11358            (Subtarget.hasPartwordAtomics() &&
11359             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11360     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11361 
11362     auto LoadMnemonic = PPC::LDARX;
11363     auto StoreMnemonic = PPC::STDCX;
11364     switch (MI.getOpcode()) {
11365     default:
11366       llvm_unreachable("Compare and swap of unknown size");
11367     case PPC::ATOMIC_CMP_SWAP_I8:
11368       LoadMnemonic = PPC::LBARX;
11369       StoreMnemonic = PPC::STBCX;
11370       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11371       break;
11372     case PPC::ATOMIC_CMP_SWAP_I16:
11373       LoadMnemonic = PPC::LHARX;
11374       StoreMnemonic = PPC::STHCX;
11375       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11376       break;
11377     case PPC::ATOMIC_CMP_SWAP_I32:
11378       LoadMnemonic = PPC::LWARX;
11379       StoreMnemonic = PPC::STWCX;
11380       break;
11381     case PPC::ATOMIC_CMP_SWAP_I64:
11382       LoadMnemonic = PPC::LDARX;
11383       StoreMnemonic = PPC::STDCX;
11384       break;
11385     }
11386     Register dest = MI.getOperand(0).getReg();
11387     Register ptrA = MI.getOperand(1).getReg();
11388     Register ptrB = MI.getOperand(2).getReg();
11389     Register oldval = MI.getOperand(3).getReg();
11390     Register newval = MI.getOperand(4).getReg();
11391     DebugLoc dl = MI.getDebugLoc();
11392 
11393     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11394     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11395     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11396     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11397     F->insert(It, loop1MBB);
11398     F->insert(It, loop2MBB);
11399     F->insert(It, midMBB);
11400     F->insert(It, exitMBB);
11401     exitMBB->splice(exitMBB->begin(), BB,
11402                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11403     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11404 
11405     //  thisMBB:
11406     //   ...
11407     //   fallthrough --> loopMBB
11408     BB->addSuccessor(loop1MBB);
11409 
11410     // loop1MBB:
11411     //   l[bhwd]arx dest, ptr
11412     //   cmp[wd] dest, oldval
11413     //   bne- midMBB
11414     // loop2MBB:
11415     //   st[bhwd]cx. newval, ptr
11416     //   bne- loopMBB
11417     //   b exitBB
11418     // midMBB:
11419     //   st[bhwd]cx. dest, ptr
11420     // exitBB:
11421     BB = loop1MBB;
11422     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11423     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11424         .addReg(oldval)
11425         .addReg(dest);
11426     BuildMI(BB, dl, TII->get(PPC::BCC))
11427         .addImm(PPC::PRED_NE)
11428         .addReg(PPC::CR0)
11429         .addMBB(midMBB);
11430     BB->addSuccessor(loop2MBB);
11431     BB->addSuccessor(midMBB);
11432 
11433     BB = loop2MBB;
11434     BuildMI(BB, dl, TII->get(StoreMnemonic))
11435         .addReg(newval)
11436         .addReg(ptrA)
11437         .addReg(ptrB);
11438     BuildMI(BB, dl, TII->get(PPC::BCC))
11439         .addImm(PPC::PRED_NE)
11440         .addReg(PPC::CR0)
11441         .addMBB(loop1MBB);
11442     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11443     BB->addSuccessor(loop1MBB);
11444     BB->addSuccessor(exitMBB);
11445 
11446     BB = midMBB;
11447     BuildMI(BB, dl, TII->get(StoreMnemonic))
11448         .addReg(dest)
11449         .addReg(ptrA)
11450         .addReg(ptrB);
11451     BB->addSuccessor(exitMBB);
11452 
11453     //  exitMBB:
11454     //   ...
11455     BB = exitMBB;
11456   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11457              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11458     // We must use 64-bit registers for addresses when targeting 64-bit,
11459     // since we're actually doing arithmetic on them.  Other registers
11460     // can be 32-bit.
11461     bool is64bit = Subtarget.isPPC64();
11462     bool isLittleEndian = Subtarget.isLittleEndian();
11463     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11464 
11465     Register dest = MI.getOperand(0).getReg();
11466     Register ptrA = MI.getOperand(1).getReg();
11467     Register ptrB = MI.getOperand(2).getReg();
11468     Register oldval = MI.getOperand(3).getReg();
11469     Register newval = MI.getOperand(4).getReg();
11470     DebugLoc dl = MI.getDebugLoc();
11471 
11472     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11473     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11474     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11475     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11476     F->insert(It, loop1MBB);
11477     F->insert(It, loop2MBB);
11478     F->insert(It, midMBB);
11479     F->insert(It, exitMBB);
11480     exitMBB->splice(exitMBB->begin(), BB,
11481                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11482     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11483 
11484     MachineRegisterInfo &RegInfo = F->getRegInfo();
11485     const TargetRegisterClass *RC =
11486         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11487     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11488 
11489     Register PtrReg = RegInfo.createVirtualRegister(RC);
11490     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11491     Register ShiftReg =
11492         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11493     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11494     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11495     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11496     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11497     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11498     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11499     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11500     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11501     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11502     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11503     Register Ptr1Reg;
11504     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11505     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11506     //  thisMBB:
11507     //   ...
11508     //   fallthrough --> loopMBB
11509     BB->addSuccessor(loop1MBB);
11510 
11511     // The 4-byte load must be aligned, while a char or short may be
11512     // anywhere in the word.  Hence all this nasty bookkeeping code.
11513     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11514     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11515     //   xori shift, shift1, 24 [16]
11516     //   rlwinm ptr, ptr1, 0, 0, 29
11517     //   slw newval2, newval, shift
11518     //   slw oldval2, oldval,shift
11519     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11520     //   slw mask, mask2, shift
11521     //   and newval3, newval2, mask
11522     //   and oldval3, oldval2, mask
11523     // loop1MBB:
11524     //   lwarx tmpDest, ptr
11525     //   and tmp, tmpDest, mask
11526     //   cmpw tmp, oldval3
11527     //   bne- midMBB
11528     // loop2MBB:
11529     //   andc tmp2, tmpDest, mask
11530     //   or tmp4, tmp2, newval3
11531     //   stwcx. tmp4, ptr
11532     //   bne- loop1MBB
11533     //   b exitBB
11534     // midMBB:
11535     //   stwcx. tmpDest, ptr
11536     // exitBB:
11537     //   srw dest, tmpDest, shift
11538     if (ptrA != ZeroReg) {
11539       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11540       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11541           .addReg(ptrA)
11542           .addReg(ptrB);
11543     } else {
11544       Ptr1Reg = ptrB;
11545     }
11546 
11547     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11548     // mode.
11549     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11550         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11551         .addImm(3)
11552         .addImm(27)
11553         .addImm(is8bit ? 28 : 27);
11554     if (!isLittleEndian)
11555       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11556           .addReg(Shift1Reg)
11557           .addImm(is8bit ? 24 : 16);
11558     if (is64bit)
11559       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11560           .addReg(Ptr1Reg)
11561           .addImm(0)
11562           .addImm(61);
11563     else
11564       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11565           .addReg(Ptr1Reg)
11566           .addImm(0)
11567           .addImm(0)
11568           .addImm(29);
11569     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11570         .addReg(newval)
11571         .addReg(ShiftReg);
11572     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11573         .addReg(oldval)
11574         .addReg(ShiftReg);
11575     if (is8bit)
11576       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11577     else {
11578       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11579       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11580           .addReg(Mask3Reg)
11581           .addImm(65535);
11582     }
11583     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11584         .addReg(Mask2Reg)
11585         .addReg(ShiftReg);
11586     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11587         .addReg(NewVal2Reg)
11588         .addReg(MaskReg);
11589     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11590         .addReg(OldVal2Reg)
11591         .addReg(MaskReg);
11592 
11593     BB = loop1MBB;
11594     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11595         .addReg(ZeroReg)
11596         .addReg(PtrReg);
11597     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11598         .addReg(TmpDestReg)
11599         .addReg(MaskReg);
11600     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11601         .addReg(TmpReg)
11602         .addReg(OldVal3Reg);
11603     BuildMI(BB, dl, TII->get(PPC::BCC))
11604         .addImm(PPC::PRED_NE)
11605         .addReg(PPC::CR0)
11606         .addMBB(midMBB);
11607     BB->addSuccessor(loop2MBB);
11608     BB->addSuccessor(midMBB);
11609 
11610     BB = loop2MBB;
11611     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11612         .addReg(TmpDestReg)
11613         .addReg(MaskReg);
11614     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11615         .addReg(Tmp2Reg)
11616         .addReg(NewVal3Reg);
11617     BuildMI(BB, dl, TII->get(PPC::STWCX))
11618         .addReg(Tmp4Reg)
11619         .addReg(ZeroReg)
11620         .addReg(PtrReg);
11621     BuildMI(BB, dl, TII->get(PPC::BCC))
11622         .addImm(PPC::PRED_NE)
11623         .addReg(PPC::CR0)
11624         .addMBB(loop1MBB);
11625     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11626     BB->addSuccessor(loop1MBB);
11627     BB->addSuccessor(exitMBB);
11628 
11629     BB = midMBB;
11630     BuildMI(BB, dl, TII->get(PPC::STWCX))
11631         .addReg(TmpDestReg)
11632         .addReg(ZeroReg)
11633         .addReg(PtrReg);
11634     BB->addSuccessor(exitMBB);
11635 
11636     //  exitMBB:
11637     //   ...
11638     BB = exitMBB;
11639     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11640         .addReg(TmpReg)
11641         .addReg(ShiftReg);
11642   } else if (MI.getOpcode() == PPC::FADDrtz) {
11643     // This pseudo performs an FADD with rounding mode temporarily forced
11644     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11645     // is not modeled at the SelectionDAG level.
11646     Register Dest = MI.getOperand(0).getReg();
11647     Register Src1 = MI.getOperand(1).getReg();
11648     Register Src2 = MI.getOperand(2).getReg();
11649     DebugLoc dl = MI.getDebugLoc();
11650 
11651     MachineRegisterInfo &RegInfo = F->getRegInfo();
11652     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11653 
11654     // Save FPSCR value.
11655     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11656 
11657     // Set rounding mode to round-to-zero.
11658     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11659     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11660 
11661     // Perform addition.
11662     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11663 
11664     // Restore FPSCR value.
11665     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11666   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11667              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
11668              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11669              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
11670     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11671                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
11672                           ? PPC::ANDI8o
11673                           : PPC::ANDIo;
11674     bool IsEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11675                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
11676 
11677     MachineRegisterInfo &RegInfo = F->getRegInfo();
11678     Register Dest = RegInfo.createVirtualRegister(
11679         Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11680 
11681     DebugLoc Dl = MI.getDebugLoc();
11682     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
11683         .addReg(MI.getOperand(1).getReg())
11684         .addImm(1);
11685     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11686             MI.getOperand(0).getReg())
11687         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
11688   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11689     DebugLoc Dl = MI.getDebugLoc();
11690     MachineRegisterInfo &RegInfo = F->getRegInfo();
11691     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11692     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11693     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11694             MI.getOperand(0).getReg())
11695         .addReg(CRReg);
11696   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11697     DebugLoc Dl = MI.getDebugLoc();
11698     unsigned Imm = MI.getOperand(1).getImm();
11699     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11700     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11701             MI.getOperand(0).getReg())
11702         .addReg(PPC::CR0EQ);
11703   } else if (MI.getOpcode() == PPC::SETRNDi) {
11704     DebugLoc dl = MI.getDebugLoc();
11705     Register OldFPSCRReg = MI.getOperand(0).getReg();
11706 
11707     // Save FPSCR value.
11708     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11709 
11710     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11711     // the following settings:
11712     //   00 Round to nearest
11713     //   01 Round to 0
11714     //   10 Round to +inf
11715     //   11 Round to -inf
11716 
11717     // When the operand is immediate, using the two least significant bits of
11718     // the immediate to set the bits 62:63 of FPSCR.
11719     unsigned Mode = MI.getOperand(1).getImm();
11720     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11721       .addImm(31);
11722 
11723     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11724       .addImm(30);
11725   } else if (MI.getOpcode() == PPC::SETRND) {
11726     DebugLoc dl = MI.getDebugLoc();
11727 
11728     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11729     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11730     // If the target doesn't have DirectMove, we should use stack to do the
11731     // conversion, because the target doesn't have the instructions like mtvsrd
11732     // or mfvsrd to do this conversion directly.
11733     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11734       if (Subtarget.hasDirectMove()) {
11735         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11736           .addReg(SrcReg);
11737       } else {
11738         // Use stack to do the register copy.
11739         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11740         MachineRegisterInfo &RegInfo = F->getRegInfo();
11741         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11742         if (RC == &PPC::F8RCRegClass) {
11743           // Copy register from F8RCRegClass to G8RCRegclass.
11744           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11745                  "Unsupported RegClass.");
11746 
11747           StoreOp = PPC::STFD;
11748           LoadOp = PPC::LD;
11749         } else {
11750           // Copy register from G8RCRegClass to F8RCRegclass.
11751           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11752                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11753                  "Unsupported RegClass.");
11754         }
11755 
11756         MachineFrameInfo &MFI = F->getFrameInfo();
11757         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11758 
11759         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11760           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11761           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11762           MFI.getObjectAlignment(FrameIdx));
11763 
11764         // Store the SrcReg into the stack.
11765         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11766           .addReg(SrcReg)
11767           .addImm(0)
11768           .addFrameIndex(FrameIdx)
11769           .addMemOperand(MMOStore);
11770 
11771         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11772           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11773           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11774           MFI.getObjectAlignment(FrameIdx));
11775 
11776         // Load from the stack where SrcReg is stored, and save to DestReg,
11777         // so we have done the RegClass conversion from RegClass::SrcReg to
11778         // RegClass::DestReg.
11779         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11780           .addImm(0)
11781           .addFrameIndex(FrameIdx)
11782           .addMemOperand(MMOLoad);
11783       }
11784     };
11785 
11786     Register OldFPSCRReg = MI.getOperand(0).getReg();
11787 
11788     // Save FPSCR value.
11789     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11790 
11791     // When the operand is gprc register, use two least significant bits of the
11792     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11793     //
11794     // copy OldFPSCRTmpReg, OldFPSCRReg
11795     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11796     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11797     // copy NewFPSCRReg, NewFPSCRTmpReg
11798     // mtfsf 255, NewFPSCRReg
11799     MachineOperand SrcOp = MI.getOperand(1);
11800     MachineRegisterInfo &RegInfo = F->getRegInfo();
11801     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11802 
11803     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11804 
11805     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11806     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11807 
11808     // The first operand of INSERT_SUBREG should be a register which has
11809     // subregisters, we only care about its RegClass, so we should use an
11810     // IMPLICIT_DEF register.
11811     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11812     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11813       .addReg(ImDefReg)
11814       .add(SrcOp)
11815       .addImm(1);
11816 
11817     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11818     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11819       .addReg(OldFPSCRTmpReg)
11820       .addReg(ExtSrcReg)
11821       .addImm(0)
11822       .addImm(62);
11823 
11824     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11825     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11826 
11827     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11828     // bits of FPSCR.
11829     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11830       .addImm(255)
11831       .addReg(NewFPSCRReg)
11832       .addImm(0)
11833       .addImm(0);
11834   } else {
11835     llvm_unreachable("Unexpected instr type to insert");
11836   }
11837 
11838   MI.eraseFromParent(); // The pseudo instruction is gone now.
11839   return BB;
11840 }
11841 
11842 //===----------------------------------------------------------------------===//
11843 // Target Optimization Hooks
11844 //===----------------------------------------------------------------------===//
11845 
11846 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11847   // For the estimates, convergence is quadratic, so we essentially double the
11848   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11849   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11850   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11851   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11852   if (VT.getScalarType() == MVT::f64)
11853     RefinementSteps++;
11854   return RefinementSteps;
11855 }
11856 
11857 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11858                                            int Enabled, int &RefinementSteps,
11859                                            bool &UseOneConstNR,
11860                                            bool Reciprocal) const {
11861   EVT VT = Operand.getValueType();
11862   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11863       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11864       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11865       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11866       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11867       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11868     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11869       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11870 
11871     // The Newton-Raphson computation with a single constant does not provide
11872     // enough accuracy on some CPUs.
11873     UseOneConstNR = !Subtarget.needsTwoConstNR();
11874     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11875   }
11876   return SDValue();
11877 }
11878 
11879 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11880                                             int Enabled,
11881                                             int &RefinementSteps) const {
11882   EVT VT = Operand.getValueType();
11883   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11884       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11885       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11886       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11887       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11888       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11889     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11890       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11891     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11892   }
11893   return SDValue();
11894 }
11895 
11896 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11897   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11898   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11899   // enabled for division), this functionality is redundant with the default
11900   // combiner logic (once the division -> reciprocal/multiply transformation
11901   // has taken place). As a result, this matters more for older cores than for
11902   // newer ones.
11903 
11904   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11905   // reciprocal if there are two or more FDIVs (for embedded cores with only
11906   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11907   switch (Subtarget.getCPUDirective()) {
11908   default:
11909     return 3;
11910   case PPC::DIR_440:
11911   case PPC::DIR_A2:
11912   case PPC::DIR_E500:
11913   case PPC::DIR_E500mc:
11914   case PPC::DIR_E5500:
11915     return 2;
11916   }
11917 }
11918 
11919 // isConsecutiveLSLoc needs to work even if all adds have not yet been
11920 // collapsed, and so we need to look through chains of them.
11921 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11922                                      int64_t& Offset, SelectionDAG &DAG) {
11923   if (DAG.isBaseWithConstantOffset(Loc)) {
11924     Base = Loc.getOperand(0);
11925     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11926 
11927     // The base might itself be a base plus an offset, and if so, accumulate
11928     // that as well.
11929     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11930   }
11931 }
11932 
11933 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11934                             unsigned Bytes, int Dist,
11935                             SelectionDAG &DAG) {
11936   if (VT.getSizeInBits() / 8 != Bytes)
11937     return false;
11938 
11939   SDValue BaseLoc = Base->getBasePtr();
11940   if (Loc.getOpcode() == ISD::FrameIndex) {
11941     if (BaseLoc.getOpcode() != ISD::FrameIndex)
11942       return false;
11943     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11944     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
11945     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11946     int FS  = MFI.getObjectSize(FI);
11947     int BFS = MFI.getObjectSize(BFI);
11948     if (FS != BFS || FS != (int)Bytes) return false;
11949     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11950   }
11951 
11952   SDValue Base1 = Loc, Base2 = BaseLoc;
11953   int64_t Offset1 = 0, Offset2 = 0;
11954   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
11955   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
11956   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
11957     return true;
11958 
11959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11960   const GlobalValue *GV1 = nullptr;
11961   const GlobalValue *GV2 = nullptr;
11962   Offset1 = 0;
11963   Offset2 = 0;
11964   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
11965   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
11966   if (isGA1 && isGA2 && GV1 == GV2)
11967     return Offset1 == (Offset2 + Dist*Bytes);
11968   return false;
11969 }
11970 
11971 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
11972 // not enforce equality of the chain operands.
11973 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
11974                             unsigned Bytes, int Dist,
11975                             SelectionDAG &DAG) {
11976   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
11977     EVT VT = LS->getMemoryVT();
11978     SDValue Loc = LS->getBasePtr();
11979     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
11980   }
11981 
11982   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
11983     EVT VT;
11984     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11985     default: return false;
11986     case Intrinsic::ppc_qpx_qvlfd:
11987     case Intrinsic::ppc_qpx_qvlfda:
11988       VT = MVT::v4f64;
11989       break;
11990     case Intrinsic::ppc_qpx_qvlfs:
11991     case Intrinsic::ppc_qpx_qvlfsa:
11992       VT = MVT::v4f32;
11993       break;
11994     case Intrinsic::ppc_qpx_qvlfcd:
11995     case Intrinsic::ppc_qpx_qvlfcda:
11996       VT = MVT::v2f64;
11997       break;
11998     case Intrinsic::ppc_qpx_qvlfcs:
11999     case Intrinsic::ppc_qpx_qvlfcsa:
12000       VT = MVT::v2f32;
12001       break;
12002     case Intrinsic::ppc_qpx_qvlfiwa:
12003     case Intrinsic::ppc_qpx_qvlfiwz:
12004     case Intrinsic::ppc_altivec_lvx:
12005     case Intrinsic::ppc_altivec_lvxl:
12006     case Intrinsic::ppc_vsx_lxvw4x:
12007     case Intrinsic::ppc_vsx_lxvw4x_be:
12008       VT = MVT::v4i32;
12009       break;
12010     case Intrinsic::ppc_vsx_lxvd2x:
12011     case Intrinsic::ppc_vsx_lxvd2x_be:
12012       VT = MVT::v2f64;
12013       break;
12014     case Intrinsic::ppc_altivec_lvebx:
12015       VT = MVT::i8;
12016       break;
12017     case Intrinsic::ppc_altivec_lvehx:
12018       VT = MVT::i16;
12019       break;
12020     case Intrinsic::ppc_altivec_lvewx:
12021       VT = MVT::i32;
12022       break;
12023     }
12024 
12025     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12026   }
12027 
12028   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12029     EVT VT;
12030     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12031     default: return false;
12032     case Intrinsic::ppc_qpx_qvstfd:
12033     case Intrinsic::ppc_qpx_qvstfda:
12034       VT = MVT::v4f64;
12035       break;
12036     case Intrinsic::ppc_qpx_qvstfs:
12037     case Intrinsic::ppc_qpx_qvstfsa:
12038       VT = MVT::v4f32;
12039       break;
12040     case Intrinsic::ppc_qpx_qvstfcd:
12041     case Intrinsic::ppc_qpx_qvstfcda:
12042       VT = MVT::v2f64;
12043       break;
12044     case Intrinsic::ppc_qpx_qvstfcs:
12045     case Intrinsic::ppc_qpx_qvstfcsa:
12046       VT = MVT::v2f32;
12047       break;
12048     case Intrinsic::ppc_qpx_qvstfiw:
12049     case Intrinsic::ppc_qpx_qvstfiwa:
12050     case Intrinsic::ppc_altivec_stvx:
12051     case Intrinsic::ppc_altivec_stvxl:
12052     case Intrinsic::ppc_vsx_stxvw4x:
12053       VT = MVT::v4i32;
12054       break;
12055     case Intrinsic::ppc_vsx_stxvd2x:
12056       VT = MVT::v2f64;
12057       break;
12058     case Intrinsic::ppc_vsx_stxvw4x_be:
12059       VT = MVT::v4i32;
12060       break;
12061     case Intrinsic::ppc_vsx_stxvd2x_be:
12062       VT = MVT::v2f64;
12063       break;
12064     case Intrinsic::ppc_altivec_stvebx:
12065       VT = MVT::i8;
12066       break;
12067     case Intrinsic::ppc_altivec_stvehx:
12068       VT = MVT::i16;
12069       break;
12070     case Intrinsic::ppc_altivec_stvewx:
12071       VT = MVT::i32;
12072       break;
12073     }
12074 
12075     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12076   }
12077 
12078   return false;
12079 }
12080 
12081 // Return true is there is a nearyby consecutive load to the one provided
12082 // (regardless of alignment). We search up and down the chain, looking though
12083 // token factors and other loads (but nothing else). As a result, a true result
12084 // indicates that it is safe to create a new consecutive load adjacent to the
12085 // load provided.
12086 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12087   SDValue Chain = LD->getChain();
12088   EVT VT = LD->getMemoryVT();
12089 
12090   SmallSet<SDNode *, 16> LoadRoots;
12091   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12092   SmallSet<SDNode *, 16> Visited;
12093 
12094   // First, search up the chain, branching to follow all token-factor operands.
12095   // If we find a consecutive load, then we're done, otherwise, record all
12096   // nodes just above the top-level loads and token factors.
12097   while (!Queue.empty()) {
12098     SDNode *ChainNext = Queue.pop_back_val();
12099     if (!Visited.insert(ChainNext).second)
12100       continue;
12101 
12102     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12103       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12104         return true;
12105 
12106       if (!Visited.count(ChainLD->getChain().getNode()))
12107         Queue.push_back(ChainLD->getChain().getNode());
12108     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12109       for (const SDUse &O : ChainNext->ops())
12110         if (!Visited.count(O.getNode()))
12111           Queue.push_back(O.getNode());
12112     } else
12113       LoadRoots.insert(ChainNext);
12114   }
12115 
12116   // Second, search down the chain, starting from the top-level nodes recorded
12117   // in the first phase. These top-level nodes are the nodes just above all
12118   // loads and token factors. Starting with their uses, recursively look though
12119   // all loads (just the chain uses) and token factors to find a consecutive
12120   // load.
12121   Visited.clear();
12122   Queue.clear();
12123 
12124   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12125        IE = LoadRoots.end(); I != IE; ++I) {
12126     Queue.push_back(*I);
12127 
12128     while (!Queue.empty()) {
12129       SDNode *LoadRoot = Queue.pop_back_val();
12130       if (!Visited.insert(LoadRoot).second)
12131         continue;
12132 
12133       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12134         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12135           return true;
12136 
12137       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12138            UE = LoadRoot->use_end(); UI != UE; ++UI)
12139         if (((isa<MemSDNode>(*UI) &&
12140             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12141             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12142           Queue.push_back(*UI);
12143     }
12144   }
12145 
12146   return false;
12147 }
12148 
12149 /// This function is called when we have proved that a SETCC node can be replaced
12150 /// by subtraction (and other supporting instructions) so that the result of
12151 /// comparison is kept in a GPR instead of CR. This function is purely for
12152 /// codegen purposes and has some flags to guide the codegen process.
12153 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12154                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12155   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12156 
12157   // Zero extend the operands to the largest legal integer. Originally, they
12158   // must be of a strictly smaller size.
12159   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12160                          DAG.getConstant(Size, DL, MVT::i32));
12161   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12162                          DAG.getConstant(Size, DL, MVT::i32));
12163 
12164   // Swap if needed. Depends on the condition code.
12165   if (Swap)
12166     std::swap(Op0, Op1);
12167 
12168   // Subtract extended integers.
12169   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12170 
12171   // Move the sign bit to the least significant position and zero out the rest.
12172   // Now the least significant bit carries the result of original comparison.
12173   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12174                              DAG.getConstant(Size - 1, DL, MVT::i32));
12175   auto Final = Shifted;
12176 
12177   // Complement the result if needed. Based on the condition code.
12178   if (Complement)
12179     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12180                         DAG.getConstant(1, DL, MVT::i64));
12181 
12182   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12183 }
12184 
12185 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12186                                                   DAGCombinerInfo &DCI) const {
12187   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12188 
12189   SelectionDAG &DAG = DCI.DAG;
12190   SDLoc DL(N);
12191 
12192   // Size of integers being compared has a critical role in the following
12193   // analysis, so we prefer to do this when all types are legal.
12194   if (!DCI.isAfterLegalizeDAG())
12195     return SDValue();
12196 
12197   // If all users of SETCC extend its value to a legal integer type
12198   // then we replace SETCC with a subtraction
12199   for (SDNode::use_iterator UI = N->use_begin(),
12200        UE = N->use_end(); UI != UE; ++UI) {
12201     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12202       return SDValue();
12203   }
12204 
12205   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12206   auto OpSize = N->getOperand(0).getValueSizeInBits();
12207 
12208   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12209 
12210   if (OpSize < Size) {
12211     switch (CC) {
12212     default: break;
12213     case ISD::SETULT:
12214       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12215     case ISD::SETULE:
12216       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12217     case ISD::SETUGT:
12218       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12219     case ISD::SETUGE:
12220       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12221     }
12222   }
12223 
12224   return SDValue();
12225 }
12226 
12227 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12228                                                   DAGCombinerInfo &DCI) const {
12229   SelectionDAG &DAG = DCI.DAG;
12230   SDLoc dl(N);
12231 
12232   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12233   // If we're tracking CR bits, we need to be careful that we don't have:
12234   //   trunc(binary-ops(zext(x), zext(y)))
12235   // or
12236   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12237   // such that we're unnecessarily moving things into GPRs when it would be
12238   // better to keep them in CR bits.
12239 
12240   // Note that trunc here can be an actual i1 trunc, or can be the effective
12241   // truncation that comes from a setcc or select_cc.
12242   if (N->getOpcode() == ISD::TRUNCATE &&
12243       N->getValueType(0) != MVT::i1)
12244     return SDValue();
12245 
12246   if (N->getOperand(0).getValueType() != MVT::i32 &&
12247       N->getOperand(0).getValueType() != MVT::i64)
12248     return SDValue();
12249 
12250   if (N->getOpcode() == ISD::SETCC ||
12251       N->getOpcode() == ISD::SELECT_CC) {
12252     // If we're looking at a comparison, then we need to make sure that the
12253     // high bits (all except for the first) don't matter the result.
12254     ISD::CondCode CC =
12255       cast<CondCodeSDNode>(N->getOperand(
12256         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12257     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12258 
12259     if (ISD::isSignedIntSetCC(CC)) {
12260       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12261           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12262         return SDValue();
12263     } else if (ISD::isUnsignedIntSetCC(CC)) {
12264       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12265                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12266           !DAG.MaskedValueIsZero(N->getOperand(1),
12267                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12268         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12269                                              : SDValue());
12270     } else {
12271       // This is neither a signed nor an unsigned comparison, just make sure
12272       // that the high bits are equal.
12273       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12274       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12275 
12276       // We don't really care about what is known about the first bit (if
12277       // anything), so clear it in all masks prior to comparing them.
12278       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12279       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12280 
12281       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12282         return SDValue();
12283     }
12284   }
12285 
12286   // We now know that the higher-order bits are irrelevant, we just need to
12287   // make sure that all of the intermediate operations are bit operations, and
12288   // all inputs are extensions.
12289   if (N->getOperand(0).getOpcode() != ISD::AND &&
12290       N->getOperand(0).getOpcode() != ISD::OR  &&
12291       N->getOperand(0).getOpcode() != ISD::XOR &&
12292       N->getOperand(0).getOpcode() != ISD::SELECT &&
12293       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12294       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12295       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12296       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12297       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12298     return SDValue();
12299 
12300   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12301       N->getOperand(1).getOpcode() != ISD::AND &&
12302       N->getOperand(1).getOpcode() != ISD::OR  &&
12303       N->getOperand(1).getOpcode() != ISD::XOR &&
12304       N->getOperand(1).getOpcode() != ISD::SELECT &&
12305       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12306       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12307       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12308       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12309       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12310     return SDValue();
12311 
12312   SmallVector<SDValue, 4> Inputs;
12313   SmallVector<SDValue, 8> BinOps, PromOps;
12314   SmallPtrSet<SDNode *, 16> Visited;
12315 
12316   for (unsigned i = 0; i < 2; ++i) {
12317     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12318           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12319           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12320           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12321         isa<ConstantSDNode>(N->getOperand(i)))
12322       Inputs.push_back(N->getOperand(i));
12323     else
12324       BinOps.push_back(N->getOperand(i));
12325 
12326     if (N->getOpcode() == ISD::TRUNCATE)
12327       break;
12328   }
12329 
12330   // Visit all inputs, collect all binary operations (and, or, xor and
12331   // select) that are all fed by extensions.
12332   while (!BinOps.empty()) {
12333     SDValue BinOp = BinOps.back();
12334     BinOps.pop_back();
12335 
12336     if (!Visited.insert(BinOp.getNode()).second)
12337       continue;
12338 
12339     PromOps.push_back(BinOp);
12340 
12341     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12342       // The condition of the select is not promoted.
12343       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12344         continue;
12345       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12346         continue;
12347 
12348       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12349             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12350             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12351            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12352           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12353         Inputs.push_back(BinOp.getOperand(i));
12354       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12355                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12356                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12357                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12358                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12359                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12360                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12361                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12362                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12363         BinOps.push_back(BinOp.getOperand(i));
12364       } else {
12365         // We have an input that is not an extension or another binary
12366         // operation; we'll abort this transformation.
12367         return SDValue();
12368       }
12369     }
12370   }
12371 
12372   // Make sure that this is a self-contained cluster of operations (which
12373   // is not quite the same thing as saying that everything has only one
12374   // use).
12375   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12376     if (isa<ConstantSDNode>(Inputs[i]))
12377       continue;
12378 
12379     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12380                               UE = Inputs[i].getNode()->use_end();
12381          UI != UE; ++UI) {
12382       SDNode *User = *UI;
12383       if (User != N && !Visited.count(User))
12384         return SDValue();
12385 
12386       // Make sure that we're not going to promote the non-output-value
12387       // operand(s) or SELECT or SELECT_CC.
12388       // FIXME: Although we could sometimes handle this, and it does occur in
12389       // practice that one of the condition inputs to the select is also one of
12390       // the outputs, we currently can't deal with this.
12391       if (User->getOpcode() == ISD::SELECT) {
12392         if (User->getOperand(0) == Inputs[i])
12393           return SDValue();
12394       } else if (User->getOpcode() == ISD::SELECT_CC) {
12395         if (User->getOperand(0) == Inputs[i] ||
12396             User->getOperand(1) == Inputs[i])
12397           return SDValue();
12398       }
12399     }
12400   }
12401 
12402   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12403     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12404                               UE = PromOps[i].getNode()->use_end();
12405          UI != UE; ++UI) {
12406       SDNode *User = *UI;
12407       if (User != N && !Visited.count(User))
12408         return SDValue();
12409 
12410       // Make sure that we're not going to promote the non-output-value
12411       // operand(s) or SELECT or SELECT_CC.
12412       // FIXME: Although we could sometimes handle this, and it does occur in
12413       // practice that one of the condition inputs to the select is also one of
12414       // the outputs, we currently can't deal with this.
12415       if (User->getOpcode() == ISD::SELECT) {
12416         if (User->getOperand(0) == PromOps[i])
12417           return SDValue();
12418       } else if (User->getOpcode() == ISD::SELECT_CC) {
12419         if (User->getOperand(0) == PromOps[i] ||
12420             User->getOperand(1) == PromOps[i])
12421           return SDValue();
12422       }
12423     }
12424   }
12425 
12426   // Replace all inputs with the extension operand.
12427   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12428     // Constants may have users outside the cluster of to-be-promoted nodes,
12429     // and so we need to replace those as we do the promotions.
12430     if (isa<ConstantSDNode>(Inputs[i]))
12431       continue;
12432     else
12433       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12434   }
12435 
12436   std::list<HandleSDNode> PromOpHandles;
12437   for (auto &PromOp : PromOps)
12438     PromOpHandles.emplace_back(PromOp);
12439 
12440   // Replace all operations (these are all the same, but have a different
12441   // (i1) return type). DAG.getNode will validate that the types of
12442   // a binary operator match, so go through the list in reverse so that
12443   // we've likely promoted both operands first. Any intermediate truncations or
12444   // extensions disappear.
12445   while (!PromOpHandles.empty()) {
12446     SDValue PromOp = PromOpHandles.back().getValue();
12447     PromOpHandles.pop_back();
12448 
12449     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12450         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12451         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12452         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12453       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12454           PromOp.getOperand(0).getValueType() != MVT::i1) {
12455         // The operand is not yet ready (see comment below).
12456         PromOpHandles.emplace_front(PromOp);
12457         continue;
12458       }
12459 
12460       SDValue RepValue = PromOp.getOperand(0);
12461       if (isa<ConstantSDNode>(RepValue))
12462         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12463 
12464       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12465       continue;
12466     }
12467 
12468     unsigned C;
12469     switch (PromOp.getOpcode()) {
12470     default:             C = 0; break;
12471     case ISD::SELECT:    C = 1; break;
12472     case ISD::SELECT_CC: C = 2; break;
12473     }
12474 
12475     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12476          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12477         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12478          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12479       // The to-be-promoted operands of this node have not yet been
12480       // promoted (this should be rare because we're going through the
12481       // list backward, but if one of the operands has several users in
12482       // this cluster of to-be-promoted nodes, it is possible).
12483       PromOpHandles.emplace_front(PromOp);
12484       continue;
12485     }
12486 
12487     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12488                                 PromOp.getNode()->op_end());
12489 
12490     // If there are any constant inputs, make sure they're replaced now.
12491     for (unsigned i = 0; i < 2; ++i)
12492       if (isa<ConstantSDNode>(Ops[C+i]))
12493         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12494 
12495     DAG.ReplaceAllUsesOfValueWith(PromOp,
12496       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12497   }
12498 
12499   // Now we're left with the initial truncation itself.
12500   if (N->getOpcode() == ISD::TRUNCATE)
12501     return N->getOperand(0);
12502 
12503   // Otherwise, this is a comparison. The operands to be compared have just
12504   // changed type (to i1), but everything else is the same.
12505   return SDValue(N, 0);
12506 }
12507 
12508 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12509                                                   DAGCombinerInfo &DCI) const {
12510   SelectionDAG &DAG = DCI.DAG;
12511   SDLoc dl(N);
12512 
12513   // If we're tracking CR bits, we need to be careful that we don't have:
12514   //   zext(binary-ops(trunc(x), trunc(y)))
12515   // or
12516   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12517   // such that we're unnecessarily moving things into CR bits that can more
12518   // efficiently stay in GPRs. Note that if we're not certain that the high
12519   // bits are set as required by the final extension, we still may need to do
12520   // some masking to get the proper behavior.
12521 
12522   // This same functionality is important on PPC64 when dealing with
12523   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12524   // the return values of functions. Because it is so similar, it is handled
12525   // here as well.
12526 
12527   if (N->getValueType(0) != MVT::i32 &&
12528       N->getValueType(0) != MVT::i64)
12529     return SDValue();
12530 
12531   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12532         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12533     return SDValue();
12534 
12535   if (N->getOperand(0).getOpcode() != ISD::AND &&
12536       N->getOperand(0).getOpcode() != ISD::OR  &&
12537       N->getOperand(0).getOpcode() != ISD::XOR &&
12538       N->getOperand(0).getOpcode() != ISD::SELECT &&
12539       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12540     return SDValue();
12541 
12542   SmallVector<SDValue, 4> Inputs;
12543   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12544   SmallPtrSet<SDNode *, 16> Visited;
12545 
12546   // Visit all inputs, collect all binary operations (and, or, xor and
12547   // select) that are all fed by truncations.
12548   while (!BinOps.empty()) {
12549     SDValue BinOp = BinOps.back();
12550     BinOps.pop_back();
12551 
12552     if (!Visited.insert(BinOp.getNode()).second)
12553       continue;
12554 
12555     PromOps.push_back(BinOp);
12556 
12557     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12558       // The condition of the select is not promoted.
12559       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12560         continue;
12561       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12562         continue;
12563 
12564       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12565           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12566         Inputs.push_back(BinOp.getOperand(i));
12567       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12568                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12569                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12570                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12571                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12572         BinOps.push_back(BinOp.getOperand(i));
12573       } else {
12574         // We have an input that is not a truncation or another binary
12575         // operation; we'll abort this transformation.
12576         return SDValue();
12577       }
12578     }
12579   }
12580 
12581   // The operands of a select that must be truncated when the select is
12582   // promoted because the operand is actually part of the to-be-promoted set.
12583   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12584 
12585   // Make sure that this is a self-contained cluster of operations (which
12586   // is not quite the same thing as saying that everything has only one
12587   // use).
12588   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12589     if (isa<ConstantSDNode>(Inputs[i]))
12590       continue;
12591 
12592     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12593                               UE = Inputs[i].getNode()->use_end();
12594          UI != UE; ++UI) {
12595       SDNode *User = *UI;
12596       if (User != N && !Visited.count(User))
12597         return SDValue();
12598 
12599       // If we're going to promote the non-output-value operand(s) or SELECT or
12600       // SELECT_CC, record them for truncation.
12601       if (User->getOpcode() == ISD::SELECT) {
12602         if (User->getOperand(0) == Inputs[i])
12603           SelectTruncOp[0].insert(std::make_pair(User,
12604                                     User->getOperand(0).getValueType()));
12605       } else if (User->getOpcode() == ISD::SELECT_CC) {
12606         if (User->getOperand(0) == Inputs[i])
12607           SelectTruncOp[0].insert(std::make_pair(User,
12608                                     User->getOperand(0).getValueType()));
12609         if (User->getOperand(1) == Inputs[i])
12610           SelectTruncOp[1].insert(std::make_pair(User,
12611                                     User->getOperand(1).getValueType()));
12612       }
12613     }
12614   }
12615 
12616   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12617     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12618                               UE = PromOps[i].getNode()->use_end();
12619          UI != UE; ++UI) {
12620       SDNode *User = *UI;
12621       if (User != N && !Visited.count(User))
12622         return SDValue();
12623 
12624       // If we're going to promote the non-output-value operand(s) or SELECT or
12625       // SELECT_CC, record them for truncation.
12626       if (User->getOpcode() == ISD::SELECT) {
12627         if (User->getOperand(0) == PromOps[i])
12628           SelectTruncOp[0].insert(std::make_pair(User,
12629                                     User->getOperand(0).getValueType()));
12630       } else if (User->getOpcode() == ISD::SELECT_CC) {
12631         if (User->getOperand(0) == PromOps[i])
12632           SelectTruncOp[0].insert(std::make_pair(User,
12633                                     User->getOperand(0).getValueType()));
12634         if (User->getOperand(1) == PromOps[i])
12635           SelectTruncOp[1].insert(std::make_pair(User,
12636                                     User->getOperand(1).getValueType()));
12637       }
12638     }
12639   }
12640 
12641   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12642   bool ReallyNeedsExt = false;
12643   if (N->getOpcode() != ISD::ANY_EXTEND) {
12644     // If all of the inputs are not already sign/zero extended, then
12645     // we'll still need to do that at the end.
12646     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12647       if (isa<ConstantSDNode>(Inputs[i]))
12648         continue;
12649 
12650       unsigned OpBits =
12651         Inputs[i].getOperand(0).getValueSizeInBits();
12652       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12653 
12654       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12655            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12656                                   APInt::getHighBitsSet(OpBits,
12657                                                         OpBits-PromBits))) ||
12658           (N->getOpcode() == ISD::SIGN_EXTEND &&
12659            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12660              (OpBits-(PromBits-1)))) {
12661         ReallyNeedsExt = true;
12662         break;
12663       }
12664     }
12665   }
12666 
12667   // Replace all inputs, either with the truncation operand, or a
12668   // truncation or extension to the final output type.
12669   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12670     // Constant inputs need to be replaced with the to-be-promoted nodes that
12671     // use them because they might have users outside of the cluster of
12672     // promoted nodes.
12673     if (isa<ConstantSDNode>(Inputs[i]))
12674       continue;
12675 
12676     SDValue InSrc = Inputs[i].getOperand(0);
12677     if (Inputs[i].getValueType() == N->getValueType(0))
12678       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12679     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12680       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12681         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12682     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12683       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12684         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12685     else
12686       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12687         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12688   }
12689 
12690   std::list<HandleSDNode> PromOpHandles;
12691   for (auto &PromOp : PromOps)
12692     PromOpHandles.emplace_back(PromOp);
12693 
12694   // Replace all operations (these are all the same, but have a different
12695   // (promoted) return type). DAG.getNode will validate that the types of
12696   // a binary operator match, so go through the list in reverse so that
12697   // we've likely promoted both operands first.
12698   while (!PromOpHandles.empty()) {
12699     SDValue PromOp = PromOpHandles.back().getValue();
12700     PromOpHandles.pop_back();
12701 
12702     unsigned C;
12703     switch (PromOp.getOpcode()) {
12704     default:             C = 0; break;
12705     case ISD::SELECT:    C = 1; break;
12706     case ISD::SELECT_CC: C = 2; break;
12707     }
12708 
12709     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12710          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12711         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12712          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12713       // The to-be-promoted operands of this node have not yet been
12714       // promoted (this should be rare because we're going through the
12715       // list backward, but if one of the operands has several users in
12716       // this cluster of to-be-promoted nodes, it is possible).
12717       PromOpHandles.emplace_front(PromOp);
12718       continue;
12719     }
12720 
12721     // For SELECT and SELECT_CC nodes, we do a similar check for any
12722     // to-be-promoted comparison inputs.
12723     if (PromOp.getOpcode() == ISD::SELECT ||
12724         PromOp.getOpcode() == ISD::SELECT_CC) {
12725       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12726            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12727           (SelectTruncOp[1].count(PromOp.getNode()) &&
12728            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12729         PromOpHandles.emplace_front(PromOp);
12730         continue;
12731       }
12732     }
12733 
12734     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12735                                 PromOp.getNode()->op_end());
12736 
12737     // If this node has constant inputs, then they'll need to be promoted here.
12738     for (unsigned i = 0; i < 2; ++i) {
12739       if (!isa<ConstantSDNode>(Ops[C+i]))
12740         continue;
12741       if (Ops[C+i].getValueType() == N->getValueType(0))
12742         continue;
12743 
12744       if (N->getOpcode() == ISD::SIGN_EXTEND)
12745         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12746       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12747         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12748       else
12749         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12750     }
12751 
12752     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12753     // truncate them again to the original value type.
12754     if (PromOp.getOpcode() == ISD::SELECT ||
12755         PromOp.getOpcode() == ISD::SELECT_CC) {
12756       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12757       if (SI0 != SelectTruncOp[0].end())
12758         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12759       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12760       if (SI1 != SelectTruncOp[1].end())
12761         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12762     }
12763 
12764     DAG.ReplaceAllUsesOfValueWith(PromOp,
12765       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12766   }
12767 
12768   // Now we're left with the initial extension itself.
12769   if (!ReallyNeedsExt)
12770     return N->getOperand(0);
12771 
12772   // To zero extend, just mask off everything except for the first bit (in the
12773   // i1 case).
12774   if (N->getOpcode() == ISD::ZERO_EXTEND)
12775     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12776                        DAG.getConstant(APInt::getLowBitsSet(
12777                                          N->getValueSizeInBits(0), PromBits),
12778                                        dl, N->getValueType(0)));
12779 
12780   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12781          "Invalid extension type");
12782   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12783   SDValue ShiftCst =
12784       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12785   return DAG.getNode(
12786       ISD::SRA, dl, N->getValueType(0),
12787       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12788       ShiftCst);
12789 }
12790 
12791 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12792                                         DAGCombinerInfo &DCI) const {
12793   assert(N->getOpcode() == ISD::SETCC &&
12794          "Should be called with a SETCC node");
12795 
12796   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12797   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12798     SDValue LHS = N->getOperand(0);
12799     SDValue RHS = N->getOperand(1);
12800 
12801     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12802     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12803         LHS.hasOneUse())
12804       std::swap(LHS, RHS);
12805 
12806     // x == 0-y --> x+y == 0
12807     // x != 0-y --> x+y != 0
12808     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12809         RHS.hasOneUse()) {
12810       SDLoc DL(N);
12811       SelectionDAG &DAG = DCI.DAG;
12812       EVT VT = N->getValueType(0);
12813       EVT OpVT = LHS.getValueType();
12814       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12815       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12816     }
12817   }
12818 
12819   return DAGCombineTruncBoolExt(N, DCI);
12820 }
12821 
12822 // Is this an extending load from an f32 to an f64?
12823 static bool isFPExtLoad(SDValue Op) {
12824   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12825     return LD->getExtensionType() == ISD::EXTLOAD &&
12826       Op.getValueType() == MVT::f64;
12827   return false;
12828 }
12829 
12830 /// Reduces the number of fp-to-int conversion when building a vector.
12831 ///
12832 /// If this vector is built out of floating to integer conversions,
12833 /// transform it to a vector built out of floating point values followed by a
12834 /// single floating to integer conversion of the vector.
12835 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12836 /// becomes (fptosi (build_vector ($A, $B, ...)))
12837 SDValue PPCTargetLowering::
12838 combineElementTruncationToVectorTruncation(SDNode *N,
12839                                            DAGCombinerInfo &DCI) const {
12840   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12841          "Should be called with a BUILD_VECTOR node");
12842 
12843   SelectionDAG &DAG = DCI.DAG;
12844   SDLoc dl(N);
12845 
12846   SDValue FirstInput = N->getOperand(0);
12847   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12848          "The input operand must be an fp-to-int conversion.");
12849 
12850   // This combine happens after legalization so the fp_to_[su]i nodes are
12851   // already converted to PPCSISD nodes.
12852   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12853   if (FirstConversion == PPCISD::FCTIDZ ||
12854       FirstConversion == PPCISD::FCTIDUZ ||
12855       FirstConversion == PPCISD::FCTIWZ ||
12856       FirstConversion == PPCISD::FCTIWUZ) {
12857     bool IsSplat = true;
12858     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12859       FirstConversion == PPCISD::FCTIWUZ;
12860     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12861     SmallVector<SDValue, 4> Ops;
12862     EVT TargetVT = N->getValueType(0);
12863     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12864       SDValue NextOp = N->getOperand(i);
12865       if (NextOp.getOpcode() != PPCISD::MFVSR)
12866         return SDValue();
12867       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12868       if (NextConversion != FirstConversion)
12869         return SDValue();
12870       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12871       // This is not valid if the input was originally double precision. It is
12872       // also not profitable to do unless this is an extending load in which
12873       // case doing this combine will allow us to combine consecutive loads.
12874       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12875         return SDValue();
12876       if (N->getOperand(i) != FirstInput)
12877         IsSplat = false;
12878     }
12879 
12880     // If this is a splat, we leave it as-is since there will be only a single
12881     // fp-to-int conversion followed by a splat of the integer. This is better
12882     // for 32-bit and smaller ints and neutral for 64-bit ints.
12883     if (IsSplat)
12884       return SDValue();
12885 
12886     // Now that we know we have the right type of node, get its operands
12887     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12888       SDValue In = N->getOperand(i).getOperand(0);
12889       if (Is32Bit) {
12890         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12891         // here, we know that all inputs are extending loads so this is safe).
12892         if (In.isUndef())
12893           Ops.push_back(DAG.getUNDEF(SrcVT));
12894         else {
12895           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12896                                       MVT::f32, In.getOperand(0),
12897                                       DAG.getIntPtrConstant(1, dl));
12898           Ops.push_back(Trunc);
12899         }
12900       } else
12901         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12902     }
12903 
12904     unsigned Opcode;
12905     if (FirstConversion == PPCISD::FCTIDZ ||
12906         FirstConversion == PPCISD::FCTIWZ)
12907       Opcode = ISD::FP_TO_SINT;
12908     else
12909       Opcode = ISD::FP_TO_UINT;
12910 
12911     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12912     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12913     return DAG.getNode(Opcode, dl, TargetVT, BV);
12914   }
12915   return SDValue();
12916 }
12917 
12918 /// Reduce the number of loads when building a vector.
12919 ///
12920 /// Building a vector out of multiple loads can be converted to a load
12921 /// of the vector type if the loads are consecutive. If the loads are
12922 /// consecutive but in descending order, a shuffle is added at the end
12923 /// to reorder the vector.
12924 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12925   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12926          "Should be called with a BUILD_VECTOR node");
12927 
12928   SDLoc dl(N);
12929 
12930   // Return early for non byte-sized type, as they can't be consecutive.
12931   if (!N->getValueType(0).getVectorElementType().isByteSized())
12932     return SDValue();
12933 
12934   bool InputsAreConsecutiveLoads = true;
12935   bool InputsAreReverseConsecutive = true;
12936   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12937   SDValue FirstInput = N->getOperand(0);
12938   bool IsRoundOfExtLoad = false;
12939 
12940   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12941       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12942     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12943     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12944   }
12945   // Not a build vector of (possibly fp_rounded) loads.
12946   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12947       N->getNumOperands() == 1)
12948     return SDValue();
12949 
12950   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12951     // If any inputs are fp_round(extload), they all must be.
12952     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12953       return SDValue();
12954 
12955     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
12956       N->getOperand(i);
12957     if (NextInput.getOpcode() != ISD::LOAD)
12958       return SDValue();
12959 
12960     SDValue PreviousInput =
12961       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
12962     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
12963     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
12964 
12965     // If any inputs are fp_round(extload), they all must be.
12966     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
12967       return SDValue();
12968 
12969     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
12970       InputsAreConsecutiveLoads = false;
12971     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
12972       InputsAreReverseConsecutive = false;
12973 
12974     // Exit early if the loads are neither consecutive nor reverse consecutive.
12975     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
12976       return SDValue();
12977   }
12978 
12979   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
12980          "The loads cannot be both consecutive and reverse consecutive.");
12981 
12982   SDValue FirstLoadOp =
12983     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
12984   SDValue LastLoadOp =
12985     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
12986                        N->getOperand(N->getNumOperands()-1);
12987 
12988   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
12989   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
12990   if (InputsAreConsecutiveLoads) {
12991     assert(LD1 && "Input needs to be a LoadSDNode.");
12992     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
12993                        LD1->getBasePtr(), LD1->getPointerInfo(),
12994                        LD1->getAlignment());
12995   }
12996   if (InputsAreReverseConsecutive) {
12997     assert(LDL && "Input needs to be a LoadSDNode.");
12998     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
12999                                LDL->getBasePtr(), LDL->getPointerInfo(),
13000                                LDL->getAlignment());
13001     SmallVector<int, 16> Ops;
13002     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13003       Ops.push_back(i);
13004 
13005     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13006                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13007   }
13008   return SDValue();
13009 }
13010 
13011 // This function adds the required vector_shuffle needed to get
13012 // the elements of the vector extract in the correct position
13013 // as specified by the CorrectElems encoding.
13014 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13015                                       SDValue Input, uint64_t Elems,
13016                                       uint64_t CorrectElems) {
13017   SDLoc dl(N);
13018 
13019   unsigned NumElems = Input.getValueType().getVectorNumElements();
13020   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13021 
13022   // Knowing the element indices being extracted from the original
13023   // vector and the order in which they're being inserted, just put
13024   // them at element indices required for the instruction.
13025   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13026     if (DAG.getDataLayout().isLittleEndian())
13027       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13028     else
13029       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13030     CorrectElems = CorrectElems >> 8;
13031     Elems = Elems >> 8;
13032   }
13033 
13034   SDValue Shuffle =
13035       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13036                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13037 
13038   EVT Ty = N->getValueType(0);
13039   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
13040   return BV;
13041 }
13042 
13043 // Look for build vector patterns where input operands come from sign
13044 // extended vector_extract elements of specific indices. If the correct indices
13045 // aren't used, add a vector shuffle to fix up the indices and create a new
13046 // PPCISD:SExtVElems node which selects the vector sign extend instructions
13047 // during instruction selection.
13048 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13049   // This array encodes the indices that the vector sign extend instructions
13050   // extract from when extending from one type to another for both BE and LE.
13051   // The right nibble of each byte corresponds to the LE incides.
13052   // and the left nibble of each byte corresponds to the BE incides.
13053   // For example: 0x3074B8FC  byte->word
13054   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13055   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13056   // For example: 0x000070F8  byte->double word
13057   // For LE: the allowed indices are: 0x0,0x8
13058   // For BE: the allowed indices are: 0x7,0xF
13059   uint64_t TargetElems[] = {
13060       0x3074B8FC, // b->w
13061       0x000070F8, // b->d
13062       0x10325476, // h->w
13063       0x00003074, // h->d
13064       0x00001032, // w->d
13065   };
13066 
13067   uint64_t Elems = 0;
13068   int Index;
13069   SDValue Input;
13070 
13071   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13072     if (!Op)
13073       return false;
13074     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13075         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13076       return false;
13077 
13078     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13079     // of the right width.
13080     SDValue Extract = Op.getOperand(0);
13081     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13082       Extract = Extract.getOperand(0);
13083     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13084       return false;
13085 
13086     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13087     if (!ExtOp)
13088       return false;
13089 
13090     Index = ExtOp->getZExtValue();
13091     if (Input && Input != Extract.getOperand(0))
13092       return false;
13093 
13094     if (!Input)
13095       Input = Extract.getOperand(0);
13096 
13097     Elems = Elems << 8;
13098     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13099     Elems |= Index;
13100 
13101     return true;
13102   };
13103 
13104   // If the build vector operands aren't sign extended vector extracts,
13105   // of the same input vector, then return.
13106   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13107     if (!isSExtOfVecExtract(N->getOperand(i))) {
13108       return SDValue();
13109     }
13110   }
13111 
13112   // If the vector extract indicies are not correct, add the appropriate
13113   // vector_shuffle.
13114   int TgtElemArrayIdx;
13115   int InputSize = Input.getValueType().getScalarSizeInBits();
13116   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13117   if (InputSize + OutputSize == 40)
13118     TgtElemArrayIdx = 0;
13119   else if (InputSize + OutputSize == 72)
13120     TgtElemArrayIdx = 1;
13121   else if (InputSize + OutputSize == 48)
13122     TgtElemArrayIdx = 2;
13123   else if (InputSize + OutputSize == 80)
13124     TgtElemArrayIdx = 3;
13125   else if (InputSize + OutputSize == 96)
13126     TgtElemArrayIdx = 4;
13127   else
13128     return SDValue();
13129 
13130   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13131   CorrectElems = DAG.getDataLayout().isLittleEndian()
13132                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13133                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13134   if (Elems != CorrectElems) {
13135     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13136   }
13137 
13138   // Regular lowering will catch cases where a shuffle is not needed.
13139   return SDValue();
13140 }
13141 
13142 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13143                                                  DAGCombinerInfo &DCI) const {
13144   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13145          "Should be called with a BUILD_VECTOR node");
13146 
13147   SelectionDAG &DAG = DCI.DAG;
13148   SDLoc dl(N);
13149 
13150   if (!Subtarget.hasVSX())
13151     return SDValue();
13152 
13153   // The target independent DAG combiner will leave a build_vector of
13154   // float-to-int conversions intact. We can generate MUCH better code for
13155   // a float-to-int conversion of a vector of floats.
13156   SDValue FirstInput = N->getOperand(0);
13157   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13158     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13159     if (Reduced)
13160       return Reduced;
13161   }
13162 
13163   // If we're building a vector out of consecutive loads, just load that
13164   // vector type.
13165   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13166   if (Reduced)
13167     return Reduced;
13168 
13169   // If we're building a vector out of extended elements from another vector
13170   // we have P9 vector integer extend instructions. The code assumes legal
13171   // input types (i.e. it can't handle things like v4i16) so do not run before
13172   // legalization.
13173   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13174     Reduced = combineBVOfVecSExt(N, DAG);
13175     if (Reduced)
13176       return Reduced;
13177   }
13178 
13179 
13180   if (N->getValueType(0) != MVT::v2f64)
13181     return SDValue();
13182 
13183   // Looking for:
13184   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13185   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13186       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13187     return SDValue();
13188   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13189       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13190     return SDValue();
13191   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13192     return SDValue();
13193 
13194   SDValue Ext1 = FirstInput.getOperand(0);
13195   SDValue Ext2 = N->getOperand(1).getOperand(0);
13196   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13197      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13198     return SDValue();
13199 
13200   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13201   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13202   if (!Ext1Op || !Ext2Op)
13203     return SDValue();
13204   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13205       Ext1.getOperand(0) != Ext2.getOperand(0))
13206     return SDValue();
13207 
13208   int FirstElem = Ext1Op->getZExtValue();
13209   int SecondElem = Ext2Op->getZExtValue();
13210   int SubvecIdx;
13211   if (FirstElem == 0 && SecondElem == 1)
13212     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13213   else if (FirstElem == 2 && SecondElem == 3)
13214     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13215   else
13216     return SDValue();
13217 
13218   SDValue SrcVec = Ext1.getOperand(0);
13219   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13220     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13221   return DAG.getNode(NodeType, dl, MVT::v2f64,
13222                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13223 }
13224 
13225 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13226                                               DAGCombinerInfo &DCI) const {
13227   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13228           N->getOpcode() == ISD::UINT_TO_FP) &&
13229          "Need an int -> FP conversion node here");
13230 
13231   if (useSoftFloat() || !Subtarget.has64BitSupport())
13232     return SDValue();
13233 
13234   SelectionDAG &DAG = DCI.DAG;
13235   SDLoc dl(N);
13236   SDValue Op(N, 0);
13237 
13238   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13239   // from the hardware.
13240   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13241     return SDValue();
13242   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13243       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13244     return SDValue();
13245 
13246   SDValue FirstOperand(Op.getOperand(0));
13247   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13248     (FirstOperand.getValueType() == MVT::i8 ||
13249      FirstOperand.getValueType() == MVT::i16);
13250   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13251     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13252     bool DstDouble = Op.getValueType() == MVT::f64;
13253     unsigned ConvOp = Signed ?
13254       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13255       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13256     SDValue WidthConst =
13257       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13258                             dl, false);
13259     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13260     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13261     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13262                                          DAG.getVTList(MVT::f64, MVT::Other),
13263                                          Ops, MVT::i8, LDN->getMemOperand());
13264 
13265     // For signed conversion, we need to sign-extend the value in the VSR
13266     if (Signed) {
13267       SDValue ExtOps[] = { Ld, WidthConst };
13268       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13269       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13270     } else
13271       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13272   }
13273 
13274 
13275   // For i32 intermediate values, unfortunately, the conversion functions
13276   // leave the upper 32 bits of the value are undefined. Within the set of
13277   // scalar instructions, we have no method for zero- or sign-extending the
13278   // value. Thus, we cannot handle i32 intermediate values here.
13279   if (Op.getOperand(0).getValueType() == MVT::i32)
13280     return SDValue();
13281 
13282   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13283          "UINT_TO_FP is supported only with FPCVT");
13284 
13285   // If we have FCFIDS, then use it when converting to single-precision.
13286   // Otherwise, convert to double-precision and then round.
13287   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13288                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13289                                                             : PPCISD::FCFIDS)
13290                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13291                                                             : PPCISD::FCFID);
13292   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13293                   ? MVT::f32
13294                   : MVT::f64;
13295 
13296   // If we're converting from a float, to an int, and back to a float again,
13297   // then we don't need the store/load pair at all.
13298   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13299        Subtarget.hasFPCVT()) ||
13300       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13301     SDValue Src = Op.getOperand(0).getOperand(0);
13302     if (Src.getValueType() == MVT::f32) {
13303       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13304       DCI.AddToWorklist(Src.getNode());
13305     } else if (Src.getValueType() != MVT::f64) {
13306       // Make sure that we don't pick up a ppc_fp128 source value.
13307       return SDValue();
13308     }
13309 
13310     unsigned FCTOp =
13311       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13312                                                         PPCISD::FCTIDUZ;
13313 
13314     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13315     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13316 
13317     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13318       FP = DAG.getNode(ISD::FP_ROUND, dl,
13319                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13320       DCI.AddToWorklist(FP.getNode());
13321     }
13322 
13323     return FP;
13324   }
13325 
13326   return SDValue();
13327 }
13328 
13329 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13330 // builtins) into loads with swaps.
13331 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13332                                               DAGCombinerInfo &DCI) const {
13333   SelectionDAG &DAG = DCI.DAG;
13334   SDLoc dl(N);
13335   SDValue Chain;
13336   SDValue Base;
13337   MachineMemOperand *MMO;
13338 
13339   switch (N->getOpcode()) {
13340   default:
13341     llvm_unreachable("Unexpected opcode for little endian VSX load");
13342   case ISD::LOAD: {
13343     LoadSDNode *LD = cast<LoadSDNode>(N);
13344     Chain = LD->getChain();
13345     Base = LD->getBasePtr();
13346     MMO = LD->getMemOperand();
13347     // If the MMO suggests this isn't a load of a full vector, leave
13348     // things alone.  For a built-in, we have to make the change for
13349     // correctness, so if there is a size problem that will be a bug.
13350     if (MMO->getSize() < 16)
13351       return SDValue();
13352     break;
13353   }
13354   case ISD::INTRINSIC_W_CHAIN: {
13355     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13356     Chain = Intrin->getChain();
13357     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13358     // us what we want. Get operand 2 instead.
13359     Base = Intrin->getOperand(2);
13360     MMO = Intrin->getMemOperand();
13361     break;
13362   }
13363   }
13364 
13365   MVT VecTy = N->getValueType(0).getSimpleVT();
13366 
13367   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13368   // aligned and the type is a vector with elements up to 4 bytes
13369   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13370       && VecTy.getScalarSizeInBits() <= 32 ) {
13371     return SDValue();
13372   }
13373 
13374   SDValue LoadOps[] = { Chain, Base };
13375   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13376                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13377                                          LoadOps, MVT::v2f64, MMO);
13378 
13379   DCI.AddToWorklist(Load.getNode());
13380   Chain = Load.getValue(1);
13381   SDValue Swap = DAG.getNode(
13382       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13383   DCI.AddToWorklist(Swap.getNode());
13384 
13385   // Add a bitcast if the resulting load type doesn't match v2f64.
13386   if (VecTy != MVT::v2f64) {
13387     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13388     DCI.AddToWorklist(N.getNode());
13389     // Package {bitcast value, swap's chain} to match Load's shape.
13390     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13391                        N, Swap.getValue(1));
13392   }
13393 
13394   return Swap;
13395 }
13396 
13397 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13398 // builtins) into stores with swaps.
13399 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13400                                                DAGCombinerInfo &DCI) const {
13401   SelectionDAG &DAG = DCI.DAG;
13402   SDLoc dl(N);
13403   SDValue Chain;
13404   SDValue Base;
13405   unsigned SrcOpnd;
13406   MachineMemOperand *MMO;
13407 
13408   switch (N->getOpcode()) {
13409   default:
13410     llvm_unreachable("Unexpected opcode for little endian VSX store");
13411   case ISD::STORE: {
13412     StoreSDNode *ST = cast<StoreSDNode>(N);
13413     Chain = ST->getChain();
13414     Base = ST->getBasePtr();
13415     MMO = ST->getMemOperand();
13416     SrcOpnd = 1;
13417     // If the MMO suggests this isn't a store of a full vector, leave
13418     // things alone.  For a built-in, we have to make the change for
13419     // correctness, so if there is a size problem that will be a bug.
13420     if (MMO->getSize() < 16)
13421       return SDValue();
13422     break;
13423   }
13424   case ISD::INTRINSIC_VOID: {
13425     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13426     Chain = Intrin->getChain();
13427     // Intrin->getBasePtr() oddly does not get what we want.
13428     Base = Intrin->getOperand(3);
13429     MMO = Intrin->getMemOperand();
13430     SrcOpnd = 2;
13431     break;
13432   }
13433   }
13434 
13435   SDValue Src = N->getOperand(SrcOpnd);
13436   MVT VecTy = Src.getValueType().getSimpleVT();
13437 
13438   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13439   // aligned and the type is a vector with elements up to 4 bytes
13440   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13441       && VecTy.getScalarSizeInBits() <= 32 ) {
13442     return SDValue();
13443   }
13444 
13445   // All stores are done as v2f64 and possible bit cast.
13446   if (VecTy != MVT::v2f64) {
13447     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13448     DCI.AddToWorklist(Src.getNode());
13449   }
13450 
13451   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13452                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13453   DCI.AddToWorklist(Swap.getNode());
13454   Chain = Swap.getValue(1);
13455   SDValue StoreOps[] = { Chain, Swap, Base };
13456   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13457                                           DAG.getVTList(MVT::Other),
13458                                           StoreOps, VecTy, MMO);
13459   DCI.AddToWorklist(Store.getNode());
13460   return Store;
13461 }
13462 
13463 // Handle DAG combine for STORE (FP_TO_INT F).
13464 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13465                                                DAGCombinerInfo &DCI) const {
13466 
13467   SelectionDAG &DAG = DCI.DAG;
13468   SDLoc dl(N);
13469   unsigned Opcode = N->getOperand(1).getOpcode();
13470 
13471   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13472          && "Not a FP_TO_INT Instruction!");
13473 
13474   SDValue Val = N->getOperand(1).getOperand(0);
13475   EVT Op1VT = N->getOperand(1).getValueType();
13476   EVT ResVT = Val.getValueType();
13477 
13478   // Floating point types smaller than 32 bits are not legal on Power.
13479   if (ResVT.getScalarSizeInBits() < 32)
13480     return SDValue();
13481 
13482   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13483   bool ValidTypeForStoreFltAsInt =
13484         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13485          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13486 
13487   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13488       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13489     return SDValue();
13490 
13491   // Extend f32 values to f64
13492   if (ResVT.getScalarSizeInBits() == 32) {
13493     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13494     DCI.AddToWorklist(Val.getNode());
13495   }
13496 
13497   // Set signed or unsigned conversion opcode.
13498   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13499                           PPCISD::FP_TO_SINT_IN_VSR :
13500                           PPCISD::FP_TO_UINT_IN_VSR;
13501 
13502   Val = DAG.getNode(ConvOpcode,
13503                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13504   DCI.AddToWorklist(Val.getNode());
13505 
13506   // Set number of bytes being converted.
13507   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13508   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13509                     DAG.getIntPtrConstant(ByteSize, dl, false),
13510                     DAG.getValueType(Op1VT) };
13511 
13512   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13513           DAG.getVTList(MVT::Other), Ops,
13514           cast<StoreSDNode>(N)->getMemoryVT(),
13515           cast<StoreSDNode>(N)->getMemOperand());
13516 
13517   DCI.AddToWorklist(Val.getNode());
13518   return Val;
13519 }
13520 
13521 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13522                                                 LSBaseSDNode *LSBase,
13523                                                 DAGCombinerInfo &DCI) const {
13524   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13525         "Not a reverse memop pattern!");
13526 
13527   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13528     auto Mask = SVN->getMask();
13529     int i = 0;
13530     auto I = Mask.rbegin();
13531     auto E = Mask.rend();
13532 
13533     for (; I != E; ++I) {
13534       if (*I != i)
13535         return false;
13536       i++;
13537     }
13538     return true;
13539   };
13540 
13541   SelectionDAG &DAG = DCI.DAG;
13542   EVT VT = SVN->getValueType(0);
13543 
13544   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13545     return SDValue();
13546 
13547   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13548   // See comment in PPCVSXSwapRemoval.cpp.
13549   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13550   if (!Subtarget.hasP9Vector())
13551     return SDValue();
13552 
13553   if(!IsElementReverse(SVN))
13554     return SDValue();
13555 
13556   if (LSBase->getOpcode() == ISD::LOAD) {
13557     SDLoc dl(SVN);
13558     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13559     return DAG.getMemIntrinsicNode(
13560         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13561         LSBase->getMemoryVT(), LSBase->getMemOperand());
13562   }
13563 
13564   if (LSBase->getOpcode() == ISD::STORE) {
13565     SDLoc dl(LSBase);
13566     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13567                           LSBase->getBasePtr()};
13568     return DAG.getMemIntrinsicNode(
13569         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13570         LSBase->getMemoryVT(), LSBase->getMemOperand());
13571   }
13572 
13573   llvm_unreachable("Expected a load or store node here");
13574 }
13575 
13576 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13577                                              DAGCombinerInfo &DCI) const {
13578   SelectionDAG &DAG = DCI.DAG;
13579   SDLoc dl(N);
13580   switch (N->getOpcode()) {
13581   default: break;
13582   case ISD::ADD:
13583     return combineADD(N, DCI);
13584   case ISD::SHL:
13585     return combineSHL(N, DCI);
13586   case ISD::SRA:
13587     return combineSRA(N, DCI);
13588   case ISD::SRL:
13589     return combineSRL(N, DCI);
13590   case ISD::MUL:
13591     return combineMUL(N, DCI);
13592   case PPCISD::SHL:
13593     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13594         return N->getOperand(0);
13595     break;
13596   case PPCISD::SRL:
13597     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13598         return N->getOperand(0);
13599     break;
13600   case PPCISD::SRA:
13601     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13602       if (C->isNullValue() ||   //  0 >>s V -> 0.
13603           C->isAllOnesValue())    // -1 >>s V -> -1.
13604         return N->getOperand(0);
13605     }
13606     break;
13607   case ISD::SIGN_EXTEND:
13608   case ISD::ZERO_EXTEND:
13609   case ISD::ANY_EXTEND:
13610     return DAGCombineExtBoolTrunc(N, DCI);
13611   case ISD::TRUNCATE:
13612     return combineTRUNCATE(N, DCI);
13613   case ISD::SETCC:
13614     if (SDValue CSCC = combineSetCC(N, DCI))
13615       return CSCC;
13616     LLVM_FALLTHROUGH;
13617   case ISD::SELECT_CC:
13618     return DAGCombineTruncBoolExt(N, DCI);
13619   case ISD::SINT_TO_FP:
13620   case ISD::UINT_TO_FP:
13621     return combineFPToIntToFP(N, DCI);
13622   case ISD::VECTOR_SHUFFLE:
13623     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13624       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13625       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13626     }
13627     break;
13628   case ISD::STORE: {
13629 
13630     EVT Op1VT = N->getOperand(1).getValueType();
13631     unsigned Opcode = N->getOperand(1).getOpcode();
13632 
13633     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13634       SDValue Val= combineStoreFPToInt(N, DCI);
13635       if (Val)
13636         return Val;
13637     }
13638 
13639     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13640       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13641       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13642       if (Val)
13643         return Val;
13644     }
13645 
13646     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13647     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13648         N->getOperand(1).getNode()->hasOneUse() &&
13649         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13650          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13651 
13652       // STBRX can only handle simple types and it makes no sense to store less
13653       // two bytes in byte-reversed order.
13654       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13655       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13656         break;
13657 
13658       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13659       // Do an any-extend to 32-bits if this is a half-word input.
13660       if (BSwapOp.getValueType() == MVT::i16)
13661         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13662 
13663       // If the type of BSWAP operand is wider than stored memory width
13664       // it need to be shifted to the right side before STBRX.
13665       if (Op1VT.bitsGT(mVT)) {
13666         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13667         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13668                               DAG.getConstant(Shift, dl, MVT::i32));
13669         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13670         if (Op1VT == MVT::i64)
13671           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13672       }
13673 
13674       SDValue Ops[] = {
13675         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13676       };
13677       return
13678         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13679                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13680                                 cast<StoreSDNode>(N)->getMemOperand());
13681     }
13682 
13683     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13684     // So it can increase the chance of CSE constant construction.
13685     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13686         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13687       // Need to sign-extended to 64-bits to handle negative values.
13688       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13689       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13690                                     MemVT.getSizeInBits());
13691       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13692 
13693       // DAG.getTruncStore() can't be used here because it doesn't accept
13694       // the general (base + offset) addressing mode.
13695       // So we use UpdateNodeOperands and setTruncatingStore instead.
13696       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13697                              N->getOperand(3));
13698       cast<StoreSDNode>(N)->setTruncatingStore(true);
13699       return SDValue(N, 0);
13700     }
13701 
13702     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13703     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13704     if (Op1VT.isSimple()) {
13705       MVT StoreVT = Op1VT.getSimpleVT();
13706       if (Subtarget.needsSwapsForVSXMemOps() &&
13707           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13708            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13709         return expandVSXStoreForLE(N, DCI);
13710     }
13711     break;
13712   }
13713   case ISD::LOAD: {
13714     LoadSDNode *LD = cast<LoadSDNode>(N);
13715     EVT VT = LD->getValueType(0);
13716 
13717     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13718     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13719     if (VT.isSimple()) {
13720       MVT LoadVT = VT.getSimpleVT();
13721       if (Subtarget.needsSwapsForVSXMemOps() &&
13722           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13723            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13724         return expandVSXLoadForLE(N, DCI);
13725     }
13726 
13727     // We sometimes end up with a 64-bit integer load, from which we extract
13728     // two single-precision floating-point numbers. This happens with
13729     // std::complex<float>, and other similar structures, because of the way we
13730     // canonicalize structure copies. However, if we lack direct moves,
13731     // then the final bitcasts from the extracted integer values to the
13732     // floating-point numbers turn into store/load pairs. Even with direct moves,
13733     // just loading the two floating-point numbers is likely better.
13734     auto ReplaceTwoFloatLoad = [&]() {
13735       if (VT != MVT::i64)
13736         return false;
13737 
13738       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13739           LD->isVolatile())
13740         return false;
13741 
13742       //  We're looking for a sequence like this:
13743       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13744       //      t16: i64 = srl t13, Constant:i32<32>
13745       //    t17: i32 = truncate t16
13746       //  t18: f32 = bitcast t17
13747       //    t19: i32 = truncate t13
13748       //  t20: f32 = bitcast t19
13749 
13750       if (!LD->hasNUsesOfValue(2, 0))
13751         return false;
13752 
13753       auto UI = LD->use_begin();
13754       while (UI.getUse().getResNo() != 0) ++UI;
13755       SDNode *Trunc = *UI++;
13756       while (UI.getUse().getResNo() != 0) ++UI;
13757       SDNode *RightShift = *UI;
13758       if (Trunc->getOpcode() != ISD::TRUNCATE)
13759         std::swap(Trunc, RightShift);
13760 
13761       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13762           Trunc->getValueType(0) != MVT::i32 ||
13763           !Trunc->hasOneUse())
13764         return false;
13765       if (RightShift->getOpcode() != ISD::SRL ||
13766           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13767           RightShift->getConstantOperandVal(1) != 32 ||
13768           !RightShift->hasOneUse())
13769         return false;
13770 
13771       SDNode *Trunc2 = *RightShift->use_begin();
13772       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13773           Trunc2->getValueType(0) != MVT::i32 ||
13774           !Trunc2->hasOneUse())
13775         return false;
13776 
13777       SDNode *Bitcast = *Trunc->use_begin();
13778       SDNode *Bitcast2 = *Trunc2->use_begin();
13779 
13780       if (Bitcast->getOpcode() != ISD::BITCAST ||
13781           Bitcast->getValueType(0) != MVT::f32)
13782         return false;
13783       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13784           Bitcast2->getValueType(0) != MVT::f32)
13785         return false;
13786 
13787       if (Subtarget.isLittleEndian())
13788         std::swap(Bitcast, Bitcast2);
13789 
13790       // Bitcast has the second float (in memory-layout order) and Bitcast2
13791       // has the first one.
13792 
13793       SDValue BasePtr = LD->getBasePtr();
13794       if (LD->isIndexed()) {
13795         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13796                "Non-pre-inc AM on PPC?");
13797         BasePtr =
13798           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13799                       LD->getOffset());
13800       }
13801 
13802       auto MMOFlags =
13803           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13804       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13805                                       LD->getPointerInfo(), LD->getAlignment(),
13806                                       MMOFlags, LD->getAAInfo());
13807       SDValue AddPtr =
13808         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13809                     BasePtr, DAG.getIntPtrConstant(4, dl));
13810       SDValue FloatLoad2 = DAG.getLoad(
13811           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13812           LD->getPointerInfo().getWithOffset(4),
13813           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13814 
13815       if (LD->isIndexed()) {
13816         // Note that DAGCombine should re-form any pre-increment load(s) from
13817         // what is produced here if that makes sense.
13818         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13819       }
13820 
13821       DCI.CombineTo(Bitcast2, FloatLoad);
13822       DCI.CombineTo(Bitcast, FloatLoad2);
13823 
13824       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13825                                     SDValue(FloatLoad2.getNode(), 1));
13826       return true;
13827     };
13828 
13829     if (ReplaceTwoFloatLoad())
13830       return SDValue(N, 0);
13831 
13832     EVT MemVT = LD->getMemoryVT();
13833     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13834     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13835     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13836     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13837     if (LD->isUnindexed() && VT.isVector() &&
13838         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13839           // P8 and later hardware should just use LOAD.
13840           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13841                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13842          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13843           LD->getAlignment() >= ScalarABIAlignment)) &&
13844         LD->getAlignment() < ABIAlignment) {
13845       // This is a type-legal unaligned Altivec or QPX load.
13846       SDValue Chain = LD->getChain();
13847       SDValue Ptr = LD->getBasePtr();
13848       bool isLittleEndian = Subtarget.isLittleEndian();
13849 
13850       // This implements the loading of unaligned vectors as described in
13851       // the venerable Apple Velocity Engine overview. Specifically:
13852       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13853       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13854       //
13855       // The general idea is to expand a sequence of one or more unaligned
13856       // loads into an alignment-based permutation-control instruction (lvsl
13857       // or lvsr), a series of regular vector loads (which always truncate
13858       // their input address to an aligned address), and a series of
13859       // permutations.  The results of these permutations are the requested
13860       // loaded values.  The trick is that the last "extra" load is not taken
13861       // from the address you might suspect (sizeof(vector) bytes after the
13862       // last requested load), but rather sizeof(vector) - 1 bytes after the
13863       // last requested vector. The point of this is to avoid a page fault if
13864       // the base address happened to be aligned. This works because if the
13865       // base address is aligned, then adding less than a full vector length
13866       // will cause the last vector in the sequence to be (re)loaded.
13867       // Otherwise, the next vector will be fetched as you might suspect was
13868       // necessary.
13869 
13870       // We might be able to reuse the permutation generation from
13871       // a different base address offset from this one by an aligned amount.
13872       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13873       // optimization later.
13874       Intrinsic::ID Intr, IntrLD, IntrPerm;
13875       MVT PermCntlTy, PermTy, LDTy;
13876       if (Subtarget.hasAltivec()) {
13877         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13878                                  Intrinsic::ppc_altivec_lvsl;
13879         IntrLD = Intrinsic::ppc_altivec_lvx;
13880         IntrPerm = Intrinsic::ppc_altivec_vperm;
13881         PermCntlTy = MVT::v16i8;
13882         PermTy = MVT::v4i32;
13883         LDTy = MVT::v4i32;
13884       } else {
13885         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13886                                        Intrinsic::ppc_qpx_qvlpcls;
13887         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13888                                        Intrinsic::ppc_qpx_qvlfs;
13889         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13890         PermCntlTy = MVT::v4f64;
13891         PermTy = MVT::v4f64;
13892         LDTy = MemVT.getSimpleVT();
13893       }
13894 
13895       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13896 
13897       // Create the new MMO for the new base load. It is like the original MMO,
13898       // but represents an area in memory almost twice the vector size centered
13899       // on the original address. If the address is unaligned, we might start
13900       // reading up to (sizeof(vector)-1) bytes below the address of the
13901       // original unaligned load.
13902       MachineFunction &MF = DAG.getMachineFunction();
13903       MachineMemOperand *BaseMMO =
13904         MF.getMachineMemOperand(LD->getMemOperand(),
13905                                 -(long)MemVT.getStoreSize()+1,
13906                                 2*MemVT.getStoreSize()-1);
13907 
13908       // Create the new base load.
13909       SDValue LDXIntID =
13910           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13911       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13912       SDValue BaseLoad =
13913         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13914                                 DAG.getVTList(PermTy, MVT::Other),
13915                                 BaseLoadOps, LDTy, BaseMMO);
13916 
13917       // Note that the value of IncOffset (which is provided to the next
13918       // load's pointer info offset value, and thus used to calculate the
13919       // alignment), and the value of IncValue (which is actually used to
13920       // increment the pointer value) are different! This is because we
13921       // require the next load to appear to be aligned, even though it
13922       // is actually offset from the base pointer by a lesser amount.
13923       int IncOffset = VT.getSizeInBits() / 8;
13924       int IncValue = IncOffset;
13925 
13926       // Walk (both up and down) the chain looking for another load at the real
13927       // (aligned) offset (the alignment of the other load does not matter in
13928       // this case). If found, then do not use the offset reduction trick, as
13929       // that will prevent the loads from being later combined (as they would
13930       // otherwise be duplicates).
13931       if (!findConsecutiveLoad(LD, DAG))
13932         --IncValue;
13933 
13934       SDValue Increment =
13935           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13936       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13937 
13938       MachineMemOperand *ExtraMMO =
13939         MF.getMachineMemOperand(LD->getMemOperand(),
13940                                 1, 2*MemVT.getStoreSize()-1);
13941       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13942       SDValue ExtraLoad =
13943         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13944                                 DAG.getVTList(PermTy, MVT::Other),
13945                                 ExtraLoadOps, LDTy, ExtraMMO);
13946 
13947       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13948         BaseLoad.getValue(1), ExtraLoad.getValue(1));
13949 
13950       // Because vperm has a big-endian bias, we must reverse the order
13951       // of the input vectors and complement the permute control vector
13952       // when generating little endian code.  We have already handled the
13953       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13954       // and ExtraLoad here.
13955       SDValue Perm;
13956       if (isLittleEndian)
13957         Perm = BuildIntrinsicOp(IntrPerm,
13958                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
13959       else
13960         Perm = BuildIntrinsicOp(IntrPerm,
13961                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
13962 
13963       if (VT != PermTy)
13964         Perm = Subtarget.hasAltivec() ?
13965                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
13966                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
13967                                DAG.getTargetConstant(1, dl, MVT::i64));
13968                                // second argument is 1 because this rounding
13969                                // is always exact.
13970 
13971       // The output of the permutation is our loaded result, the TokenFactor is
13972       // our new chain.
13973       DCI.CombineTo(N, Perm, TF);
13974       return SDValue(N, 0);
13975     }
13976     }
13977     break;
13978     case ISD::INTRINSIC_WO_CHAIN: {
13979       bool isLittleEndian = Subtarget.isLittleEndian();
13980       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13981       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
13982                                            : Intrinsic::ppc_altivec_lvsl);
13983       if ((IID == Intr ||
13984            IID == Intrinsic::ppc_qpx_qvlpcld  ||
13985            IID == Intrinsic::ppc_qpx_qvlpcls) &&
13986         N->getOperand(1)->getOpcode() == ISD::ADD) {
13987         SDValue Add = N->getOperand(1);
13988 
13989         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
13990                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
13991 
13992         if (DAG.MaskedValueIsZero(Add->getOperand(1),
13993                                   APInt::getAllOnesValue(Bits /* alignment */)
13994                                       .zext(Add.getScalarValueSizeInBits()))) {
13995           SDNode *BasePtr = Add->getOperand(0).getNode();
13996           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13997                                     UE = BasePtr->use_end();
13998                UI != UE; ++UI) {
13999             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14000                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14001               // We've found another LVSL/LVSR, and this address is an aligned
14002               // multiple of that one. The results will be the same, so use the
14003               // one we've just found instead.
14004 
14005               return SDValue(*UI, 0);
14006             }
14007           }
14008         }
14009 
14010         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14011           SDNode *BasePtr = Add->getOperand(0).getNode();
14012           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14013                UE = BasePtr->use_end(); UI != UE; ++UI) {
14014             if (UI->getOpcode() == ISD::ADD &&
14015                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14016                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14017                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14018                 (1ULL << Bits) == 0) {
14019               SDNode *OtherAdd = *UI;
14020               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14021                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14022                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14023                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14024                   return SDValue(*VI, 0);
14025                 }
14026               }
14027             }
14028           }
14029         }
14030       }
14031 
14032       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14033       // Expose the vabsduw/h/b opportunity for down stream
14034       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14035           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14036            IID == Intrinsic::ppc_altivec_vmaxsh ||
14037            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14038         SDValue V1 = N->getOperand(1);
14039         SDValue V2 = N->getOperand(2);
14040         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14041              V1.getSimpleValueType() == MVT::v8i16 ||
14042              V1.getSimpleValueType() == MVT::v16i8) &&
14043             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14044           // (0-a, a)
14045           if (V1.getOpcode() == ISD::SUB &&
14046               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14047               V1.getOperand(1) == V2) {
14048             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14049           }
14050           // (a, 0-a)
14051           if (V2.getOpcode() == ISD::SUB &&
14052               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14053               V2.getOperand(1) == V1) {
14054             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14055           }
14056           // (x-y, y-x)
14057           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14058               V1.getOperand(0) == V2.getOperand(1) &&
14059               V1.getOperand(1) == V2.getOperand(0)) {
14060             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14061           }
14062         }
14063       }
14064     }
14065 
14066     break;
14067   case ISD::INTRINSIC_W_CHAIN:
14068     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14069     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14070     if (Subtarget.needsSwapsForVSXMemOps()) {
14071       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14072       default:
14073         break;
14074       case Intrinsic::ppc_vsx_lxvw4x:
14075       case Intrinsic::ppc_vsx_lxvd2x:
14076         return expandVSXLoadForLE(N, DCI);
14077       }
14078     }
14079     break;
14080   case ISD::INTRINSIC_VOID:
14081     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14082     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14083     if (Subtarget.needsSwapsForVSXMemOps()) {
14084       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14085       default:
14086         break;
14087       case Intrinsic::ppc_vsx_stxvw4x:
14088       case Intrinsic::ppc_vsx_stxvd2x:
14089         return expandVSXStoreForLE(N, DCI);
14090       }
14091     }
14092     break;
14093   case ISD::BSWAP:
14094     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14095     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14096         N->getOperand(0).hasOneUse() &&
14097         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14098          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14099           N->getValueType(0) == MVT::i64))) {
14100       SDValue Load = N->getOperand(0);
14101       LoadSDNode *LD = cast<LoadSDNode>(Load);
14102       // Create the byte-swapping load.
14103       SDValue Ops[] = {
14104         LD->getChain(),    // Chain
14105         LD->getBasePtr(),  // Ptr
14106         DAG.getValueType(N->getValueType(0)) // VT
14107       };
14108       SDValue BSLoad =
14109         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14110                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14111                                               MVT::i64 : MVT::i32, MVT::Other),
14112                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14113 
14114       // If this is an i16 load, insert the truncate.
14115       SDValue ResVal = BSLoad;
14116       if (N->getValueType(0) == MVT::i16)
14117         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14118 
14119       // First, combine the bswap away.  This makes the value produced by the
14120       // load dead.
14121       DCI.CombineTo(N, ResVal);
14122 
14123       // Next, combine the load away, we give it a bogus result value but a real
14124       // chain result.  The result value is dead because the bswap is dead.
14125       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14126 
14127       // Return N so it doesn't get rechecked!
14128       return SDValue(N, 0);
14129     }
14130     break;
14131   case PPCISD::VCMP:
14132     // If a VCMPo node already exists with exactly the same operands as this
14133     // node, use its result instead of this node (VCMPo computes both a CR6 and
14134     // a normal output).
14135     //
14136     if (!N->getOperand(0).hasOneUse() &&
14137         !N->getOperand(1).hasOneUse() &&
14138         !N->getOperand(2).hasOneUse()) {
14139 
14140       // Scan all of the users of the LHS, looking for VCMPo's that match.
14141       SDNode *VCMPoNode = nullptr;
14142 
14143       SDNode *LHSN = N->getOperand(0).getNode();
14144       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14145            UI != E; ++UI)
14146         if (UI->getOpcode() == PPCISD::VCMPo &&
14147             UI->getOperand(1) == N->getOperand(1) &&
14148             UI->getOperand(2) == N->getOperand(2) &&
14149             UI->getOperand(0) == N->getOperand(0)) {
14150           VCMPoNode = *UI;
14151           break;
14152         }
14153 
14154       // If there is no VCMPo node, or if the flag value has a single use, don't
14155       // transform this.
14156       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14157         break;
14158 
14159       // Look at the (necessarily single) use of the flag value.  If it has a
14160       // chain, this transformation is more complex.  Note that multiple things
14161       // could use the value result, which we should ignore.
14162       SDNode *FlagUser = nullptr;
14163       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14164            FlagUser == nullptr; ++UI) {
14165         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14166         SDNode *User = *UI;
14167         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14168           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14169             FlagUser = User;
14170             break;
14171           }
14172         }
14173       }
14174 
14175       // If the user is a MFOCRF instruction, we know this is safe.
14176       // Otherwise we give up for right now.
14177       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14178         return SDValue(VCMPoNode, 0);
14179     }
14180     break;
14181   case ISD::BRCOND: {
14182     SDValue Cond = N->getOperand(1);
14183     SDValue Target = N->getOperand(2);
14184 
14185     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14186         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14187           Intrinsic::loop_decrement) {
14188 
14189       // We now need to make the intrinsic dead (it cannot be instruction
14190       // selected).
14191       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14192       assert(Cond.getNode()->hasOneUse() &&
14193              "Counter decrement has more than one use");
14194 
14195       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14196                          N->getOperand(0), Target);
14197     }
14198   }
14199   break;
14200   case ISD::BR_CC: {
14201     // If this is a branch on an altivec predicate comparison, lower this so
14202     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14203     // lowering is done pre-legalize, because the legalizer lowers the predicate
14204     // compare down to code that is difficult to reassemble.
14205     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14206     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14207 
14208     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14209     // value. If so, pass-through the AND to get to the intrinsic.
14210     if (LHS.getOpcode() == ISD::AND &&
14211         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14212         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14213           Intrinsic::loop_decrement &&
14214         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14215         !isNullConstant(LHS.getOperand(1)))
14216       LHS = LHS.getOperand(0);
14217 
14218     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14219         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14220           Intrinsic::loop_decrement &&
14221         isa<ConstantSDNode>(RHS)) {
14222       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14223              "Counter decrement comparison is not EQ or NE");
14224 
14225       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14226       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14227                     (CC == ISD::SETNE && !Val);
14228 
14229       // We now need to make the intrinsic dead (it cannot be instruction
14230       // selected).
14231       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14232       assert(LHS.getNode()->hasOneUse() &&
14233              "Counter decrement has more than one use");
14234 
14235       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14236                          N->getOperand(0), N->getOperand(4));
14237     }
14238 
14239     int CompareOpc;
14240     bool isDot;
14241 
14242     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14243         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14244         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14245       assert(isDot && "Can't compare against a vector result!");
14246 
14247       // If this is a comparison against something other than 0/1, then we know
14248       // that the condition is never/always true.
14249       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14250       if (Val != 0 && Val != 1) {
14251         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14252           return N->getOperand(0);
14253         // Always !=, turn it into an unconditional branch.
14254         return DAG.getNode(ISD::BR, dl, MVT::Other,
14255                            N->getOperand(0), N->getOperand(4));
14256       }
14257 
14258       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14259 
14260       // Create the PPCISD altivec 'dot' comparison node.
14261       SDValue Ops[] = {
14262         LHS.getOperand(2),  // LHS of compare
14263         LHS.getOperand(3),  // RHS of compare
14264         DAG.getConstant(CompareOpc, dl, MVT::i32)
14265       };
14266       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14267       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14268 
14269       // Unpack the result based on how the target uses it.
14270       PPC::Predicate CompOpc;
14271       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14272       default:  // Can't happen, don't crash on invalid number though.
14273       case 0:   // Branch on the value of the EQ bit of CR6.
14274         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14275         break;
14276       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14277         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14278         break;
14279       case 2:   // Branch on the value of the LT bit of CR6.
14280         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14281         break;
14282       case 3:   // Branch on the inverted value of the LT bit of CR6.
14283         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14284         break;
14285       }
14286 
14287       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14288                          DAG.getConstant(CompOpc, dl, MVT::i32),
14289                          DAG.getRegister(PPC::CR6, MVT::i32),
14290                          N->getOperand(4), CompNode.getValue(1));
14291     }
14292     break;
14293   }
14294   case ISD::BUILD_VECTOR:
14295     return DAGCombineBuildVector(N, DCI);
14296   case ISD::ABS:
14297     return combineABS(N, DCI);
14298   case ISD::VSELECT:
14299     return combineVSelect(N, DCI);
14300   }
14301 
14302   return SDValue();
14303 }
14304 
14305 SDValue
14306 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14307                                  SelectionDAG &DAG,
14308                                  SmallVectorImpl<SDNode *> &Created) const {
14309   // fold (sdiv X, pow2)
14310   EVT VT = N->getValueType(0);
14311   if (VT == MVT::i64 && !Subtarget.isPPC64())
14312     return SDValue();
14313   if ((VT != MVT::i32 && VT != MVT::i64) ||
14314       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14315     return SDValue();
14316 
14317   SDLoc DL(N);
14318   SDValue N0 = N->getOperand(0);
14319 
14320   bool IsNegPow2 = (-Divisor).isPowerOf2();
14321   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14322   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14323 
14324   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14325   Created.push_back(Op.getNode());
14326 
14327   if (IsNegPow2) {
14328     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14329     Created.push_back(Op.getNode());
14330   }
14331 
14332   return Op;
14333 }
14334 
14335 //===----------------------------------------------------------------------===//
14336 // Inline Assembly Support
14337 //===----------------------------------------------------------------------===//
14338 
14339 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14340                                                       KnownBits &Known,
14341                                                       const APInt &DemandedElts,
14342                                                       const SelectionDAG &DAG,
14343                                                       unsigned Depth) const {
14344   Known.resetAll();
14345   switch (Op.getOpcode()) {
14346   default: break;
14347   case PPCISD::LBRX: {
14348     // lhbrx is known to have the top bits cleared out.
14349     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14350       Known.Zero = 0xFFFF0000;
14351     break;
14352   }
14353   case ISD::INTRINSIC_WO_CHAIN: {
14354     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14355     default: break;
14356     case Intrinsic::ppc_altivec_vcmpbfp_p:
14357     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14358     case Intrinsic::ppc_altivec_vcmpequb_p:
14359     case Intrinsic::ppc_altivec_vcmpequh_p:
14360     case Intrinsic::ppc_altivec_vcmpequw_p:
14361     case Intrinsic::ppc_altivec_vcmpequd_p:
14362     case Intrinsic::ppc_altivec_vcmpgefp_p:
14363     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14364     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14365     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14366     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14367     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14368     case Intrinsic::ppc_altivec_vcmpgtub_p:
14369     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14370     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14371     case Intrinsic::ppc_altivec_vcmpgtud_p:
14372       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14373       break;
14374     }
14375   }
14376   }
14377 }
14378 
14379 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14380   switch (Subtarget.getCPUDirective()) {
14381   default: break;
14382   case PPC::DIR_970:
14383   case PPC::DIR_PWR4:
14384   case PPC::DIR_PWR5:
14385   case PPC::DIR_PWR5X:
14386   case PPC::DIR_PWR6:
14387   case PPC::DIR_PWR6X:
14388   case PPC::DIR_PWR7:
14389   case PPC::DIR_PWR8:
14390   case PPC::DIR_PWR9:
14391   case PPC::DIR_PWR_FUTURE: {
14392     if (!ML)
14393       break;
14394 
14395     if (!DisableInnermostLoopAlign32) {
14396       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14397       // so that we can decrease cache misses and branch-prediction misses.
14398       // Actual alignment of the loop will depend on the hotness check and other
14399       // logic in alignBlocks.
14400       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14401         return Align(32);
14402     }
14403 
14404     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14405 
14406     // For small loops (between 5 and 8 instructions), align to a 32-byte
14407     // boundary so that the entire loop fits in one instruction-cache line.
14408     uint64_t LoopSize = 0;
14409     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14410       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14411         LoopSize += TII->getInstSizeInBytes(*J);
14412         if (LoopSize > 32)
14413           break;
14414       }
14415 
14416     if (LoopSize > 16 && LoopSize <= 32)
14417       return Align(32);
14418 
14419     break;
14420   }
14421   }
14422 
14423   return TargetLowering::getPrefLoopAlignment(ML);
14424 }
14425 
14426 /// getConstraintType - Given a constraint, return the type of
14427 /// constraint it is for this target.
14428 PPCTargetLowering::ConstraintType
14429 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14430   if (Constraint.size() == 1) {
14431     switch (Constraint[0]) {
14432     default: break;
14433     case 'b':
14434     case 'r':
14435     case 'f':
14436     case 'd':
14437     case 'v':
14438     case 'y':
14439       return C_RegisterClass;
14440     case 'Z':
14441       // FIXME: While Z does indicate a memory constraint, it specifically
14442       // indicates an r+r address (used in conjunction with the 'y' modifier
14443       // in the replacement string). Currently, we're forcing the base
14444       // register to be r0 in the asm printer (which is interpreted as zero)
14445       // and forming the complete address in the second register. This is
14446       // suboptimal.
14447       return C_Memory;
14448     }
14449   } else if (Constraint == "wc") { // individual CR bits.
14450     return C_RegisterClass;
14451   } else if (Constraint == "wa" || Constraint == "wd" ||
14452              Constraint == "wf" || Constraint == "ws" ||
14453              Constraint == "wi" || Constraint == "ww") {
14454     return C_RegisterClass; // VSX registers.
14455   }
14456   return TargetLowering::getConstraintType(Constraint);
14457 }
14458 
14459 /// Examine constraint type and operand type and determine a weight value.
14460 /// This object must already have been set up with the operand type
14461 /// and the current alternative constraint selected.
14462 TargetLowering::ConstraintWeight
14463 PPCTargetLowering::getSingleConstraintMatchWeight(
14464     AsmOperandInfo &info, const char *constraint) const {
14465   ConstraintWeight weight = CW_Invalid;
14466   Value *CallOperandVal = info.CallOperandVal;
14467     // If we don't have a value, we can't do a match,
14468     // but allow it at the lowest weight.
14469   if (!CallOperandVal)
14470     return CW_Default;
14471   Type *type = CallOperandVal->getType();
14472 
14473   // Look at the constraint type.
14474   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14475     return CW_Register; // an individual CR bit.
14476   else if ((StringRef(constraint) == "wa" ||
14477             StringRef(constraint) == "wd" ||
14478             StringRef(constraint) == "wf") &&
14479            type->isVectorTy())
14480     return CW_Register;
14481   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14482     return CW_Register; // just hold 64-bit integers data.
14483   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14484     return CW_Register;
14485   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14486     return CW_Register;
14487 
14488   switch (*constraint) {
14489   default:
14490     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14491     break;
14492   case 'b':
14493     if (type->isIntegerTy())
14494       weight = CW_Register;
14495     break;
14496   case 'f':
14497     if (type->isFloatTy())
14498       weight = CW_Register;
14499     break;
14500   case 'd':
14501     if (type->isDoubleTy())
14502       weight = CW_Register;
14503     break;
14504   case 'v':
14505     if (type->isVectorTy())
14506       weight = CW_Register;
14507     break;
14508   case 'y':
14509     weight = CW_Register;
14510     break;
14511   case 'Z':
14512     weight = CW_Memory;
14513     break;
14514   }
14515   return weight;
14516 }
14517 
14518 std::pair<unsigned, const TargetRegisterClass *>
14519 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14520                                                 StringRef Constraint,
14521                                                 MVT VT) const {
14522   if (Constraint.size() == 1) {
14523     // GCC RS6000 Constraint Letters
14524     switch (Constraint[0]) {
14525     case 'b':   // R1-R31
14526       if (VT == MVT::i64 && Subtarget.isPPC64())
14527         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14528       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14529     case 'r':   // R0-R31
14530       if (VT == MVT::i64 && Subtarget.isPPC64())
14531         return std::make_pair(0U, &PPC::G8RCRegClass);
14532       return std::make_pair(0U, &PPC::GPRCRegClass);
14533     // 'd' and 'f' constraints are both defined to be "the floating point
14534     // registers", where one is for 32-bit and the other for 64-bit. We don't
14535     // really care overly much here so just give them all the same reg classes.
14536     case 'd':
14537     case 'f':
14538       if (Subtarget.hasSPE()) {
14539         if (VT == MVT::f32 || VT == MVT::i32)
14540           return std::make_pair(0U, &PPC::GPRCRegClass);
14541         if (VT == MVT::f64 || VT == MVT::i64)
14542           return std::make_pair(0U, &PPC::SPERCRegClass);
14543       } else {
14544         if (VT == MVT::f32 || VT == MVT::i32)
14545           return std::make_pair(0U, &PPC::F4RCRegClass);
14546         if (VT == MVT::f64 || VT == MVT::i64)
14547           return std::make_pair(0U, &PPC::F8RCRegClass);
14548         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14549           return std::make_pair(0U, &PPC::QFRCRegClass);
14550         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14551           return std::make_pair(0U, &PPC::QSRCRegClass);
14552       }
14553       break;
14554     case 'v':
14555       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14556         return std::make_pair(0U, &PPC::QFRCRegClass);
14557       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14558         return std::make_pair(0U, &PPC::QSRCRegClass);
14559       if (Subtarget.hasAltivec())
14560         return std::make_pair(0U, &PPC::VRRCRegClass);
14561       break;
14562     case 'y':   // crrc
14563       return std::make_pair(0U, &PPC::CRRCRegClass);
14564     }
14565   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14566     // An individual CR bit.
14567     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14568   } else if ((Constraint == "wa" || Constraint == "wd" ||
14569              Constraint == "wf" || Constraint == "wi") &&
14570              Subtarget.hasVSX()) {
14571     return std::make_pair(0U, &PPC::VSRCRegClass);
14572   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14573     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14574       return std::make_pair(0U, &PPC::VSSRCRegClass);
14575     else
14576       return std::make_pair(0U, &PPC::VSFRCRegClass);
14577   }
14578 
14579   // If we name a VSX register, we can't defer to the base class because it
14580   // will not recognize the correct register (their names will be VSL{0-31}
14581   // and V{0-31} so they won't match). So we match them here.
14582   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
14583     int VSNum = atoi(Constraint.data() + 3);
14584     assert(VSNum >= 0 && VSNum <= 63 &&
14585            "Attempted to access a vsr out of range");
14586     if (VSNum < 32)
14587       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
14588     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
14589   }
14590   std::pair<unsigned, const TargetRegisterClass *> R =
14591       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14592 
14593   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14594   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14595   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14596   // register.
14597   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14598   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14599   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14600       PPC::GPRCRegClass.contains(R.first))
14601     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14602                             PPC::sub_32, &PPC::G8RCRegClass),
14603                           &PPC::G8RCRegClass);
14604 
14605   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14606   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14607     R.first = PPC::CR0;
14608     R.second = &PPC::CRRCRegClass;
14609   }
14610 
14611   return R;
14612 }
14613 
14614 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14615 /// vector.  If it is invalid, don't add anything to Ops.
14616 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14617                                                      std::string &Constraint,
14618                                                      std::vector<SDValue>&Ops,
14619                                                      SelectionDAG &DAG) const {
14620   SDValue Result;
14621 
14622   // Only support length 1 constraints.
14623   if (Constraint.length() > 1) return;
14624 
14625   char Letter = Constraint[0];
14626   switch (Letter) {
14627   default: break;
14628   case 'I':
14629   case 'J':
14630   case 'K':
14631   case 'L':
14632   case 'M':
14633   case 'N':
14634   case 'O':
14635   case 'P': {
14636     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14637     if (!CST) return; // Must be an immediate to match.
14638     SDLoc dl(Op);
14639     int64_t Value = CST->getSExtValue();
14640     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14641                          // numbers are printed as such.
14642     switch (Letter) {
14643     default: llvm_unreachable("Unknown constraint letter!");
14644     case 'I':  // "I" is a signed 16-bit constant.
14645       if (isInt<16>(Value))
14646         Result = DAG.getTargetConstant(Value, dl, TCVT);
14647       break;
14648     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14649       if (isShiftedUInt<16, 16>(Value))
14650         Result = DAG.getTargetConstant(Value, dl, TCVT);
14651       break;
14652     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14653       if (isShiftedInt<16, 16>(Value))
14654         Result = DAG.getTargetConstant(Value, dl, TCVT);
14655       break;
14656     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14657       if (isUInt<16>(Value))
14658         Result = DAG.getTargetConstant(Value, dl, TCVT);
14659       break;
14660     case 'M':  // "M" is a constant that is greater than 31.
14661       if (Value > 31)
14662         Result = DAG.getTargetConstant(Value, dl, TCVT);
14663       break;
14664     case 'N':  // "N" is a positive constant that is an exact power of two.
14665       if (Value > 0 && isPowerOf2_64(Value))
14666         Result = DAG.getTargetConstant(Value, dl, TCVT);
14667       break;
14668     case 'O':  // "O" is the constant zero.
14669       if (Value == 0)
14670         Result = DAG.getTargetConstant(Value, dl, TCVT);
14671       break;
14672     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14673       if (isInt<16>(-Value))
14674         Result = DAG.getTargetConstant(Value, dl, TCVT);
14675       break;
14676     }
14677     break;
14678   }
14679   }
14680 
14681   if (Result.getNode()) {
14682     Ops.push_back(Result);
14683     return;
14684   }
14685 
14686   // Handle standard constraint letters.
14687   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14688 }
14689 
14690 // isLegalAddressingMode - Return true if the addressing mode represented
14691 // by AM is legal for this target, for a load/store of the specified type.
14692 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14693                                               const AddrMode &AM, Type *Ty,
14694                                               unsigned AS, Instruction *I) const {
14695   // PPC does not allow r+i addressing modes for vectors!
14696   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14697     return false;
14698 
14699   // PPC allows a sign-extended 16-bit immediate field.
14700   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14701     return false;
14702 
14703   // No global is ever allowed as a base.
14704   if (AM.BaseGV)
14705     return false;
14706 
14707   // PPC only support r+r,
14708   switch (AM.Scale) {
14709   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14710     break;
14711   case 1:
14712     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14713       return false;
14714     // Otherwise we have r+r or r+i.
14715     break;
14716   case 2:
14717     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14718       return false;
14719     // Allow 2*r as r+r.
14720     break;
14721   default:
14722     // No other scales are supported.
14723     return false;
14724   }
14725 
14726   return true;
14727 }
14728 
14729 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14730                                            SelectionDAG &DAG) const {
14731   MachineFunction &MF = DAG.getMachineFunction();
14732   MachineFrameInfo &MFI = MF.getFrameInfo();
14733   MFI.setReturnAddressIsTaken(true);
14734 
14735   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14736     return SDValue();
14737 
14738   SDLoc dl(Op);
14739   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14740 
14741   // Make sure the function does not optimize away the store of the RA to
14742   // the stack.
14743   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14744   FuncInfo->setLRStoreRequired();
14745   bool isPPC64 = Subtarget.isPPC64();
14746   auto PtrVT = getPointerTy(MF.getDataLayout());
14747 
14748   if (Depth > 0) {
14749     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14750     SDValue Offset =
14751         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14752                         isPPC64 ? MVT::i64 : MVT::i32);
14753     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14754                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14755                        MachinePointerInfo());
14756   }
14757 
14758   // Just load the return address off the stack.
14759   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14760   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14761                      MachinePointerInfo());
14762 }
14763 
14764 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14765                                           SelectionDAG &DAG) const {
14766   SDLoc dl(Op);
14767   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14768 
14769   MachineFunction &MF = DAG.getMachineFunction();
14770   MachineFrameInfo &MFI = MF.getFrameInfo();
14771   MFI.setFrameAddressIsTaken(true);
14772 
14773   EVT PtrVT = getPointerTy(MF.getDataLayout());
14774   bool isPPC64 = PtrVT == MVT::i64;
14775 
14776   // Naked functions never have a frame pointer, and so we use r1. For all
14777   // other functions, this decision must be delayed until during PEI.
14778   unsigned FrameReg;
14779   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14780     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14781   else
14782     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14783 
14784   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14785                                          PtrVT);
14786   while (Depth--)
14787     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14788                             FrameAddr, MachinePointerInfo());
14789   return FrameAddr;
14790 }
14791 
14792 // FIXME? Maybe this could be a TableGen attribute on some registers and
14793 // this table could be generated automatically from RegInfo.
14794 Register PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
14795                                               const MachineFunction &MF) const {
14796   bool isPPC64 = Subtarget.isPPC64();
14797   bool IsDarwinABI = Subtarget.isDarwinABI();
14798 
14799   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
14800       (!isPPC64 && VT != MVT::i32))
14801     report_fatal_error("Invalid register global variable type");
14802 
14803   bool is64Bit = isPPC64 && VT == MVT::i64;
14804   Register Reg = StringSwitch<Register>(RegName)
14805                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14806                    .Case("r2", (IsDarwinABI || isPPC64) ? Register() : PPC::R2)
14807                    .Case("r13", (!isPPC64 && IsDarwinABI) ? Register() :
14808                                   (is64Bit ? PPC::X13 : PPC::R13))
14809                    .Default(Register());
14810 
14811   if (Reg)
14812     return Reg;
14813   report_fatal_error("Invalid register name global variable");
14814 }
14815 
14816 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14817   // 32-bit SVR4 ABI access everything as got-indirect.
14818   if (Subtarget.is32BitELFABI())
14819     return true;
14820 
14821   // AIX accesses everything indirectly through the TOC, which is similar to
14822   // the GOT.
14823   if (Subtarget.isAIXABI())
14824     return true;
14825 
14826   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14827   // If it is small or large code model, module locals are accessed
14828   // indirectly by loading their address from .toc/.got.
14829   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14830     return true;
14831 
14832   // JumpTable and BlockAddress are accessed as got-indirect.
14833   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14834     return true;
14835 
14836   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
14837     return Subtarget.isGVIndirectSymbol(G->getGlobal());
14838 
14839   return false;
14840 }
14841 
14842 bool
14843 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14844   // The PowerPC target isn't yet aware of offsets.
14845   return false;
14846 }
14847 
14848 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14849                                            const CallInst &I,
14850                                            MachineFunction &MF,
14851                                            unsigned Intrinsic) const {
14852   switch (Intrinsic) {
14853   case Intrinsic::ppc_qpx_qvlfd:
14854   case Intrinsic::ppc_qpx_qvlfs:
14855   case Intrinsic::ppc_qpx_qvlfcd:
14856   case Intrinsic::ppc_qpx_qvlfcs:
14857   case Intrinsic::ppc_qpx_qvlfiwa:
14858   case Intrinsic::ppc_qpx_qvlfiwz:
14859   case Intrinsic::ppc_altivec_lvx:
14860   case Intrinsic::ppc_altivec_lvxl:
14861   case Intrinsic::ppc_altivec_lvebx:
14862   case Intrinsic::ppc_altivec_lvehx:
14863   case Intrinsic::ppc_altivec_lvewx:
14864   case Intrinsic::ppc_vsx_lxvd2x:
14865   case Intrinsic::ppc_vsx_lxvw4x: {
14866     EVT VT;
14867     switch (Intrinsic) {
14868     case Intrinsic::ppc_altivec_lvebx:
14869       VT = MVT::i8;
14870       break;
14871     case Intrinsic::ppc_altivec_lvehx:
14872       VT = MVT::i16;
14873       break;
14874     case Intrinsic::ppc_altivec_lvewx:
14875       VT = MVT::i32;
14876       break;
14877     case Intrinsic::ppc_vsx_lxvd2x:
14878       VT = MVT::v2f64;
14879       break;
14880     case Intrinsic::ppc_qpx_qvlfd:
14881       VT = MVT::v4f64;
14882       break;
14883     case Intrinsic::ppc_qpx_qvlfs:
14884       VT = MVT::v4f32;
14885       break;
14886     case Intrinsic::ppc_qpx_qvlfcd:
14887       VT = MVT::v2f64;
14888       break;
14889     case Intrinsic::ppc_qpx_qvlfcs:
14890       VT = MVT::v2f32;
14891       break;
14892     default:
14893       VT = MVT::v4i32;
14894       break;
14895     }
14896 
14897     Info.opc = ISD::INTRINSIC_W_CHAIN;
14898     Info.memVT = VT;
14899     Info.ptrVal = I.getArgOperand(0);
14900     Info.offset = -VT.getStoreSize()+1;
14901     Info.size = 2*VT.getStoreSize()-1;
14902     Info.align = Align::None();
14903     Info.flags = MachineMemOperand::MOLoad;
14904     return true;
14905   }
14906   case Intrinsic::ppc_qpx_qvlfda:
14907   case Intrinsic::ppc_qpx_qvlfsa:
14908   case Intrinsic::ppc_qpx_qvlfcda:
14909   case Intrinsic::ppc_qpx_qvlfcsa:
14910   case Intrinsic::ppc_qpx_qvlfiwaa:
14911   case Intrinsic::ppc_qpx_qvlfiwza: {
14912     EVT VT;
14913     switch (Intrinsic) {
14914     case Intrinsic::ppc_qpx_qvlfda:
14915       VT = MVT::v4f64;
14916       break;
14917     case Intrinsic::ppc_qpx_qvlfsa:
14918       VT = MVT::v4f32;
14919       break;
14920     case Intrinsic::ppc_qpx_qvlfcda:
14921       VT = MVT::v2f64;
14922       break;
14923     case Intrinsic::ppc_qpx_qvlfcsa:
14924       VT = MVT::v2f32;
14925       break;
14926     default:
14927       VT = MVT::v4i32;
14928       break;
14929     }
14930 
14931     Info.opc = ISD::INTRINSIC_W_CHAIN;
14932     Info.memVT = VT;
14933     Info.ptrVal = I.getArgOperand(0);
14934     Info.offset = 0;
14935     Info.size = VT.getStoreSize();
14936     Info.align = Align::None();
14937     Info.flags = MachineMemOperand::MOLoad;
14938     return true;
14939   }
14940   case Intrinsic::ppc_qpx_qvstfd:
14941   case Intrinsic::ppc_qpx_qvstfs:
14942   case Intrinsic::ppc_qpx_qvstfcd:
14943   case Intrinsic::ppc_qpx_qvstfcs:
14944   case Intrinsic::ppc_qpx_qvstfiw:
14945   case Intrinsic::ppc_altivec_stvx:
14946   case Intrinsic::ppc_altivec_stvxl:
14947   case Intrinsic::ppc_altivec_stvebx:
14948   case Intrinsic::ppc_altivec_stvehx:
14949   case Intrinsic::ppc_altivec_stvewx:
14950   case Intrinsic::ppc_vsx_stxvd2x:
14951   case Intrinsic::ppc_vsx_stxvw4x: {
14952     EVT VT;
14953     switch (Intrinsic) {
14954     case Intrinsic::ppc_altivec_stvebx:
14955       VT = MVT::i8;
14956       break;
14957     case Intrinsic::ppc_altivec_stvehx:
14958       VT = MVT::i16;
14959       break;
14960     case Intrinsic::ppc_altivec_stvewx:
14961       VT = MVT::i32;
14962       break;
14963     case Intrinsic::ppc_vsx_stxvd2x:
14964       VT = MVT::v2f64;
14965       break;
14966     case Intrinsic::ppc_qpx_qvstfd:
14967       VT = MVT::v4f64;
14968       break;
14969     case Intrinsic::ppc_qpx_qvstfs:
14970       VT = MVT::v4f32;
14971       break;
14972     case Intrinsic::ppc_qpx_qvstfcd:
14973       VT = MVT::v2f64;
14974       break;
14975     case Intrinsic::ppc_qpx_qvstfcs:
14976       VT = MVT::v2f32;
14977       break;
14978     default:
14979       VT = MVT::v4i32;
14980       break;
14981     }
14982 
14983     Info.opc = ISD::INTRINSIC_VOID;
14984     Info.memVT = VT;
14985     Info.ptrVal = I.getArgOperand(1);
14986     Info.offset = -VT.getStoreSize()+1;
14987     Info.size = 2*VT.getStoreSize()-1;
14988     Info.align = Align::None();
14989     Info.flags = MachineMemOperand::MOStore;
14990     return true;
14991   }
14992   case Intrinsic::ppc_qpx_qvstfda:
14993   case Intrinsic::ppc_qpx_qvstfsa:
14994   case Intrinsic::ppc_qpx_qvstfcda:
14995   case Intrinsic::ppc_qpx_qvstfcsa:
14996   case Intrinsic::ppc_qpx_qvstfiwa: {
14997     EVT VT;
14998     switch (Intrinsic) {
14999     case Intrinsic::ppc_qpx_qvstfda:
15000       VT = MVT::v4f64;
15001       break;
15002     case Intrinsic::ppc_qpx_qvstfsa:
15003       VT = MVT::v4f32;
15004       break;
15005     case Intrinsic::ppc_qpx_qvstfcda:
15006       VT = MVT::v2f64;
15007       break;
15008     case Intrinsic::ppc_qpx_qvstfcsa:
15009       VT = MVT::v2f32;
15010       break;
15011     default:
15012       VT = MVT::v4i32;
15013       break;
15014     }
15015 
15016     Info.opc = ISD::INTRINSIC_VOID;
15017     Info.memVT = VT;
15018     Info.ptrVal = I.getArgOperand(1);
15019     Info.offset = 0;
15020     Info.size = VT.getStoreSize();
15021     Info.align = Align::None();
15022     Info.flags = MachineMemOperand::MOStore;
15023     return true;
15024   }
15025   default:
15026     break;
15027   }
15028 
15029   return false;
15030 }
15031 
15032 /// getOptimalMemOpType - Returns the target specific optimal type for load
15033 /// and store operations as a result of memset, memcpy, and memmove
15034 /// lowering. If DstAlign is zero that means it's safe to destination
15035 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
15036 /// means there isn't a need to check it against alignment requirement,
15037 /// probably because the source does not need to be loaded. If 'IsMemset' is
15038 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
15039 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
15040 /// source is constant so it does not need to be loaded.
15041 /// It returns EVT::Other if the type should be determined using generic
15042 /// target-independent logic.
15043 EVT PPCTargetLowering::getOptimalMemOpType(
15044     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
15045     bool ZeroMemset, bool MemcpyStrSrc,
15046     const AttributeList &FuncAttributes) const {
15047   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15048     // When expanding a memset, require at least two QPX instructions to cover
15049     // the cost of loading the value to be stored from the constant pool.
15050     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
15051        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
15052         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15053       return MVT::v4f64;
15054     }
15055 
15056     // We should use Altivec/VSX loads and stores when available. For unaligned
15057     // addresses, unaligned VSX loads are only fast starting with the P8.
15058     if (Subtarget.hasAltivec() && Size >= 16 &&
15059         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
15060          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15061       return MVT::v4i32;
15062   }
15063 
15064   if (Subtarget.isPPC64()) {
15065     return MVT::i64;
15066   }
15067 
15068   return MVT::i32;
15069 }
15070 
15071 /// Returns true if it is beneficial to convert a load of a constant
15072 /// to just the constant itself.
15073 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15074                                                           Type *Ty) const {
15075   assert(Ty->isIntegerTy());
15076 
15077   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15078   return !(BitSize == 0 || BitSize > 64);
15079 }
15080 
15081 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15082   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15083     return false;
15084   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15085   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15086   return NumBits1 == 64 && NumBits2 == 32;
15087 }
15088 
15089 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15090   if (!VT1.isInteger() || !VT2.isInteger())
15091     return false;
15092   unsigned NumBits1 = VT1.getSizeInBits();
15093   unsigned NumBits2 = VT2.getSizeInBits();
15094   return NumBits1 == 64 && NumBits2 == 32;
15095 }
15096 
15097 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15098   // Generally speaking, zexts are not free, but they are free when they can be
15099   // folded with other operations.
15100   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15101     EVT MemVT = LD->getMemoryVT();
15102     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15103          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15104         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15105          LD->getExtensionType() == ISD::ZEXTLOAD))
15106       return true;
15107   }
15108 
15109   // FIXME: Add other cases...
15110   //  - 32-bit shifts with a zext to i64
15111   //  - zext after ctlz, bswap, etc.
15112   //  - zext after and by a constant mask
15113 
15114   return TargetLowering::isZExtFree(Val, VT2);
15115 }
15116 
15117 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15118   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15119          "invalid fpext types");
15120   // Extending to float128 is not free.
15121   if (DestVT == MVT::f128)
15122     return false;
15123   return true;
15124 }
15125 
15126 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15127   return isInt<16>(Imm) || isUInt<16>(Imm);
15128 }
15129 
15130 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15131   return isInt<16>(Imm) || isUInt<16>(Imm);
15132 }
15133 
15134 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15135                                                        unsigned,
15136                                                        unsigned,
15137                                                        MachineMemOperand::Flags,
15138                                                        bool *Fast) const {
15139   if (DisablePPCUnaligned)
15140     return false;
15141 
15142   // PowerPC supports unaligned memory access for simple non-vector types.
15143   // Although accessing unaligned addresses is not as efficient as accessing
15144   // aligned addresses, it is generally more efficient than manual expansion,
15145   // and generally only traps for software emulation when crossing page
15146   // boundaries.
15147 
15148   if (!VT.isSimple())
15149     return false;
15150 
15151   if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess())
15152     return false;
15153 
15154   if (VT.getSimpleVT().isVector()) {
15155     if (Subtarget.hasVSX()) {
15156       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15157           VT != MVT::v4f32 && VT != MVT::v4i32)
15158         return false;
15159     } else {
15160       return false;
15161     }
15162   }
15163 
15164   if (VT == MVT::ppcf128)
15165     return false;
15166 
15167   if (Fast)
15168     *Fast = true;
15169 
15170   return true;
15171 }
15172 
15173 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15174                                                    EVT VT) const {
15175   VT = VT.getScalarType();
15176 
15177   if (!VT.isSimple())
15178     return false;
15179 
15180   switch (VT.getSimpleVT().SimpleTy) {
15181   case MVT::f32:
15182   case MVT::f64:
15183     return true;
15184   case MVT::f128:
15185     return (EnableQuadPrecision && Subtarget.hasP9Vector());
15186   default:
15187     break;
15188   }
15189 
15190   return false;
15191 }
15192 
15193 const MCPhysReg *
15194 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15195   // LR is a callee-save register, but we must treat it as clobbered by any call
15196   // site. Hence we include LR in the scratch registers, which are in turn added
15197   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15198   // to CTR, which is used by any indirect call.
15199   static const MCPhysReg ScratchRegs[] = {
15200     PPC::X12, PPC::LR8, PPC::CTR8, 0
15201   };
15202 
15203   return ScratchRegs;
15204 }
15205 
15206 unsigned PPCTargetLowering::getExceptionPointerRegister(
15207     const Constant *PersonalityFn) const {
15208   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15209 }
15210 
15211 unsigned PPCTargetLowering::getExceptionSelectorRegister(
15212     const Constant *PersonalityFn) const {
15213   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15214 }
15215 
15216 bool
15217 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15218                      EVT VT , unsigned DefinedValues) const {
15219   if (VT == MVT::v2i64)
15220     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15221 
15222   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15223     return true;
15224 
15225   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15226 }
15227 
15228 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15229   if (DisableILPPref || Subtarget.enableMachineScheduler())
15230     return TargetLowering::getSchedulingPreference(N);
15231 
15232   return Sched::ILP;
15233 }
15234 
15235 // Create a fast isel object.
15236 FastISel *
15237 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15238                                   const TargetLibraryInfo *LibInfo) const {
15239   return PPC::createFastISel(FuncInfo, LibInfo);
15240 }
15241 
15242 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15243   if (Subtarget.isDarwinABI()) return;
15244   if (!Subtarget.isPPC64()) return;
15245 
15246   // Update IsSplitCSR in PPCFunctionInfo
15247   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15248   PFI->setIsSplitCSR(true);
15249 }
15250 
15251 void PPCTargetLowering::insertCopiesSplitCSR(
15252   MachineBasicBlock *Entry,
15253   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15254   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15255   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15256   if (!IStart)
15257     return;
15258 
15259   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15260   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15261   MachineBasicBlock::iterator MBBI = Entry->begin();
15262   for (const MCPhysReg *I = IStart; *I; ++I) {
15263     const TargetRegisterClass *RC = nullptr;
15264     if (PPC::G8RCRegClass.contains(*I))
15265       RC = &PPC::G8RCRegClass;
15266     else if (PPC::F8RCRegClass.contains(*I))
15267       RC = &PPC::F8RCRegClass;
15268     else if (PPC::CRRCRegClass.contains(*I))
15269       RC = &PPC::CRRCRegClass;
15270     else if (PPC::VRRCRegClass.contains(*I))
15271       RC = &PPC::VRRCRegClass;
15272     else
15273       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15274 
15275     Register NewVR = MRI->createVirtualRegister(RC);
15276     // Create copy from CSR to a virtual register.
15277     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15278     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15279     // nounwind. If we want to generalize this later, we may need to emit
15280     // CFI pseudo-instructions.
15281     assert(Entry->getParent()->getFunction().hasFnAttribute(
15282              Attribute::NoUnwind) &&
15283            "Function should be nounwind in insertCopiesSplitCSR!");
15284     Entry->addLiveIn(*I);
15285     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15286       .addReg(*I);
15287 
15288     // Insert the copy-back instructions right before the terminator.
15289     for (auto *Exit : Exits)
15290       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15291               TII->get(TargetOpcode::COPY), *I)
15292         .addReg(NewVR);
15293   }
15294 }
15295 
15296 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15297 bool PPCTargetLowering::useLoadStackGuardNode() const {
15298   if (!Subtarget.isTargetLinux())
15299     return TargetLowering::useLoadStackGuardNode();
15300   return true;
15301 }
15302 
15303 // Override to disable global variable loading on Linux.
15304 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15305   if (!Subtarget.isTargetLinux())
15306     return TargetLowering::insertSSPDeclarations(M);
15307 }
15308 
15309 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15310                                      bool ForCodeSize) const {
15311   if (!VT.isSimple() || !Subtarget.hasVSX())
15312     return false;
15313 
15314   switch(VT.getSimpleVT().SimpleTy) {
15315   default:
15316     // For FP types that are currently not supported by PPC backend, return
15317     // false. Examples: f16, f80.
15318     return false;
15319   case MVT::f32:
15320   case MVT::f64:
15321   case MVT::ppcf128:
15322     return Imm.isPosZero();
15323   }
15324 }
15325 
15326 // For vector shift operation op, fold
15327 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15328 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15329                                   SelectionDAG &DAG) {
15330   SDValue N0 = N->getOperand(0);
15331   SDValue N1 = N->getOperand(1);
15332   EVT VT = N0.getValueType();
15333   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15334   unsigned Opcode = N->getOpcode();
15335   unsigned TargetOpcode;
15336 
15337   switch (Opcode) {
15338   default:
15339     llvm_unreachable("Unexpected shift operation");
15340   case ISD::SHL:
15341     TargetOpcode = PPCISD::SHL;
15342     break;
15343   case ISD::SRL:
15344     TargetOpcode = PPCISD::SRL;
15345     break;
15346   case ISD::SRA:
15347     TargetOpcode = PPCISD::SRA;
15348     break;
15349   }
15350 
15351   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15352       N1->getOpcode() == ISD::AND)
15353     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15354       if (Mask->getZExtValue() == OpSizeInBits - 1)
15355         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15356 
15357   return SDValue();
15358 }
15359 
15360 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15361   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15362     return Value;
15363 
15364   SDValue N0 = N->getOperand(0);
15365   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15366   if (!Subtarget.isISA3_0() ||
15367       N0.getOpcode() != ISD::SIGN_EXTEND ||
15368       N0.getOperand(0).getValueType() != MVT::i32 ||
15369       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15370     return SDValue();
15371 
15372   // We can't save an operation here if the value is already extended, and
15373   // the existing shift is easier to combine.
15374   SDValue ExtsSrc = N0.getOperand(0);
15375   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15376       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15377     return SDValue();
15378 
15379   SDLoc DL(N0);
15380   SDValue ShiftBy = SDValue(CN1, 0);
15381   // We want the shift amount to be i32 on the extswli, but the shift could
15382   // have an i64.
15383   if (ShiftBy.getValueType() == MVT::i64)
15384     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15385 
15386   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15387                          ShiftBy);
15388 }
15389 
15390 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15391   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15392     return Value;
15393 
15394   return SDValue();
15395 }
15396 
15397 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15398   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15399     return Value;
15400 
15401   return SDValue();
15402 }
15403 
15404 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15405 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15406 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15407 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15408 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15409                                  const PPCSubtarget &Subtarget) {
15410   if (!Subtarget.isPPC64())
15411     return SDValue();
15412 
15413   SDValue LHS = N->getOperand(0);
15414   SDValue RHS = N->getOperand(1);
15415 
15416   auto isZextOfCompareWithConstant = [](SDValue Op) {
15417     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15418         Op.getValueType() != MVT::i64)
15419       return false;
15420 
15421     SDValue Cmp = Op.getOperand(0);
15422     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15423         Cmp.getOperand(0).getValueType() != MVT::i64)
15424       return false;
15425 
15426     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15427       int64_t NegConstant = 0 - Constant->getSExtValue();
15428       // Due to the limitations of the addi instruction,
15429       // -C is required to be [-32768, 32767].
15430       return isInt<16>(NegConstant);
15431     }
15432 
15433     return false;
15434   };
15435 
15436   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15437   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15438 
15439   // If there is a pattern, canonicalize a zext operand to the RHS.
15440   if (LHSHasPattern && !RHSHasPattern)
15441     std::swap(LHS, RHS);
15442   else if (!LHSHasPattern && !RHSHasPattern)
15443     return SDValue();
15444 
15445   SDLoc DL(N);
15446   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15447   SDValue Cmp = RHS.getOperand(0);
15448   SDValue Z = Cmp.getOperand(0);
15449   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15450 
15451   assert(Constant && "Constant Should not be a null pointer.");
15452   int64_t NegConstant = 0 - Constant->getSExtValue();
15453 
15454   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15455   default: break;
15456   case ISD::SETNE: {
15457     //                                 when C == 0
15458     //                             --> addze X, (addic Z, -1).carry
15459     //                            /
15460     // add X, (zext(setne Z, C))--
15461     //                            \    when -32768 <= -C <= 32767 && C != 0
15462     //                             --> addze X, (addic (addi Z, -C), -1).carry
15463     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15464                               DAG.getConstant(NegConstant, DL, MVT::i64));
15465     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15466     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15467                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15468     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15469                        SDValue(Addc.getNode(), 1));
15470     }
15471   case ISD::SETEQ: {
15472     //                                 when C == 0
15473     //                             --> addze X, (subfic Z, 0).carry
15474     //                            /
15475     // add X, (zext(sete  Z, C))--
15476     //                            \    when -32768 <= -C <= 32767 && C != 0
15477     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15478     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15479                               DAG.getConstant(NegConstant, DL, MVT::i64));
15480     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15481     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15482                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15483     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15484                        SDValue(Subc.getNode(), 1));
15485     }
15486   }
15487 
15488   return SDValue();
15489 }
15490 
15491 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15492   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15493     return Value;
15494 
15495   return SDValue();
15496 }
15497 
15498 // Detect TRUNCATE operations on bitcasts of float128 values.
15499 // What we are looking for here is the situtation where we extract a subset
15500 // of bits from a 128 bit float.
15501 // This can be of two forms:
15502 // 1) BITCAST of f128 feeding TRUNCATE
15503 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15504 // The reason this is required is because we do not have a legal i128 type
15505 // and so we want to prevent having to store the f128 and then reload part
15506 // of it.
15507 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15508                                            DAGCombinerInfo &DCI) const {
15509   // If we are using CRBits then try that first.
15510   if (Subtarget.useCRBits()) {
15511     // Check if CRBits did anything and return that if it did.
15512     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15513       return CRTruncValue;
15514   }
15515 
15516   SDLoc dl(N);
15517   SDValue Op0 = N->getOperand(0);
15518 
15519   // Looking for a truncate of i128 to i64.
15520   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15521     return SDValue();
15522 
15523   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15524 
15525   // SRL feeding TRUNCATE.
15526   if (Op0.getOpcode() == ISD::SRL) {
15527     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15528     // The right shift has to be by 64 bits.
15529     if (!ConstNode || ConstNode->getZExtValue() != 64)
15530       return SDValue();
15531 
15532     // Switch the element number to extract.
15533     EltToExtract = EltToExtract ? 0 : 1;
15534     // Update Op0 past the SRL.
15535     Op0 = Op0.getOperand(0);
15536   }
15537 
15538   // BITCAST feeding a TRUNCATE possibly via SRL.
15539   if (Op0.getOpcode() == ISD::BITCAST &&
15540       Op0.getValueType() == MVT::i128 &&
15541       Op0.getOperand(0).getValueType() == MVT::f128) {
15542     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15543     return DCI.DAG.getNode(
15544         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15545         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15546   }
15547   return SDValue();
15548 }
15549 
15550 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15551   SelectionDAG &DAG = DCI.DAG;
15552 
15553   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15554   if (!ConstOpOrElement)
15555     return SDValue();
15556 
15557   // An imul is usually smaller than the alternative sequence for legal type.
15558   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15559       isOperationLegal(ISD::MUL, N->getValueType(0)))
15560     return SDValue();
15561 
15562   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15563     switch (this->Subtarget.getCPUDirective()) {
15564     default:
15565       // TODO: enhance the condition for subtarget before pwr8
15566       return false;
15567     case PPC::DIR_PWR8:
15568       //  type        mul     add    shl
15569       // scalar        4       1      1
15570       // vector        7       2      2
15571       return true;
15572     case PPC::DIR_PWR9:
15573     case PPC::DIR_PWR_FUTURE:
15574       //  type        mul     add    shl
15575       // scalar        5       2      2
15576       // vector        7       2      2
15577 
15578       // The cycle RATIO of related operations are showed as a table above.
15579       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15580       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15581       // are 4, it is always profitable; but for 3 instrs patterns
15582       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15583       // So we should only do it for vector type.
15584       return IsAddOne && IsNeg ? VT.isVector() : true;
15585     }
15586   };
15587 
15588   EVT VT = N->getValueType(0);
15589   SDLoc DL(N);
15590 
15591   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15592   bool IsNeg = MulAmt.isNegative();
15593   APInt MulAmtAbs = MulAmt.abs();
15594 
15595   if ((MulAmtAbs - 1).isPowerOf2()) {
15596     // (mul x, 2^N + 1) => (add (shl x, N), x)
15597     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15598 
15599     if (!IsProfitable(IsNeg, true, VT))
15600       return SDValue();
15601 
15602     SDValue Op0 = N->getOperand(0);
15603     SDValue Op1 =
15604         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15605                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15606     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15607 
15608     if (!IsNeg)
15609       return Res;
15610 
15611     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15612   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15613     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15614     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15615 
15616     if (!IsProfitable(IsNeg, false, VT))
15617       return SDValue();
15618 
15619     SDValue Op0 = N->getOperand(0);
15620     SDValue Op1 =
15621         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15622                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15623 
15624     if (!IsNeg)
15625       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15626     else
15627       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15628 
15629   } else {
15630     return SDValue();
15631   }
15632 }
15633 
15634 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15635   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15636   if (!Subtarget.is64BitELFABI())
15637     return false;
15638 
15639   // If not a tail call then no need to proceed.
15640   if (!CI->isTailCall())
15641     return false;
15642 
15643   // If tail calls are disabled for the caller then we are done.
15644   const Function *Caller = CI->getParent()->getParent();
15645   auto Attr = Caller->getFnAttribute("disable-tail-calls");
15646   if (Attr.getValueAsString() == "true")
15647     return false;
15648 
15649   // If sibling calls have been disabled and tail-calls aren't guaranteed
15650   // there is no reason to duplicate.
15651   auto &TM = getTargetMachine();
15652   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15653     return false;
15654 
15655   // Can't tail call a function called indirectly, or if it has variadic args.
15656   const Function *Callee = CI->getCalledFunction();
15657   if (!Callee || Callee->isVarArg())
15658     return false;
15659 
15660   // Make sure the callee and caller calling conventions are eligible for tco.
15661   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15662                                            CI->getCallingConv()))
15663       return false;
15664 
15665   // If the function is local then we have a good chance at tail-calling it
15666   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15667 }
15668 
15669 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15670   if (!Subtarget.hasVSX())
15671     return false;
15672   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15673     return true;
15674   return VT == MVT::f32 || VT == MVT::f64 ||
15675     VT == MVT::v4f32 || VT == MVT::v2f64;
15676 }
15677 
15678 bool PPCTargetLowering::
15679 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15680   const Value *Mask = AndI.getOperand(1);
15681   // If the mask is suitable for andi. or andis. we should sink the and.
15682   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15683     // Can't handle constants wider than 64-bits.
15684     if (CI->getBitWidth() > 64)
15685       return false;
15686     int64_t ConstVal = CI->getZExtValue();
15687     return isUInt<16>(ConstVal) ||
15688       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15689   }
15690 
15691   // For non-constant masks, we can always use the record-form and.
15692   return true;
15693 }
15694 
15695 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15696 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15697 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15698 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15699 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15700 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15701   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15702   assert(Subtarget.hasP9Altivec() &&
15703          "Only combine this when P9 altivec supported!");
15704   EVT VT = N->getValueType(0);
15705   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15706     return SDValue();
15707 
15708   SelectionDAG &DAG = DCI.DAG;
15709   SDLoc dl(N);
15710   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15711     // Even for signed integers, if it's known to be positive (as signed
15712     // integer) due to zero-extended inputs.
15713     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15714     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15715     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15716          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15717         (SubOpcd1 == ISD::ZERO_EXTEND ||
15718          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15719       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15720                          N->getOperand(0)->getOperand(0),
15721                          N->getOperand(0)->getOperand(1),
15722                          DAG.getTargetConstant(0, dl, MVT::i32));
15723     }
15724 
15725     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15726     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15727         N->getOperand(0).hasOneUse()) {
15728       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15729                          N->getOperand(0)->getOperand(0),
15730                          N->getOperand(0)->getOperand(1),
15731                          DAG.getTargetConstant(1, dl, MVT::i32));
15732     }
15733   }
15734 
15735   return SDValue();
15736 }
15737 
15738 // For type v4i32/v8ii16/v16i8, transform
15739 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15740 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15741 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15742 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15743 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15744                                           DAGCombinerInfo &DCI) const {
15745   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15746   assert(Subtarget.hasP9Altivec() &&
15747          "Only combine this when P9 altivec supported!");
15748 
15749   SelectionDAG &DAG = DCI.DAG;
15750   SDLoc dl(N);
15751   SDValue Cond = N->getOperand(0);
15752   SDValue TrueOpnd = N->getOperand(1);
15753   SDValue FalseOpnd = N->getOperand(2);
15754   EVT VT = N->getOperand(1).getValueType();
15755 
15756   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15757       FalseOpnd.getOpcode() != ISD::SUB)
15758     return SDValue();
15759 
15760   // ABSD only available for type v4i32/v8i16/v16i8
15761   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15762     return SDValue();
15763 
15764   // At least to save one more dependent computation
15765   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15766     return SDValue();
15767 
15768   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15769 
15770   // Can only handle unsigned comparison here
15771   switch (CC) {
15772   default:
15773     return SDValue();
15774   case ISD::SETUGT:
15775   case ISD::SETUGE:
15776     break;
15777   case ISD::SETULT:
15778   case ISD::SETULE:
15779     std::swap(TrueOpnd, FalseOpnd);
15780     break;
15781   }
15782 
15783   SDValue CmpOpnd1 = Cond.getOperand(0);
15784   SDValue CmpOpnd2 = Cond.getOperand(1);
15785 
15786   // SETCC CmpOpnd1 CmpOpnd2 cond
15787   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15788   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15789   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15790       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15791       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15792       FalseOpnd.getOperand(1) == CmpOpnd1) {
15793     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15794                        CmpOpnd1, CmpOpnd2,
15795                        DAG.getTargetConstant(0, dl, MVT::i32));
15796   }
15797 
15798   return SDValue();
15799 }
15800