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/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/ValueTypes.h"
57 #include "llvm/IR/CallSite.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/MC/MCContext.h"
74 #include "llvm/MC/MCExpr.h"
75 #include "llvm/MC/MCRegisterInfo.h"
76 #include "llvm/MC/MCSymbolXCOFF.h"
77 #include "llvm/Support/AtomicOrdering.h"
78 #include "llvm/Support/BranchProbability.h"
79 #include "llvm/Support/Casting.h"
80 #include "llvm/Support/CodeGen.h"
81 #include "llvm/Support/CommandLine.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/Debug.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MachineValueType.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include "llvm/Target/TargetMachine.h"
91 #include "llvm/Target/TargetOptions.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <list>
97 #include <utility>
98 #include <vector>
99 
100 using namespace llvm;
101 
102 #define DEBUG_TYPE "ppc-lowering"
103 
104 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
105 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
106 
107 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
108 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
109 
110 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
111 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
112 
113 static cl::opt<bool> DisableSCO("disable-ppc-sco",
114 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
115 
116 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
117 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
118 
119 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
120 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
121 
122 STATISTIC(NumTailCalls, "Number of tail calls");
123 STATISTIC(NumSiblingCalls, "Number of sibling calls");
124 
125 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
126 
127 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
128 
129 // FIXME: Remove this once the bug has been fixed!
130 extern cl::opt<bool> ANDIGlueBug;
131 
132 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
133                                      const PPCSubtarget &STI)
134     : TargetLowering(TM), Subtarget(STI) {
135   // Use _setjmp/_longjmp instead of setjmp/longjmp.
136   setUseUnderscoreSetJmp(true);
137   setUseUnderscoreLongJmp(true);
138 
139   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
140   // arguments are at least 4/8 bytes aligned.
141   bool isPPC64 = Subtarget.isPPC64();
142   setMinStackArgumentAlignment(isPPC64 ? 8:4);
143 
144   // Set up the register classes.
145   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
146   if (!useSoftFloat()) {
147     if (hasSPE()) {
148       addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass);
149       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
150     } else {
151       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
152       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
153     }
154   }
155 
156   // Match BITREVERSE to customized fast code sequence in the td file.
157   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
158   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
159 
160   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
161   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
162 
163   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
164   for (MVT VT : MVT::integer_valuetypes()) {
165     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
166     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
167   }
168 
169   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
170 
171   // PowerPC has pre-inc load and store's.
172   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
173   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
174   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
175   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
176   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
177   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
178   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
179   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
180   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
181   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
182   if (!Subtarget.hasSPE()) {
183     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
184     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
185     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
186     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
187   }
188 
189   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
190   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
191   for (MVT VT : ScalarIntVTs) {
192     setOperationAction(ISD::ADDC, VT, Legal);
193     setOperationAction(ISD::ADDE, VT, Legal);
194     setOperationAction(ISD::SUBC, VT, Legal);
195     setOperationAction(ISD::SUBE, VT, Legal);
196   }
197 
198   if (Subtarget.useCRBits()) {
199     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
200 
201     if (isPPC64 || Subtarget.hasFPCVT()) {
202       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
203       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
204                          isPPC64 ? MVT::i64 : MVT::i32);
205       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
206       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
207                         isPPC64 ? MVT::i64 : MVT::i32);
208     } else {
209       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
210       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
211     }
212 
213     // PowerPC does not support direct load/store of condition registers.
214     setOperationAction(ISD::LOAD, MVT::i1, Custom);
215     setOperationAction(ISD::STORE, MVT::i1, Custom);
216 
217     // FIXME: Remove this once the ANDI glue bug is fixed:
218     if (ANDIGlueBug)
219       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
220 
221     for (MVT VT : MVT::integer_valuetypes()) {
222       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
223       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
224       setTruncStoreAction(VT, MVT::i1, Expand);
225     }
226 
227     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
228   }
229 
230   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
231   // PPC (the libcall is not available).
232   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
233   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
234 
235   // We do not currently implement these libm ops for PowerPC.
236   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
237   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
238   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
239   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
240   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
241   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
242 
243   // PowerPC has no SREM/UREM instructions unless we are on P9
244   // On P9 we may use a hardware instruction to compute the remainder.
245   // The instructions are not legalized directly because in the cases where the
246   // result of both the remainder and the division is required it is more
247   // efficient to compute the remainder from the result of the division rather
248   // than use the remainder instruction.
249   if (Subtarget.isISA3_0()) {
250     setOperationAction(ISD::SREM, MVT::i32, Custom);
251     setOperationAction(ISD::UREM, MVT::i32, Custom);
252     setOperationAction(ISD::SREM, MVT::i64, Custom);
253     setOperationAction(ISD::UREM, MVT::i64, Custom);
254   } else {
255     setOperationAction(ISD::SREM, MVT::i32, Expand);
256     setOperationAction(ISD::UREM, MVT::i32, Expand);
257     setOperationAction(ISD::SREM, MVT::i64, Expand);
258     setOperationAction(ISD::UREM, MVT::i64, Expand);
259   }
260 
261   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
262   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
263   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
264   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
265   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
266   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
267   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
268   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
269   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
270 
271   // We don't support sin/cos/sqrt/fmod/pow
272   setOperationAction(ISD::FSIN , MVT::f64, Expand);
273   setOperationAction(ISD::FCOS , MVT::f64, Expand);
274   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
275   setOperationAction(ISD::FREM , MVT::f64, Expand);
276   setOperationAction(ISD::FPOW , MVT::f64, Expand);
277   setOperationAction(ISD::FSIN , MVT::f32, Expand);
278   setOperationAction(ISD::FCOS , MVT::f32, Expand);
279   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
280   setOperationAction(ISD::FREM , MVT::f32, Expand);
281   setOperationAction(ISD::FPOW , MVT::f32, Expand);
282   if (Subtarget.hasSPE()) {
283     setOperationAction(ISD::FMA  , MVT::f64, Expand);
284     setOperationAction(ISD::FMA  , MVT::f32, Expand);
285   } else {
286     setOperationAction(ISD::FMA  , MVT::f64, Legal);
287     setOperationAction(ISD::FMA  , MVT::f32, Legal);
288   }
289 
290   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
291 
292   // If we're enabling GP optimizations, use hardware square root
293   if (!Subtarget.hasFSQRT() &&
294       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
295         Subtarget.hasFRE()))
296     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
297 
298   if (!Subtarget.hasFSQRT() &&
299       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
300         Subtarget.hasFRES()))
301     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
302 
303   if (Subtarget.hasFCPSGN()) {
304     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
305     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
306   } else {
307     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
308     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
309   }
310 
311   if (Subtarget.hasFPRND()) {
312     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
313     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
314     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
315     setOperationAction(ISD::FROUND, MVT::f64, Legal);
316 
317     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
318     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
319     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
320     setOperationAction(ISD::FROUND, MVT::f32, Legal);
321   }
322 
323   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
324   // to speed up scalar BSWAP64.
325   // CTPOP or CTTZ were introduced in P8/P9 respectively
326   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
327   if (Subtarget.hasP9Vector())
328     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
329   else
330     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
331   if (Subtarget.isISA3_0()) {
332     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
333     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
334   } else {
335     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
336     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
337   }
338 
339   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
340     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
341     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
342   } else {
343     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
344     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
345   }
346 
347   // PowerPC does not have ROTR
348   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
349   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
350 
351   if (!Subtarget.useCRBits()) {
352     // PowerPC does not have Select
353     setOperationAction(ISD::SELECT, MVT::i32, Expand);
354     setOperationAction(ISD::SELECT, MVT::i64, Expand);
355     setOperationAction(ISD::SELECT, MVT::f32, Expand);
356     setOperationAction(ISD::SELECT, MVT::f64, Expand);
357   }
358 
359   // PowerPC wants to turn select_cc of FP into fsel when possible.
360   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
361   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
362 
363   // PowerPC wants to optimize integer setcc a bit
364   if (!Subtarget.useCRBits())
365     setOperationAction(ISD::SETCC, MVT::i32, Custom);
366 
367   // PowerPC does not have BRCOND which requires SetCC
368   if (!Subtarget.useCRBits())
369     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
370 
371   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
372 
373   if (Subtarget.hasSPE()) {
374     // SPE has built-in conversions
375     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
376     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
377     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
378   } else {
379     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
380     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
381 
382     // PowerPC does not have [U|S]INT_TO_FP
383     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
384     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
385   }
386 
387   if (Subtarget.hasDirectMove() && isPPC64) {
388     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
389     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
390     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
391     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
392   } else {
393     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
394     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
395     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
396     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
397   }
398 
399   // We cannot sextinreg(i1).  Expand to shifts.
400   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
401 
402   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
403   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
404   // support continuation, user-level threading, and etc.. As a result, no
405   // other SjLj exception interfaces are implemented and please don't build
406   // your own exception handling based on them.
407   // LLVM/Clang supports zero-cost DWARF exception handling.
408   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
409   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
410 
411   // We want to legalize GlobalAddress and ConstantPool nodes into the
412   // appropriate instructions to materialize the address.
413   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
414   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
415   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
416   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
417   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
418   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
419   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
420   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
421   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
422   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
423 
424   // TRAP is legal.
425   setOperationAction(ISD::TRAP, MVT::Other, Legal);
426 
427   // TRAMPOLINE is custom lowered.
428   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
429   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
430 
431   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
432   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
433 
434   if (Subtarget.isSVR4ABI()) {
435     if (isPPC64) {
436       // VAARG always uses double-word chunks, so promote anything smaller.
437       setOperationAction(ISD::VAARG, MVT::i1, Promote);
438       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
439       setOperationAction(ISD::VAARG, MVT::i8, Promote);
440       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
441       setOperationAction(ISD::VAARG, MVT::i16, Promote);
442       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
443       setOperationAction(ISD::VAARG, MVT::i32, Promote);
444       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
445       setOperationAction(ISD::VAARG, MVT::Other, Expand);
446     } else {
447       // VAARG is custom lowered with the 32-bit SVR4 ABI.
448       setOperationAction(ISD::VAARG, MVT::Other, Custom);
449       setOperationAction(ISD::VAARG, MVT::i64, Custom);
450     }
451   } else
452     setOperationAction(ISD::VAARG, MVT::Other, Expand);
453 
454   if (Subtarget.isSVR4ABI() && !isPPC64)
455     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
456     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
457   else
458     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
459 
460   // Use the default implementation.
461   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
462   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
463   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
464   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
465   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
466   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
467   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
468   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
469   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
470 
471   // We want to custom lower some of our intrinsics.
472   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
473 
474   // To handle counter-based loop conditions.
475   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
476 
477   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
478   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
479   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
480   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
481 
482   // Comparisons that require checking two conditions.
483   if (Subtarget.hasSPE()) {
484     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
485     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
486     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
487     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
488   }
489   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
490   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
491   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
492   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
493   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
494   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
495   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
496   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
497   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
498   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
499   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
500   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
501 
502   if (Subtarget.has64BitSupport()) {
503     // They also have instructions for converting between i64 and fp.
504     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
505     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
506     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
507     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
508     // This is just the low 32 bits of a (signed) fp->i64 conversion.
509     // We cannot do this with Promote because i64 is not a legal type.
510     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
511 
512     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
513       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
514   } else {
515     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
516     if (Subtarget.hasSPE())
517       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
518     else
519       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
520   }
521 
522   // With the instructions enabled under FPCVT, we can do everything.
523   if (Subtarget.hasFPCVT()) {
524     if (Subtarget.has64BitSupport()) {
525       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
526       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
527       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
528       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
529     }
530 
531     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
532     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
533     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
534     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
535   }
536 
537   if (Subtarget.use64BitRegs()) {
538     // 64-bit PowerPC implementations can support i64 types directly
539     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
540     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
541     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
542     // 64-bit PowerPC wants to expand i128 shifts itself.
543     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
544     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
545     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
546   } else {
547     // 32-bit PowerPC wants to expand i64 shifts itself.
548     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
549     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
550     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
551   }
552 
553   if (Subtarget.hasAltivec()) {
554     // First set operation action for all vector types to expand. Then we
555     // will selectively turn on ones that can be effectively codegen'd.
556     for (MVT VT : MVT::vector_valuetypes()) {
557       // add/sub are legal for all supported vector VT's.
558       setOperationAction(ISD::ADD, VT, Legal);
559       setOperationAction(ISD::SUB, VT, Legal);
560 
561       // For v2i64, these are only valid with P8Vector. This is corrected after
562       // the loop.
563       setOperationAction(ISD::SMAX, VT, Legal);
564       setOperationAction(ISD::SMIN, VT, Legal);
565       setOperationAction(ISD::UMAX, VT, Legal);
566       setOperationAction(ISD::UMIN, VT, Legal);
567 
568       if (Subtarget.hasVSX()) {
569         setOperationAction(ISD::FMAXNUM, VT, Legal);
570         setOperationAction(ISD::FMINNUM, VT, Legal);
571       }
572 
573       // Vector instructions introduced in P8
574       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
575         setOperationAction(ISD::CTPOP, VT, Legal);
576         setOperationAction(ISD::CTLZ, VT, Legal);
577       }
578       else {
579         setOperationAction(ISD::CTPOP, VT, Expand);
580         setOperationAction(ISD::CTLZ, VT, Expand);
581       }
582 
583       // Vector instructions introduced in P9
584       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
585         setOperationAction(ISD::CTTZ, VT, Legal);
586       else
587         setOperationAction(ISD::CTTZ, VT, Expand);
588 
589       // We promote all shuffles to v16i8.
590       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
591       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
592 
593       // We promote all non-typed operations to v4i32.
594       setOperationAction(ISD::AND   , VT, Promote);
595       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
596       setOperationAction(ISD::OR    , VT, Promote);
597       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
598       setOperationAction(ISD::XOR   , VT, Promote);
599       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
600       setOperationAction(ISD::LOAD  , VT, Promote);
601       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
602       setOperationAction(ISD::SELECT, VT, Promote);
603       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
604       setOperationAction(ISD::VSELECT, VT, Legal);
605       setOperationAction(ISD::SELECT_CC, VT, Promote);
606       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
607       setOperationAction(ISD::STORE, VT, Promote);
608       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
609 
610       // No other operations are legal.
611       setOperationAction(ISD::MUL , VT, Expand);
612       setOperationAction(ISD::SDIV, VT, Expand);
613       setOperationAction(ISD::SREM, VT, Expand);
614       setOperationAction(ISD::UDIV, VT, Expand);
615       setOperationAction(ISD::UREM, VT, Expand);
616       setOperationAction(ISD::FDIV, VT, Expand);
617       setOperationAction(ISD::FREM, VT, Expand);
618       setOperationAction(ISD::FNEG, VT, Expand);
619       setOperationAction(ISD::FSQRT, VT, Expand);
620       setOperationAction(ISD::FLOG, VT, Expand);
621       setOperationAction(ISD::FLOG10, VT, Expand);
622       setOperationAction(ISD::FLOG2, VT, Expand);
623       setOperationAction(ISD::FEXP, VT, Expand);
624       setOperationAction(ISD::FEXP2, VT, Expand);
625       setOperationAction(ISD::FSIN, VT, Expand);
626       setOperationAction(ISD::FCOS, VT, Expand);
627       setOperationAction(ISD::FABS, VT, Expand);
628       setOperationAction(ISD::FFLOOR, VT, Expand);
629       setOperationAction(ISD::FCEIL,  VT, Expand);
630       setOperationAction(ISD::FTRUNC, VT, Expand);
631       setOperationAction(ISD::FRINT,  VT, Expand);
632       setOperationAction(ISD::FNEARBYINT, VT, Expand);
633       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
634       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
635       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
636       setOperationAction(ISD::MULHU, VT, Expand);
637       setOperationAction(ISD::MULHS, VT, Expand);
638       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
639       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
640       setOperationAction(ISD::UDIVREM, VT, Expand);
641       setOperationAction(ISD::SDIVREM, VT, Expand);
642       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
643       setOperationAction(ISD::FPOW, VT, Expand);
644       setOperationAction(ISD::BSWAP, VT, Expand);
645       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
646       setOperationAction(ISD::ROTL, VT, Expand);
647       setOperationAction(ISD::ROTR, VT, Expand);
648 
649       for (MVT InnerVT : MVT::vector_valuetypes()) {
650         setTruncStoreAction(VT, InnerVT, Expand);
651         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
652         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
653         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
654       }
655     }
656     if (!Subtarget.hasP8Vector()) {
657       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
658       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
659       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
660       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
661     }
662 
663     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
664       setOperationAction(ISD::ABS, VT, Custom);
665 
666     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
667     // with merges, splats, etc.
668     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
669 
670     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
671     // are cheap, so handle them before they get expanded to scalar.
672     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
673     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
674     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
675     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
676     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
677 
678     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
679     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
680     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
681     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
682     setOperationAction(ISD::SELECT, MVT::v4i32,
683                        Subtarget.useCRBits() ? Legal : Expand);
684     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
685     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
686     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
687     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
688     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
689     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
690     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
691     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
692     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
693 
694     // Without hasP8Altivec set, v2i64 SMAX isn't available.
695     // But ABS custom lowering requires SMAX support.
696     if (!Subtarget.hasP8Altivec())
697       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
698 
699     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
700     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
701     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
702     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
703 
704     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
705     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
706 
707     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
708       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
709       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
710     }
711 
712     if (Subtarget.hasP8Altivec())
713       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
714     else
715       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
716 
717     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
718     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
719 
720     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
721     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
722 
723     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
724     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
725     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
726     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
727 
728     // Altivec does not contain unordered floating-point compare instructions
729     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
730     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
731     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
732     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
733 
734     if (Subtarget.hasVSX()) {
735       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
736       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
737       if (Subtarget.hasP8Vector()) {
738         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
739         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
740       }
741       if (Subtarget.hasDirectMove() && isPPC64) {
742         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
743         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
744         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
745         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
746         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
747         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
748         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
749         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
750       }
751       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
752 
753       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
754       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
755       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
756       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
757       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
758 
759       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
760 
761       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
762       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
763 
764       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
765       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
766 
767       // Share the Altivec comparison restrictions.
768       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
769       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
770       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
771       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
772 
773       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
774       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
775 
776       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
777 
778       if (Subtarget.hasP8Vector())
779         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
780 
781       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
782 
783       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
784       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
785       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
786 
787       if (Subtarget.hasP8Altivec()) {
788         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
789         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
790         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
791 
792         // 128 bit shifts can be accomplished via 3 instructions for SHL and
793         // SRL, but not for SRA because of the instructions available:
794         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
795         // doing
796         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
797         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
798         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
799 
800         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
801       }
802       else {
803         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
804         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
805         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
806 
807         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
808 
809         // VSX v2i64 only supports non-arithmetic operations.
810         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
811         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
812       }
813 
814       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
815       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
816       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
817       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
818 
819       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
820 
821       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
822       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
823       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
824       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
825 
826       // Custom handling for partial vectors of integers converted to
827       // floating point. We already have optimal handling for v2i32 through
828       // the DAG combine, so those aren't necessary.
829       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
830       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
831       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
832       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
833       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
834       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
835       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
836       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
837 
838       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
839       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
840       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
841       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
842       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
843       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
844 
845       if (Subtarget.hasDirectMove())
846         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
847       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
848 
849       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
850     }
851 
852     if (Subtarget.hasP8Altivec()) {
853       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
854       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
855     }
856 
857     if (Subtarget.hasP9Vector()) {
858       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
859       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
860 
861       // 128 bit shifts can be accomplished via 3 instructions for SHL and
862       // SRL, but not for SRA because of the instructions available:
863       // VS{RL} and VS{RL}O.
864       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
865       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
866       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
867 
868       if (EnableQuadPrecision) {
869         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
870         setOperationAction(ISD::FADD, MVT::f128, Legal);
871         setOperationAction(ISD::FSUB, MVT::f128, Legal);
872         setOperationAction(ISD::FDIV, MVT::f128, Legal);
873         setOperationAction(ISD::FMUL, MVT::f128, Legal);
874         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
875         // No extending loads to f128 on PPC.
876         for (MVT FPT : MVT::fp_valuetypes())
877           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
878         setOperationAction(ISD::FMA, MVT::f128, Legal);
879         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
880         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
881         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
882         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
883         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
884         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
885 
886         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
887         setOperationAction(ISD::FRINT, MVT::f128, Legal);
888         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
889         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
890         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
891         setOperationAction(ISD::FROUND, MVT::f128, Legal);
892 
893         setOperationAction(ISD::SELECT, MVT::f128, Expand);
894         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
895         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
896         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
897         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
898         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
899         // No implementation for these ops for PowerPC.
900         setOperationAction(ISD::FSIN , MVT::f128, Expand);
901         setOperationAction(ISD::FCOS , MVT::f128, Expand);
902         setOperationAction(ISD::FPOW, MVT::f128, Expand);
903         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
904         setOperationAction(ISD::FREM, MVT::f128, Expand);
905       }
906       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
907 
908     }
909 
910     if (Subtarget.hasP9Altivec()) {
911       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
912       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
913     }
914   }
915 
916   if (Subtarget.hasQPX()) {
917     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
918     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
919     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
920     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
921 
922     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
923     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
924 
925     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
926     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
927 
928     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
929     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
930 
931     if (!Subtarget.useCRBits())
932       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
933     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
934 
935     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
936     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
937     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
938     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
939     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
940     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
941     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
942 
943     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
944     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
945 
946     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
947     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
948     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
949 
950     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
951     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
952     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
953     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
954     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
955     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
956     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
957     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
958     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
959     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
960 
961     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
962     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
963 
964     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
965     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
966 
967     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
968 
969     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
970     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
971     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
972     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
973 
974     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
975     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
976 
977     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
978     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
979 
980     if (!Subtarget.useCRBits())
981       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
982     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
983 
984     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
985     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
986     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
987     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
988     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
989     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
990     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
991 
992     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
993     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
994 
995     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
996     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
997     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
998     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
999     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1000     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1001     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1002     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1003     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1004     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1005 
1006     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1007     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1008 
1009     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1010     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1011 
1012     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1013 
1014     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1015     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1016     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1017 
1018     if (!Subtarget.useCRBits())
1019       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1020     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1021 
1022     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1023     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1024 
1025     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1026     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1027     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1028     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1029     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1030     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1031     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1032 
1033     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1034     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1035 
1036     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1037 
1038     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1039     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1040     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1041     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1042 
1043     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1044     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1045     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1046     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1047 
1048     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1049     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1050 
1051     // These need to set FE_INEXACT, and so cannot be vectorized here.
1052     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1053     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1054 
1055     if (TM.Options.UnsafeFPMath) {
1056       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1057       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1058 
1059       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1060       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1061     } else {
1062       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1063       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1064 
1065       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1066       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1067     }
1068   }
1069 
1070   if (Subtarget.has64BitSupport())
1071     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1072 
1073   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1074 
1075   if (!isPPC64) {
1076     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1077     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1078   }
1079 
1080   setBooleanContents(ZeroOrOneBooleanContent);
1081 
1082   if (Subtarget.hasAltivec()) {
1083     // Altivec instructions set fields to all zeros or all ones.
1084     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1085   }
1086 
1087   if (!isPPC64) {
1088     // These libcalls are not available in 32-bit.
1089     setLibcallName(RTLIB::SHL_I128, nullptr);
1090     setLibcallName(RTLIB::SRL_I128, nullptr);
1091     setLibcallName(RTLIB::SRA_I128, nullptr);
1092   }
1093 
1094   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1095 
1096   // We have target-specific dag combine patterns for the following nodes:
1097   setTargetDAGCombine(ISD::ADD);
1098   setTargetDAGCombine(ISD::SHL);
1099   setTargetDAGCombine(ISD::SRA);
1100   setTargetDAGCombine(ISD::SRL);
1101   setTargetDAGCombine(ISD::MUL);
1102   setTargetDAGCombine(ISD::SINT_TO_FP);
1103   setTargetDAGCombine(ISD::BUILD_VECTOR);
1104   if (Subtarget.hasFPCVT())
1105     setTargetDAGCombine(ISD::UINT_TO_FP);
1106   setTargetDAGCombine(ISD::LOAD);
1107   setTargetDAGCombine(ISD::STORE);
1108   setTargetDAGCombine(ISD::BR_CC);
1109   if (Subtarget.useCRBits())
1110     setTargetDAGCombine(ISD::BRCOND);
1111   setTargetDAGCombine(ISD::BSWAP);
1112   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1113   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1114   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1115 
1116   setTargetDAGCombine(ISD::SIGN_EXTEND);
1117   setTargetDAGCombine(ISD::ZERO_EXTEND);
1118   setTargetDAGCombine(ISD::ANY_EXTEND);
1119 
1120   setTargetDAGCombine(ISD::TRUNCATE);
1121   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1122 
1123 
1124   if (Subtarget.useCRBits()) {
1125     setTargetDAGCombine(ISD::TRUNCATE);
1126     setTargetDAGCombine(ISD::SETCC);
1127     setTargetDAGCombine(ISD::SELECT_CC);
1128   }
1129 
1130   // Use reciprocal estimates.
1131   if (TM.Options.UnsafeFPMath) {
1132     setTargetDAGCombine(ISD::FDIV);
1133     setTargetDAGCombine(ISD::FSQRT);
1134   }
1135 
1136   if (Subtarget.hasP9Altivec()) {
1137     setTargetDAGCombine(ISD::ABS);
1138     setTargetDAGCombine(ISD::VSELECT);
1139   }
1140 
1141   // Darwin long double math library functions have $LDBL128 appended.
1142   if (Subtarget.isDarwin()) {
1143     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1144     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1145     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1146     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1147     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1148     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1149     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1150     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1151     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1152     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1153   }
1154 
1155   if (EnableQuadPrecision) {
1156     setLibcallName(RTLIB::LOG_F128, "logf128");
1157     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1158     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1159     setLibcallName(RTLIB::EXP_F128, "expf128");
1160     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1161     setLibcallName(RTLIB::SIN_F128, "sinf128");
1162     setLibcallName(RTLIB::COS_F128, "cosf128");
1163     setLibcallName(RTLIB::POW_F128, "powf128");
1164     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1165     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1166     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1167     setLibcallName(RTLIB::REM_F128, "fmodf128");
1168   }
1169 
1170   // With 32 condition bits, we don't need to sink (and duplicate) compares
1171   // aggressively in CodeGenPrep.
1172   if (Subtarget.useCRBits()) {
1173     setHasMultipleConditionRegisters();
1174     setJumpIsExpensive();
1175   }
1176 
1177   setMinFunctionAlignment(2);
1178   if (Subtarget.isDarwin())
1179     setPrefFunctionAlignment(4);
1180 
1181   switch (Subtarget.getDarwinDirective()) {
1182   default: break;
1183   case PPC::DIR_970:
1184   case PPC::DIR_A2:
1185   case PPC::DIR_E500:
1186   case PPC::DIR_E500mc:
1187   case PPC::DIR_E5500:
1188   case PPC::DIR_PWR4:
1189   case PPC::DIR_PWR5:
1190   case PPC::DIR_PWR5X:
1191   case PPC::DIR_PWR6:
1192   case PPC::DIR_PWR6X:
1193   case PPC::DIR_PWR7:
1194   case PPC::DIR_PWR8:
1195   case PPC::DIR_PWR9:
1196     setPrefFunctionAlignment(4);
1197     setPrefLoopAlignment(4);
1198     break;
1199   }
1200 
1201   if (Subtarget.enableMachineScheduler())
1202     setSchedulingPreference(Sched::Source);
1203   else
1204     setSchedulingPreference(Sched::Hybrid);
1205 
1206   computeRegisterProperties(STI.getRegisterInfo());
1207 
1208   // The Freescale cores do better with aggressive inlining of memcpy and
1209   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1210   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1211       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1212     MaxStoresPerMemset = 32;
1213     MaxStoresPerMemsetOptSize = 16;
1214     MaxStoresPerMemcpy = 32;
1215     MaxStoresPerMemcpyOptSize = 8;
1216     MaxStoresPerMemmove = 32;
1217     MaxStoresPerMemmoveOptSize = 8;
1218   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1219     // The A2 also benefits from (very) aggressive inlining of memcpy and
1220     // friends. The overhead of a the function call, even when warm, can be
1221     // over one hundred cycles.
1222     MaxStoresPerMemset = 128;
1223     MaxStoresPerMemcpy = 128;
1224     MaxStoresPerMemmove = 128;
1225     MaxLoadsPerMemcmp = 128;
1226   } else {
1227     MaxLoadsPerMemcmp = 8;
1228     MaxLoadsPerMemcmpOptSize = 4;
1229   }
1230 }
1231 
1232 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1233 /// the desired ByVal argument alignment.
1234 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1235                              unsigned MaxMaxAlign) {
1236   if (MaxAlign == MaxMaxAlign)
1237     return;
1238   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1239     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1240       MaxAlign = 32;
1241     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1242       MaxAlign = 16;
1243   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1244     unsigned EltAlign = 0;
1245     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1246     if (EltAlign > MaxAlign)
1247       MaxAlign = EltAlign;
1248   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1249     for (auto *EltTy : STy->elements()) {
1250       unsigned EltAlign = 0;
1251       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1252       if (EltAlign > MaxAlign)
1253         MaxAlign = EltAlign;
1254       if (MaxAlign == MaxMaxAlign)
1255         break;
1256     }
1257   }
1258 }
1259 
1260 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1261 /// function arguments in the caller parameter area.
1262 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1263                                                   const DataLayout &DL) const {
1264   // Darwin passes everything on 4 byte boundary.
1265   if (Subtarget.isDarwin())
1266     return 4;
1267 
1268   // 16byte and wider vectors are passed on 16byte boundary.
1269   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1270   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1271   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1272     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1273   return Align;
1274 }
1275 
1276 bool PPCTargetLowering::useSoftFloat() const {
1277   return Subtarget.useSoftFloat();
1278 }
1279 
1280 bool PPCTargetLowering::hasSPE() const {
1281   return Subtarget.hasSPE();
1282 }
1283 
1284 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1285   return VT.isScalarInteger();
1286 }
1287 
1288 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1289   switch ((PPCISD::NodeType)Opcode) {
1290   case PPCISD::FIRST_NUMBER:    break;
1291   case PPCISD::FSEL:            return "PPCISD::FSEL";
1292   case PPCISD::FCFID:           return "PPCISD::FCFID";
1293   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1294   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1295   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1296   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1297   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1298   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1299   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1300   case PPCISD::FP_TO_UINT_IN_VSR:
1301                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1302   case PPCISD::FP_TO_SINT_IN_VSR:
1303                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1304   case PPCISD::FRE:             return "PPCISD::FRE";
1305   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1306   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1307   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1308   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1309   case PPCISD::VPERM:           return "PPCISD::VPERM";
1310   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1311   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1312   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1313   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1314   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1315   case PPCISD::CMPB:            return "PPCISD::CMPB";
1316   case PPCISD::Hi:              return "PPCISD::Hi";
1317   case PPCISD::Lo:              return "PPCISD::Lo";
1318   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1319   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1320   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1321   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1322   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1323   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1324   case PPCISD::SRL:             return "PPCISD::SRL";
1325   case PPCISD::SRA:             return "PPCISD::SRA";
1326   case PPCISD::SHL:             return "PPCISD::SHL";
1327   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1328   case PPCISD::CALL:            return "PPCISD::CALL";
1329   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1330   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1331   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1332   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1333   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1334   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1335   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1336   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1337   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1338   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1339   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1340   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1341   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1342   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1343   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1344   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1345   case PPCISD::VCMP:            return "PPCISD::VCMP";
1346   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1347   case PPCISD::LBRX:            return "PPCISD::LBRX";
1348   case PPCISD::STBRX:           return "PPCISD::STBRX";
1349   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1350   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1351   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1352   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1353   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1354   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1355   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1356   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1357   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1358   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1359   case PPCISD::ST_VSR_SCAL_INT:
1360                                 return "PPCISD::ST_VSR_SCAL_INT";
1361   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1362   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1363   case PPCISD::BDZ:             return "PPCISD::BDZ";
1364   case PPCISD::MFFS:            return "PPCISD::MFFS";
1365   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1366   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1367   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1368   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1369   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1370   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1371   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1372   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1373   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1374   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1375   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1376   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1377   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1378   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1379   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1380   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1381   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1382   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1383   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1384   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1385   case PPCISD::SC:              return "PPCISD::SC";
1386   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1387   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1388   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1389   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1390   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1391   case PPCISD::VABSD:           return "PPCISD::VABSD";
1392   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1393   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1394   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1395   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1396   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1397   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1398   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1399   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1400   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1401   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1402   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1403   case PPCISD::FP_EXTEND_LH:    return "PPCISD::FP_EXTEND_LH";
1404   }
1405   return nullptr;
1406 }
1407 
1408 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1409                                           EVT VT) const {
1410   if (!VT.isVector())
1411     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1412 
1413   if (Subtarget.hasQPX())
1414     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1415 
1416   return VT.changeVectorElementTypeToInteger();
1417 }
1418 
1419 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1420   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1421   return true;
1422 }
1423 
1424 //===----------------------------------------------------------------------===//
1425 // Node matching predicates, for use by the tblgen matching code.
1426 //===----------------------------------------------------------------------===//
1427 
1428 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1429 static bool isFloatingPointZero(SDValue Op) {
1430   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1431     return CFP->getValueAPF().isZero();
1432   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1433     // Maybe this has already been legalized into the constant pool?
1434     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1435       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1436         return CFP->getValueAPF().isZero();
1437   }
1438   return false;
1439 }
1440 
1441 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1442 /// true if Op is undef or if it matches the specified value.
1443 static bool isConstantOrUndef(int Op, int Val) {
1444   return Op < 0 || Op == Val;
1445 }
1446 
1447 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1448 /// VPKUHUM instruction.
1449 /// The ShuffleKind distinguishes between big-endian operations with
1450 /// two different inputs (0), either-endian operations with two identical
1451 /// inputs (1), and little-endian operations with two different inputs (2).
1452 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1453 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1454                                SelectionDAG &DAG) {
1455   bool IsLE = DAG.getDataLayout().isLittleEndian();
1456   if (ShuffleKind == 0) {
1457     if (IsLE)
1458       return false;
1459     for (unsigned i = 0; i != 16; ++i)
1460       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1461         return false;
1462   } else if (ShuffleKind == 2) {
1463     if (!IsLE)
1464       return false;
1465     for (unsigned i = 0; i != 16; ++i)
1466       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1467         return false;
1468   } else if (ShuffleKind == 1) {
1469     unsigned j = IsLE ? 0 : 1;
1470     for (unsigned i = 0; i != 8; ++i)
1471       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1472           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1473         return false;
1474   }
1475   return true;
1476 }
1477 
1478 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1479 /// VPKUWUM instruction.
1480 /// The ShuffleKind distinguishes between big-endian operations with
1481 /// two different inputs (0), either-endian operations with two identical
1482 /// inputs (1), and little-endian operations with two different inputs (2).
1483 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1484 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1485                                SelectionDAG &DAG) {
1486   bool IsLE = DAG.getDataLayout().isLittleEndian();
1487   if (ShuffleKind == 0) {
1488     if (IsLE)
1489       return false;
1490     for (unsigned i = 0; i != 16; i += 2)
1491       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1492           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1493         return false;
1494   } else if (ShuffleKind == 2) {
1495     if (!IsLE)
1496       return false;
1497     for (unsigned i = 0; i != 16; i += 2)
1498       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1499           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1500         return false;
1501   } else if (ShuffleKind == 1) {
1502     unsigned j = IsLE ? 0 : 2;
1503     for (unsigned i = 0; i != 8; i += 2)
1504       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1505           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1506           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1507           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1508         return false;
1509   }
1510   return true;
1511 }
1512 
1513 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1514 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1515 /// current subtarget.
1516 ///
1517 /// The ShuffleKind distinguishes between big-endian operations with
1518 /// two different inputs (0), either-endian operations with two identical
1519 /// inputs (1), and little-endian operations with two different inputs (2).
1520 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1521 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1522                                SelectionDAG &DAG) {
1523   const PPCSubtarget& Subtarget =
1524     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1525   if (!Subtarget.hasP8Vector())
1526     return false;
1527 
1528   bool IsLE = DAG.getDataLayout().isLittleEndian();
1529   if (ShuffleKind == 0) {
1530     if (IsLE)
1531       return false;
1532     for (unsigned i = 0; i != 16; i += 4)
1533       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1534           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1535           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1536           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1537         return false;
1538   } else if (ShuffleKind == 2) {
1539     if (!IsLE)
1540       return false;
1541     for (unsigned i = 0; i != 16; i += 4)
1542       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1543           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1544           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1545           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1546         return false;
1547   } else if (ShuffleKind == 1) {
1548     unsigned j = IsLE ? 0 : 4;
1549     for (unsigned i = 0; i != 8; i += 4)
1550       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1551           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1552           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1553           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1554           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1555           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1556           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1557           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1558         return false;
1559   }
1560   return true;
1561 }
1562 
1563 /// isVMerge - Common function, used to match vmrg* shuffles.
1564 ///
1565 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1566                      unsigned LHSStart, unsigned RHSStart) {
1567   if (N->getValueType(0) != MVT::v16i8)
1568     return false;
1569   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1570          "Unsupported merge size!");
1571 
1572   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1573     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1574       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1575                              LHSStart+j+i*UnitSize) ||
1576           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1577                              RHSStart+j+i*UnitSize))
1578         return false;
1579     }
1580   return true;
1581 }
1582 
1583 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1584 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1585 /// The ShuffleKind distinguishes between big-endian merges with two
1586 /// different inputs (0), either-endian merges with two identical inputs (1),
1587 /// and little-endian merges with two different inputs (2).  For the latter,
1588 /// the input operands are swapped (see PPCInstrAltivec.td).
1589 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1590                              unsigned ShuffleKind, SelectionDAG &DAG) {
1591   if (DAG.getDataLayout().isLittleEndian()) {
1592     if (ShuffleKind == 1) // unary
1593       return isVMerge(N, UnitSize, 0, 0);
1594     else if (ShuffleKind == 2) // swapped
1595       return isVMerge(N, UnitSize, 0, 16);
1596     else
1597       return false;
1598   } else {
1599     if (ShuffleKind == 1) // unary
1600       return isVMerge(N, UnitSize, 8, 8);
1601     else if (ShuffleKind == 0) // normal
1602       return isVMerge(N, UnitSize, 8, 24);
1603     else
1604       return false;
1605   }
1606 }
1607 
1608 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1609 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1610 /// The ShuffleKind distinguishes between big-endian merges with two
1611 /// different inputs (0), either-endian merges with two identical inputs (1),
1612 /// and little-endian merges with two different inputs (2).  For the latter,
1613 /// the input operands are swapped (see PPCInstrAltivec.td).
1614 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1615                              unsigned ShuffleKind, SelectionDAG &DAG) {
1616   if (DAG.getDataLayout().isLittleEndian()) {
1617     if (ShuffleKind == 1) // unary
1618       return isVMerge(N, UnitSize, 8, 8);
1619     else if (ShuffleKind == 2) // swapped
1620       return isVMerge(N, UnitSize, 8, 24);
1621     else
1622       return false;
1623   } else {
1624     if (ShuffleKind == 1) // unary
1625       return isVMerge(N, UnitSize, 0, 0);
1626     else if (ShuffleKind == 0) // normal
1627       return isVMerge(N, UnitSize, 0, 16);
1628     else
1629       return false;
1630   }
1631 }
1632 
1633 /**
1634  * Common function used to match vmrgew and vmrgow shuffles
1635  *
1636  * The indexOffset determines whether to look for even or odd words in
1637  * the shuffle mask. This is based on the of the endianness of the target
1638  * machine.
1639  *   - Little Endian:
1640  *     - Use offset of 0 to check for odd elements
1641  *     - Use offset of 4 to check for even elements
1642  *   - Big Endian:
1643  *     - Use offset of 0 to check for even elements
1644  *     - Use offset of 4 to check for odd elements
1645  * A detailed description of the vector element ordering for little endian and
1646  * big endian can be found at
1647  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1648  * Targeting your applications - what little endian and big endian IBM XL C/C++
1649  * compiler differences mean to you
1650  *
1651  * The mask to the shuffle vector instruction specifies the indices of the
1652  * elements from the two input vectors to place in the result. The elements are
1653  * numbered in array-access order, starting with the first vector. These vectors
1654  * are always of type v16i8, thus each vector will contain 16 elements of size
1655  * 8. More info on the shuffle vector can be found in the
1656  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1657  * Language Reference.
1658  *
1659  * The RHSStartValue indicates whether the same input vectors are used (unary)
1660  * or two different input vectors are used, based on the following:
1661  *   - If the instruction uses the same vector for both inputs, the range of the
1662  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1663  *     be 0.
1664  *   - If the instruction has two different vectors then the range of the
1665  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1666  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1667  *     to 31 specify elements in the second vector).
1668  *
1669  * \param[in] N The shuffle vector SD Node to analyze
1670  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1671  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1672  * vector to the shuffle_vector instruction
1673  * \return true iff this shuffle vector represents an even or odd word merge
1674  */
1675 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1676                      unsigned RHSStartValue) {
1677   if (N->getValueType(0) != MVT::v16i8)
1678     return false;
1679 
1680   for (unsigned i = 0; i < 2; ++i)
1681     for (unsigned j = 0; j < 4; ++j)
1682       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1683                              i*RHSStartValue+j+IndexOffset) ||
1684           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1685                              i*RHSStartValue+j+IndexOffset+8))
1686         return false;
1687   return true;
1688 }
1689 
1690 /**
1691  * Determine if the specified shuffle mask is suitable for the vmrgew or
1692  * vmrgow instructions.
1693  *
1694  * \param[in] N The shuffle vector SD Node to analyze
1695  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1696  * \param[in] ShuffleKind Identify the type of merge:
1697  *   - 0 = big-endian merge with two different inputs;
1698  *   - 1 = either-endian merge with two identical inputs;
1699  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1700  *     little-endian merges).
1701  * \param[in] DAG The current SelectionDAG
1702  * \return true iff this shuffle mask
1703  */
1704 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1705                               unsigned ShuffleKind, SelectionDAG &DAG) {
1706   if (DAG.getDataLayout().isLittleEndian()) {
1707     unsigned indexOffset = CheckEven ? 4 : 0;
1708     if (ShuffleKind == 1) // Unary
1709       return isVMerge(N, indexOffset, 0);
1710     else if (ShuffleKind == 2) // swapped
1711       return isVMerge(N, indexOffset, 16);
1712     else
1713       return false;
1714   }
1715   else {
1716     unsigned indexOffset = CheckEven ? 0 : 4;
1717     if (ShuffleKind == 1) // Unary
1718       return isVMerge(N, indexOffset, 0);
1719     else if (ShuffleKind == 0) // Normal
1720       return isVMerge(N, indexOffset, 16);
1721     else
1722       return false;
1723   }
1724   return false;
1725 }
1726 
1727 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1728 /// amount, otherwise return -1.
1729 /// The ShuffleKind distinguishes between big-endian operations with two
1730 /// different inputs (0), either-endian operations with two identical inputs
1731 /// (1), and little-endian operations with two different inputs (2).  For the
1732 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1733 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1734                              SelectionDAG &DAG) {
1735   if (N->getValueType(0) != MVT::v16i8)
1736     return -1;
1737 
1738   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1739 
1740   // Find the first non-undef value in the shuffle mask.
1741   unsigned i;
1742   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1743     /*search*/;
1744 
1745   if (i == 16) return -1;  // all undef.
1746 
1747   // Otherwise, check to see if the rest of the elements are consecutively
1748   // numbered from this value.
1749   unsigned ShiftAmt = SVOp->getMaskElt(i);
1750   if (ShiftAmt < i) return -1;
1751 
1752   ShiftAmt -= i;
1753   bool isLE = DAG.getDataLayout().isLittleEndian();
1754 
1755   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1756     // Check the rest of the elements to see if they are consecutive.
1757     for (++i; i != 16; ++i)
1758       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1759         return -1;
1760   } else if (ShuffleKind == 1) {
1761     // Check the rest of the elements to see if they are consecutive.
1762     for (++i; i != 16; ++i)
1763       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1764         return -1;
1765   } else
1766     return -1;
1767 
1768   if (isLE)
1769     ShiftAmt = 16 - ShiftAmt;
1770 
1771   return ShiftAmt;
1772 }
1773 
1774 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1775 /// specifies a splat of a single element that is suitable for input to
1776 /// VSPLTB/VSPLTH/VSPLTW.
1777 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1778   assert(N->getValueType(0) == MVT::v16i8 &&
1779          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1780 
1781   // The consecutive indices need to specify an element, not part of two
1782   // different elements.  So abandon ship early if this isn't the case.
1783   if (N->getMaskElt(0) % EltSize != 0)
1784     return false;
1785 
1786   // This is a splat operation if each element of the permute is the same, and
1787   // if the value doesn't reference the second vector.
1788   unsigned ElementBase = N->getMaskElt(0);
1789 
1790   // FIXME: Handle UNDEF elements too!
1791   if (ElementBase >= 16)
1792     return false;
1793 
1794   // Check that the indices are consecutive, in the case of a multi-byte element
1795   // splatted with a v16i8 mask.
1796   for (unsigned i = 1; i != EltSize; ++i)
1797     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1798       return false;
1799 
1800   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1801     if (N->getMaskElt(i) < 0) continue;
1802     for (unsigned j = 0; j != EltSize; ++j)
1803       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1804         return false;
1805   }
1806   return true;
1807 }
1808 
1809 /// Check that the mask is shuffling N byte elements. Within each N byte
1810 /// element of the mask, the indices could be either in increasing or
1811 /// decreasing order as long as they are consecutive.
1812 /// \param[in] N the shuffle vector SD Node to analyze
1813 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1814 /// Word/DoubleWord/QuadWord).
1815 /// \param[in] StepLen the delta indices number among the N byte element, if
1816 /// the mask is in increasing/decreasing order then it is 1/-1.
1817 /// \return true iff the mask is shuffling N byte elements.
1818 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1819                                    int StepLen) {
1820   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1821          "Unexpected element width.");
1822   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1823 
1824   unsigned NumOfElem = 16 / Width;
1825   unsigned MaskVal[16]; //  Width is never greater than 16
1826   for (unsigned i = 0; i < NumOfElem; ++i) {
1827     MaskVal[0] = N->getMaskElt(i * Width);
1828     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1829       return false;
1830     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1831       return false;
1832     }
1833 
1834     for (unsigned int j = 1; j < Width; ++j) {
1835       MaskVal[j] = N->getMaskElt(i * Width + j);
1836       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1837         return false;
1838       }
1839     }
1840   }
1841 
1842   return true;
1843 }
1844 
1845 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1846                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1847   if (!isNByteElemShuffleMask(N, 4, 1))
1848     return false;
1849 
1850   // Now we look at mask elements 0,4,8,12
1851   unsigned M0 = N->getMaskElt(0) / 4;
1852   unsigned M1 = N->getMaskElt(4) / 4;
1853   unsigned M2 = N->getMaskElt(8) / 4;
1854   unsigned M3 = N->getMaskElt(12) / 4;
1855   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1856   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1857 
1858   // Below, let H and L be arbitrary elements of the shuffle mask
1859   // where H is in the range [4,7] and L is in the range [0,3].
1860   // H, 1, 2, 3 or L, 5, 6, 7
1861   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1862       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1863     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1864     InsertAtByte = IsLE ? 12 : 0;
1865     Swap = M0 < 4;
1866     return true;
1867   }
1868   // 0, H, 2, 3 or 4, L, 6, 7
1869   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1870       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1871     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1872     InsertAtByte = IsLE ? 8 : 4;
1873     Swap = M1 < 4;
1874     return true;
1875   }
1876   // 0, 1, H, 3 or 4, 5, L, 7
1877   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1878       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1879     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1880     InsertAtByte = IsLE ? 4 : 8;
1881     Swap = M2 < 4;
1882     return true;
1883   }
1884   // 0, 1, 2, H or 4, 5, 6, L
1885   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1886       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1887     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1888     InsertAtByte = IsLE ? 0 : 12;
1889     Swap = M3 < 4;
1890     return true;
1891   }
1892 
1893   // If both vector operands for the shuffle are the same vector, the mask will
1894   // contain only elements from the first one and the second one will be undef.
1895   if (N->getOperand(1).isUndef()) {
1896     ShiftElts = 0;
1897     Swap = true;
1898     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1899     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1900       InsertAtByte = IsLE ? 12 : 0;
1901       return true;
1902     }
1903     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1904       InsertAtByte = IsLE ? 8 : 4;
1905       return true;
1906     }
1907     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1908       InsertAtByte = IsLE ? 4 : 8;
1909       return true;
1910     }
1911     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1912       InsertAtByte = IsLE ? 0 : 12;
1913       return true;
1914     }
1915   }
1916 
1917   return false;
1918 }
1919 
1920 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1921                                bool &Swap, bool IsLE) {
1922   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1923   // Ensure each byte index of the word is consecutive.
1924   if (!isNByteElemShuffleMask(N, 4, 1))
1925     return false;
1926 
1927   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1928   unsigned M0 = N->getMaskElt(0) / 4;
1929   unsigned M1 = N->getMaskElt(4) / 4;
1930   unsigned M2 = N->getMaskElt(8) / 4;
1931   unsigned M3 = N->getMaskElt(12) / 4;
1932 
1933   // If both vector operands for the shuffle are the same vector, the mask will
1934   // contain only elements from the first one and the second one will be undef.
1935   if (N->getOperand(1).isUndef()) {
1936     assert(M0 < 4 && "Indexing into an undef vector?");
1937     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1938       return false;
1939 
1940     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1941     Swap = false;
1942     return true;
1943   }
1944 
1945   // Ensure each word index of the ShuffleVector Mask is consecutive.
1946   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1947     return false;
1948 
1949   if (IsLE) {
1950     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1951       // Input vectors don't need to be swapped if the leading element
1952       // of the result is one of the 3 left elements of the second vector
1953       // (or if there is no shift to be done at all).
1954       Swap = false;
1955       ShiftElts = (8 - M0) % 8;
1956     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1957       // Input vectors need to be swapped if the leading element
1958       // of the result is one of the 3 left elements of the first vector
1959       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1960       Swap = true;
1961       ShiftElts = (4 - M0) % 4;
1962     }
1963 
1964     return true;
1965   } else {                                          // BE
1966     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1967       // Input vectors don't need to be swapped if the leading element
1968       // of the result is one of the 4 elements of the first vector.
1969       Swap = false;
1970       ShiftElts = M0;
1971     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1972       // Input vectors need to be swapped if the leading element
1973       // of the result is one of the 4 elements of the right vector.
1974       Swap = true;
1975       ShiftElts = M0 - 4;
1976     }
1977 
1978     return true;
1979   }
1980 }
1981 
1982 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1983   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1984 
1985   if (!isNByteElemShuffleMask(N, Width, -1))
1986     return false;
1987 
1988   for (int i = 0; i < 16; i += Width)
1989     if (N->getMaskElt(i) != i + Width - 1)
1990       return false;
1991 
1992   return true;
1993 }
1994 
1995 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1996   return isXXBRShuffleMaskHelper(N, 2);
1997 }
1998 
1999 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2000   return isXXBRShuffleMaskHelper(N, 4);
2001 }
2002 
2003 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2004   return isXXBRShuffleMaskHelper(N, 8);
2005 }
2006 
2007 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2008   return isXXBRShuffleMaskHelper(N, 16);
2009 }
2010 
2011 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2012 /// if the inputs to the instruction should be swapped and set \p DM to the
2013 /// value for the immediate.
2014 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2015 /// AND element 0 of the result comes from the first input (LE) or second input
2016 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2017 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2018 /// mask.
2019 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2020                                bool &Swap, bool IsLE) {
2021   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2022 
2023   // Ensure each byte index of the double word is consecutive.
2024   if (!isNByteElemShuffleMask(N, 8, 1))
2025     return false;
2026 
2027   unsigned M0 = N->getMaskElt(0) / 8;
2028   unsigned M1 = N->getMaskElt(8) / 8;
2029   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2030 
2031   // If both vector operands for the shuffle are the same vector, the mask will
2032   // contain only elements from the first one and the second one will be undef.
2033   if (N->getOperand(1).isUndef()) {
2034     if ((M0 | M1) < 2) {
2035       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2036       Swap = false;
2037       return true;
2038     } else
2039       return false;
2040   }
2041 
2042   if (IsLE) {
2043     if (M0 > 1 && M1 < 2) {
2044       Swap = false;
2045     } else if (M0 < 2 && M1 > 1) {
2046       M0 = (M0 + 2) % 4;
2047       M1 = (M1 + 2) % 4;
2048       Swap = true;
2049     } else
2050       return false;
2051 
2052     // Note: if control flow comes here that means Swap is already set above
2053     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2054     return true;
2055   } else { // BE
2056     if (M0 < 2 && M1 > 1) {
2057       Swap = false;
2058     } else if (M0 > 1 && M1 < 2) {
2059       M0 = (M0 + 2) % 4;
2060       M1 = (M1 + 2) % 4;
2061       Swap = true;
2062     } else
2063       return false;
2064 
2065     // Note: if control flow comes here that means Swap is already set above
2066     DM = (M0 << 1) + (M1 & 1);
2067     return true;
2068   }
2069 }
2070 
2071 
2072 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
2073 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
2074 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
2075                                 SelectionDAG &DAG) {
2076   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2077   assert(isSplatShuffleMask(SVOp, EltSize));
2078   if (DAG.getDataLayout().isLittleEndian())
2079     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2080   else
2081     return SVOp->getMaskElt(0) / EltSize;
2082 }
2083 
2084 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2085 /// by using a vspltis[bhw] instruction of the specified element size, return
2086 /// the constant being splatted.  The ByteSize field indicates the number of
2087 /// bytes of each element [124] -> [bhw].
2088 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2089   SDValue OpVal(nullptr, 0);
2090 
2091   // If ByteSize of the splat is bigger than the element size of the
2092   // build_vector, then we have a case where we are checking for a splat where
2093   // multiple elements of the buildvector are folded together into a single
2094   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2095   unsigned EltSize = 16/N->getNumOperands();
2096   if (EltSize < ByteSize) {
2097     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2098     SDValue UniquedVals[4];
2099     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2100 
2101     // See if all of the elements in the buildvector agree across.
2102     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2103       if (N->getOperand(i).isUndef()) continue;
2104       // If the element isn't a constant, bail fully out.
2105       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2106 
2107       if (!UniquedVals[i&(Multiple-1)].getNode())
2108         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2109       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2110         return SDValue();  // no match.
2111     }
2112 
2113     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2114     // either constant or undef values that are identical for each chunk.  See
2115     // if these chunks can form into a larger vspltis*.
2116 
2117     // Check to see if all of the leading entries are either 0 or -1.  If
2118     // neither, then this won't fit into the immediate field.
2119     bool LeadingZero = true;
2120     bool LeadingOnes = true;
2121     for (unsigned i = 0; i != Multiple-1; ++i) {
2122       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2123 
2124       LeadingZero &= isNullConstant(UniquedVals[i]);
2125       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2126     }
2127     // Finally, check the least significant entry.
2128     if (LeadingZero) {
2129       if (!UniquedVals[Multiple-1].getNode())
2130         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2131       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2132       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2133         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2134     }
2135     if (LeadingOnes) {
2136       if (!UniquedVals[Multiple-1].getNode())
2137         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2138       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2139       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2140         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2141     }
2142 
2143     return SDValue();
2144   }
2145 
2146   // Check to see if this buildvec has a single non-undef value in its elements.
2147   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2148     if (N->getOperand(i).isUndef()) continue;
2149     if (!OpVal.getNode())
2150       OpVal = N->getOperand(i);
2151     else if (OpVal != N->getOperand(i))
2152       return SDValue();
2153   }
2154 
2155   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2156 
2157   unsigned ValSizeInBytes = EltSize;
2158   uint64_t Value = 0;
2159   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2160     Value = CN->getZExtValue();
2161   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2162     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2163     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2164   }
2165 
2166   // If the splat value is larger than the element value, then we can never do
2167   // this splat.  The only case that we could fit the replicated bits into our
2168   // immediate field for would be zero, and we prefer to use vxor for it.
2169   if (ValSizeInBytes < ByteSize) return SDValue();
2170 
2171   // If the element value is larger than the splat value, check if it consists
2172   // of a repeated bit pattern of size ByteSize.
2173   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2174     return SDValue();
2175 
2176   // Properly sign extend the value.
2177   int MaskVal = SignExtend32(Value, ByteSize * 8);
2178 
2179   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2180   if (MaskVal == 0) return SDValue();
2181 
2182   // Finally, if this value fits in a 5 bit sext field, return it
2183   if (SignExtend32<5>(MaskVal) == MaskVal)
2184     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2185   return SDValue();
2186 }
2187 
2188 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2189 /// amount, otherwise return -1.
2190 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2191   EVT VT = N->getValueType(0);
2192   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2193     return -1;
2194 
2195   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2196 
2197   // Find the first non-undef value in the shuffle mask.
2198   unsigned i;
2199   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2200     /*search*/;
2201 
2202   if (i == 4) return -1;  // all undef.
2203 
2204   // Otherwise, check to see if the rest of the elements are consecutively
2205   // numbered from this value.
2206   unsigned ShiftAmt = SVOp->getMaskElt(i);
2207   if (ShiftAmt < i) return -1;
2208   ShiftAmt -= i;
2209 
2210   // Check the rest of the elements to see if they are consecutive.
2211   for (++i; i != 4; ++i)
2212     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2213       return -1;
2214 
2215   return ShiftAmt;
2216 }
2217 
2218 //===----------------------------------------------------------------------===//
2219 //  Addressing Mode Selection
2220 //===----------------------------------------------------------------------===//
2221 
2222 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2223 /// or 64-bit immediate, and if the value can be accurately represented as a
2224 /// sign extension from a 16-bit value.  If so, this returns true and the
2225 /// immediate.
2226 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2227   if (!isa<ConstantSDNode>(N))
2228     return false;
2229 
2230   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2231   if (N->getValueType(0) == MVT::i32)
2232     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2233   else
2234     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2235 }
2236 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2237   return isIntS16Immediate(Op.getNode(), Imm);
2238 }
2239 
2240 
2241 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2242 /// be represented as an indexed [r+r] operation.
2243 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2244                                                SDValue &Index,
2245                                                SelectionDAG &DAG) const {
2246   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2247       UI != E; ++UI) {
2248     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2249       if (Memop->getMemoryVT() == MVT::f64) {
2250           Base = N.getOperand(0);
2251           Index = N.getOperand(1);
2252           return true;
2253       }
2254     }
2255   }
2256   return false;
2257 }
2258 
2259 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2260 /// can be represented as an indexed [r+r] operation.  Returns false if it
2261 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2262 /// non-zero and N can be represented by a base register plus a signed 16-bit
2263 /// displacement, make a more precise judgement by checking (displacement % \p
2264 /// EncodingAlignment).
2265 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2266                                             SDValue &Index, SelectionDAG &DAG,
2267                                             unsigned EncodingAlignment) const {
2268   int16_t imm = 0;
2269   if (N.getOpcode() == ISD::ADD) {
2270     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2271     // SPE load/store can only handle 8-bit offsets.
2272     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2273         return true;
2274     if (isIntS16Immediate(N.getOperand(1), imm) &&
2275         (!EncodingAlignment || !(imm % EncodingAlignment)))
2276       return false; // r+i
2277     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2278       return false;    // r+i
2279 
2280     Base = N.getOperand(0);
2281     Index = N.getOperand(1);
2282     return true;
2283   } else if (N.getOpcode() == ISD::OR) {
2284     if (isIntS16Immediate(N.getOperand(1), imm) &&
2285         (!EncodingAlignment || !(imm % EncodingAlignment)))
2286       return false; // r+i can fold it if we can.
2287 
2288     // If this is an or of disjoint bitfields, we can codegen this as an add
2289     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2290     // disjoint.
2291     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2292 
2293     if (LHSKnown.Zero.getBoolValue()) {
2294       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2295       // If all of the bits are known zero on the LHS or RHS, the add won't
2296       // carry.
2297       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2298         Base = N.getOperand(0);
2299         Index = N.getOperand(1);
2300         return true;
2301       }
2302     }
2303   }
2304 
2305   return false;
2306 }
2307 
2308 // If we happen to be doing an i64 load or store into a stack slot that has
2309 // less than a 4-byte alignment, then the frame-index elimination may need to
2310 // use an indexed load or store instruction (because the offset may not be a
2311 // multiple of 4). The extra register needed to hold the offset comes from the
2312 // register scavenger, and it is possible that the scavenger will need to use
2313 // an emergency spill slot. As a result, we need to make sure that a spill slot
2314 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2315 // stack slot.
2316 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2317   // FIXME: This does not handle the LWA case.
2318   if (VT != MVT::i64)
2319     return;
2320 
2321   // NOTE: We'll exclude negative FIs here, which come from argument
2322   // lowering, because there are no known test cases triggering this problem
2323   // using packed structures (or similar). We can remove this exclusion if
2324   // we find such a test case. The reason why this is so test-case driven is
2325   // because this entire 'fixup' is only to prevent crashes (from the
2326   // register scavenger) on not-really-valid inputs. For example, if we have:
2327   //   %a = alloca i1
2328   //   %b = bitcast i1* %a to i64*
2329   //   store i64* a, i64 b
2330   // then the store should really be marked as 'align 1', but is not. If it
2331   // were marked as 'align 1' then the indexed form would have been
2332   // instruction-selected initially, and the problem this 'fixup' is preventing
2333   // won't happen regardless.
2334   if (FrameIdx < 0)
2335     return;
2336 
2337   MachineFunction &MF = DAG.getMachineFunction();
2338   MachineFrameInfo &MFI = MF.getFrameInfo();
2339 
2340   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2341   if (Align >= 4)
2342     return;
2343 
2344   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2345   FuncInfo->setHasNonRISpills();
2346 }
2347 
2348 /// Returns true if the address N can be represented by a base register plus
2349 /// a signed 16-bit displacement [r+imm], and if it is not better
2350 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2351 /// displacements that are multiples of that value.
2352 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2353                                             SDValue &Base,
2354                                             SelectionDAG &DAG,
2355                                             unsigned EncodingAlignment) const {
2356   // FIXME dl should come from parent load or store, not from address
2357   SDLoc dl(N);
2358   // If this can be more profitably realized as r+r, fail.
2359   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2360     return false;
2361 
2362   if (N.getOpcode() == ISD::ADD) {
2363     int16_t imm = 0;
2364     if (isIntS16Immediate(N.getOperand(1), imm) &&
2365         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2366       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2367       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2368         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2369         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2370       } else {
2371         Base = N.getOperand(0);
2372       }
2373       return true; // [r+i]
2374     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2375       // Match LOAD (ADD (X, Lo(G))).
2376       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2377              && "Cannot handle constant offsets yet!");
2378       Disp = N.getOperand(1).getOperand(0);  // The global address.
2379       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2380              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2381              Disp.getOpcode() == ISD::TargetConstantPool ||
2382              Disp.getOpcode() == ISD::TargetJumpTable);
2383       Base = N.getOperand(0);
2384       return true;  // [&g+r]
2385     }
2386   } else if (N.getOpcode() == ISD::OR) {
2387     int16_t imm = 0;
2388     if (isIntS16Immediate(N.getOperand(1), imm) &&
2389         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2390       // If this is an or of disjoint bitfields, we can codegen this as an add
2391       // (for better address arithmetic) if the LHS and RHS of the OR are
2392       // provably disjoint.
2393       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2394 
2395       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2396         // If all of the bits are known zero on the LHS or RHS, the add won't
2397         // carry.
2398         if (FrameIndexSDNode *FI =
2399               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2400           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2401           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2402         } else {
2403           Base = N.getOperand(0);
2404         }
2405         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2406         return true;
2407       }
2408     }
2409   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2410     // Loading from a constant address.
2411 
2412     // If this address fits entirely in a 16-bit sext immediate field, codegen
2413     // this as "d, 0"
2414     int16_t Imm;
2415     if (isIntS16Immediate(CN, Imm) &&
2416         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2417       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2418       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2419                              CN->getValueType(0));
2420       return true;
2421     }
2422 
2423     // Handle 32-bit sext immediates with LIS + addr mode.
2424     if ((CN->getValueType(0) == MVT::i32 ||
2425          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2426         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2427       int Addr = (int)CN->getZExtValue();
2428 
2429       // Otherwise, break this down into an LIS + disp.
2430       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2431 
2432       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2433                                    MVT::i32);
2434       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2435       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2436       return true;
2437     }
2438   }
2439 
2440   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2441   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2442     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2443     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2444   } else
2445     Base = N;
2446   return true;      // [r+0]
2447 }
2448 
2449 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2450 /// represented as an indexed [r+r] operation.
2451 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2452                                                 SDValue &Index,
2453                                                 SelectionDAG &DAG) const {
2454   // Check to see if we can easily represent this as an [r+r] address.  This
2455   // will fail if it thinks that the address is more profitably represented as
2456   // reg+imm, e.g. where imm = 0.
2457   if (SelectAddressRegReg(N, Base, Index, DAG))
2458     return true;
2459 
2460   // If the address is the result of an add, we will utilize the fact that the
2461   // address calculation includes an implicit add.  However, we can reduce
2462   // register pressure if we do not materialize a constant just for use as the
2463   // index register.  We only get rid of the add if it is not an add of a
2464   // value and a 16-bit signed constant and both have a single use.
2465   int16_t imm = 0;
2466   if (N.getOpcode() == ISD::ADD &&
2467       (!isIntS16Immediate(N.getOperand(1), imm) ||
2468        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2469     Base = N.getOperand(0);
2470     Index = N.getOperand(1);
2471     return true;
2472   }
2473 
2474   // Otherwise, do it the hard way, using R0 as the base register.
2475   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2476                          N.getValueType());
2477   Index = N;
2478   return true;
2479 }
2480 
2481 /// Returns true if we should use a direct load into vector instruction
2482 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2483 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2484 
2485   // If there are any other uses other than scalar to vector, then we should
2486   // keep it as a scalar load -> direct move pattern to prevent multiple
2487   // loads.
2488   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2489   if (!LD)
2490     return false;
2491 
2492   EVT MemVT = LD->getMemoryVT();
2493   if (!MemVT.isSimple())
2494     return false;
2495   switch(MemVT.getSimpleVT().SimpleTy) {
2496   case MVT::i64:
2497     break;
2498   case MVT::i32:
2499     if (!ST.hasP8Vector())
2500       return false;
2501     break;
2502   case MVT::i16:
2503   case MVT::i8:
2504     if (!ST.hasP9Vector())
2505       return false;
2506     break;
2507   default:
2508     return false;
2509   }
2510 
2511   SDValue LoadedVal(N, 0);
2512   if (!LoadedVal.hasOneUse())
2513     return false;
2514 
2515   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2516        UI != UE; ++UI)
2517     if (UI.getUse().get().getResNo() == 0 &&
2518         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2519       return false;
2520 
2521   return true;
2522 }
2523 
2524 /// getPreIndexedAddressParts - returns true by value, base pointer and
2525 /// offset pointer and addressing mode by reference if the node's address
2526 /// can be legally represented as pre-indexed load / store address.
2527 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2528                                                   SDValue &Offset,
2529                                                   ISD::MemIndexedMode &AM,
2530                                                   SelectionDAG &DAG) const {
2531   if (DisablePPCPreinc) return false;
2532 
2533   bool isLoad = true;
2534   SDValue Ptr;
2535   EVT VT;
2536   unsigned Alignment;
2537   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2538     Ptr = LD->getBasePtr();
2539     VT = LD->getMemoryVT();
2540     Alignment = LD->getAlignment();
2541   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2542     Ptr = ST->getBasePtr();
2543     VT  = ST->getMemoryVT();
2544     Alignment = ST->getAlignment();
2545     isLoad = false;
2546   } else
2547     return false;
2548 
2549   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2550   // instructions because we can fold these into a more efficient instruction
2551   // instead, (such as LXSD).
2552   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2553     return false;
2554   }
2555 
2556   // PowerPC doesn't have preinc load/store instructions for vectors (except
2557   // for QPX, which does have preinc r+r forms).
2558   if (VT.isVector()) {
2559     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2560       return false;
2561     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2562       AM = ISD::PRE_INC;
2563       return true;
2564     }
2565   }
2566 
2567   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2568     // Common code will reject creating a pre-inc form if the base pointer
2569     // is a frame index, or if N is a store and the base pointer is either
2570     // the same as or a predecessor of the value being stored.  Check for
2571     // those situations here, and try with swapped Base/Offset instead.
2572     bool Swap = false;
2573 
2574     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2575       Swap = true;
2576     else if (!isLoad) {
2577       SDValue Val = cast<StoreSDNode>(N)->getValue();
2578       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2579         Swap = true;
2580     }
2581 
2582     if (Swap)
2583       std::swap(Base, Offset);
2584 
2585     AM = ISD::PRE_INC;
2586     return true;
2587   }
2588 
2589   // LDU/STU can only handle immediates that are a multiple of 4.
2590   if (VT != MVT::i64) {
2591     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2592       return false;
2593   } else {
2594     // LDU/STU need an address with at least 4-byte alignment.
2595     if (Alignment < 4)
2596       return false;
2597 
2598     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2599       return false;
2600   }
2601 
2602   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2603     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2604     // sext i32 to i64 when addr mode is r+i.
2605     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2606         LD->getExtensionType() == ISD::SEXTLOAD &&
2607         isa<ConstantSDNode>(Offset))
2608       return false;
2609   }
2610 
2611   AM = ISD::PRE_INC;
2612   return true;
2613 }
2614 
2615 //===----------------------------------------------------------------------===//
2616 //  LowerOperation implementation
2617 //===----------------------------------------------------------------------===//
2618 
2619 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2620 /// and LoOpFlags to the target MO flags.
2621 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2622                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2623                                const GlobalValue *GV = nullptr) {
2624   HiOpFlags = PPCII::MO_HA;
2625   LoOpFlags = PPCII::MO_LO;
2626 
2627   // Don't use the pic base if not in PIC relocation model.
2628   if (IsPIC) {
2629     HiOpFlags |= PPCII::MO_PIC_FLAG;
2630     LoOpFlags |= PPCII::MO_PIC_FLAG;
2631   }
2632 
2633   // If this is a reference to a global value that requires a non-lazy-ptr, make
2634   // sure that instruction lowering adds it.
2635   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2636     HiOpFlags |= PPCII::MO_NLP_FLAG;
2637     LoOpFlags |= PPCII::MO_NLP_FLAG;
2638 
2639     if (GV->hasHiddenVisibility()) {
2640       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2641       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2642     }
2643   }
2644 }
2645 
2646 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2647                              SelectionDAG &DAG) {
2648   SDLoc DL(HiPart);
2649   EVT PtrVT = HiPart.getValueType();
2650   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2651 
2652   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2653   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2654 
2655   // With PIC, the first instruction is actually "GR+hi(&G)".
2656   if (isPIC)
2657     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2658                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2659 
2660   // Generate non-pic code that has direct accesses to the constant pool.
2661   // The address of the global is just (hi(&g)+lo(&g)).
2662   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2663 }
2664 
2665 static void setUsesTOCBasePtr(MachineFunction &MF) {
2666   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2667   FuncInfo->setUsesTOCBasePtr();
2668 }
2669 
2670 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2671   setUsesTOCBasePtr(DAG.getMachineFunction());
2672 }
2673 
2674 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2675                            SDValue GA) {
2676   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2677   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2678                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2679 
2680   SDValue Ops[] = { GA, Reg };
2681   return DAG.getMemIntrinsicNode(
2682       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2683       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2684       MachineMemOperand::MOLoad);
2685 }
2686 
2687 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2688                                              SelectionDAG &DAG) const {
2689   EVT PtrVT = Op.getValueType();
2690   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2691   const Constant *C = CP->getConstVal();
2692 
2693   // 64-bit SVR4 ABI code is always position-independent.
2694   // The actual address of the GlobalValue is stored in the TOC.
2695   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2696     setUsesTOCBasePtr(DAG);
2697     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2698     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2699   }
2700 
2701   unsigned MOHiFlag, MOLoFlag;
2702   bool IsPIC = isPositionIndependent();
2703   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2704 
2705   if (IsPIC && Subtarget.isSVR4ABI()) {
2706     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2707                                            PPCII::MO_PIC_FLAG);
2708     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2709   }
2710 
2711   SDValue CPIHi =
2712     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2713   SDValue CPILo =
2714     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2715   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2716 }
2717 
2718 // For 64-bit PowerPC, prefer the more compact relative encodings.
2719 // This trades 32 bits per jump table entry for one or two instructions
2720 // on the jump site.
2721 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2722   if (isJumpTableRelative())
2723     return MachineJumpTableInfo::EK_LabelDifference32;
2724 
2725   return TargetLowering::getJumpTableEncoding();
2726 }
2727 
2728 bool PPCTargetLowering::isJumpTableRelative() const {
2729   if (Subtarget.isPPC64())
2730     return true;
2731   return TargetLowering::isJumpTableRelative();
2732 }
2733 
2734 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2735                                                     SelectionDAG &DAG) const {
2736   if (!Subtarget.isPPC64())
2737     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2738 
2739   switch (getTargetMachine().getCodeModel()) {
2740   case CodeModel::Small:
2741   case CodeModel::Medium:
2742     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2743   default:
2744     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2745                        getPointerTy(DAG.getDataLayout()));
2746   }
2747 }
2748 
2749 const MCExpr *
2750 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2751                                                 unsigned JTI,
2752                                                 MCContext &Ctx) const {
2753   if (!Subtarget.isPPC64())
2754     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2755 
2756   switch (getTargetMachine().getCodeModel()) {
2757   case CodeModel::Small:
2758   case CodeModel::Medium:
2759     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2760   default:
2761     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2762   }
2763 }
2764 
2765 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2766   EVT PtrVT = Op.getValueType();
2767   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2768 
2769   // 64-bit SVR4 ABI code is always position-independent.
2770   // The actual address of the GlobalValue is stored in the TOC.
2771   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2772     setUsesTOCBasePtr(DAG);
2773     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2774     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2775   }
2776 
2777   unsigned MOHiFlag, MOLoFlag;
2778   bool IsPIC = isPositionIndependent();
2779   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2780 
2781   if (IsPIC && Subtarget.isSVR4ABI()) {
2782     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2783                                         PPCII::MO_PIC_FLAG);
2784     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2785   }
2786 
2787   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2788   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2789   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2790 }
2791 
2792 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2793                                              SelectionDAG &DAG) const {
2794   EVT PtrVT = Op.getValueType();
2795   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2796   const BlockAddress *BA = BASDN->getBlockAddress();
2797 
2798   // 64-bit SVR4 ABI code is always position-independent.
2799   // The actual BlockAddress is stored in the TOC.
2800   if (Subtarget.isSVR4ABI() &&
2801       (Subtarget.isPPC64() || isPositionIndependent())) {
2802     if (Subtarget.isPPC64())
2803       setUsesTOCBasePtr(DAG);
2804     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2805     return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA);
2806   }
2807 
2808   unsigned MOHiFlag, MOLoFlag;
2809   bool IsPIC = isPositionIndependent();
2810   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2811   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2812   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2813   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2814 }
2815 
2816 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2817                                               SelectionDAG &DAG) const {
2818   // FIXME: TLS addresses currently use medium model code sequences,
2819   // which is the most useful form.  Eventually support for small and
2820   // large models could be added if users need it, at the cost of
2821   // additional complexity.
2822   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2823   if (DAG.getTarget().useEmulatedTLS())
2824     return LowerToTLSEmulatedModel(GA, DAG);
2825 
2826   SDLoc dl(GA);
2827   const GlobalValue *GV = GA->getGlobal();
2828   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2829   bool is64bit = Subtarget.isPPC64();
2830   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2831   PICLevel::Level picLevel = M->getPICLevel();
2832 
2833   const TargetMachine &TM = getTargetMachine();
2834   TLSModel::Model Model = TM.getTLSModel(GV);
2835 
2836   if (Model == TLSModel::LocalExec) {
2837     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2838                                                PPCII::MO_TPREL_HA);
2839     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2840                                                PPCII::MO_TPREL_LO);
2841     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2842                              : DAG.getRegister(PPC::R2, MVT::i32);
2843 
2844     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2845     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2846   }
2847 
2848   if (Model == TLSModel::InitialExec) {
2849     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2850     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2851                                                 PPCII::MO_TLS);
2852     SDValue GOTPtr;
2853     if (is64bit) {
2854       setUsesTOCBasePtr(DAG);
2855       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2856       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2857                            PtrVT, GOTReg, TGA);
2858     } else {
2859       if (!TM.isPositionIndependent())
2860         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2861       else if (picLevel == PICLevel::SmallPIC)
2862         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2863       else
2864         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2865     }
2866     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2867                                    PtrVT, TGA, GOTPtr);
2868     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2869   }
2870 
2871   if (Model == TLSModel::GeneralDynamic) {
2872     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2873     SDValue GOTPtr;
2874     if (is64bit) {
2875       setUsesTOCBasePtr(DAG);
2876       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2877       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2878                                    GOTReg, TGA);
2879     } else {
2880       if (picLevel == PICLevel::SmallPIC)
2881         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2882       else
2883         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2884     }
2885     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2886                        GOTPtr, TGA, TGA);
2887   }
2888 
2889   if (Model == TLSModel::LocalDynamic) {
2890     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2891     SDValue GOTPtr;
2892     if (is64bit) {
2893       setUsesTOCBasePtr(DAG);
2894       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2895       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2896                            GOTReg, TGA);
2897     } else {
2898       if (picLevel == PICLevel::SmallPIC)
2899         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2900       else
2901         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2902     }
2903     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2904                                   PtrVT, GOTPtr, TGA, TGA);
2905     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2906                                       PtrVT, TLSAddr, TGA);
2907     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2908   }
2909 
2910   llvm_unreachable("Unknown TLS model!");
2911 }
2912 
2913 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2914                                               SelectionDAG &DAG) const {
2915   EVT PtrVT = Op.getValueType();
2916   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2917   SDLoc DL(GSDN);
2918   const GlobalValue *GV = GSDN->getGlobal();
2919 
2920   // 64-bit SVR4 ABI code is always position-independent.
2921   // The actual address of the GlobalValue is stored in the TOC.
2922   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2923     setUsesTOCBasePtr(DAG);
2924     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2925     return getTOCEntry(DAG, DL, true, GA);
2926   }
2927 
2928   unsigned MOHiFlag, MOLoFlag;
2929   bool IsPIC = isPositionIndependent();
2930   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2931 
2932   if (IsPIC && Subtarget.isSVR4ABI()) {
2933     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2934                                             GSDN->getOffset(),
2935                                             PPCII::MO_PIC_FLAG);
2936     return getTOCEntry(DAG, DL, false, GA);
2937   }
2938 
2939   SDValue GAHi =
2940     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2941   SDValue GALo =
2942     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2943 
2944   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2945 
2946   // If the global reference is actually to a non-lazy-pointer, we have to do an
2947   // extra load to get the address of the global.
2948   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2949     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2950   return Ptr;
2951 }
2952 
2953 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2954   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2955   SDLoc dl(Op);
2956 
2957   if (Op.getValueType() == MVT::v2i64) {
2958     // When the operands themselves are v2i64 values, we need to do something
2959     // special because VSX has no underlying comparison operations for these.
2960     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2961       // Equality can be handled by casting to the legal type for Altivec
2962       // comparisons, everything else needs to be expanded.
2963       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2964         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2965                  DAG.getSetCC(dl, MVT::v4i32,
2966                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2967                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2968                    CC));
2969       }
2970 
2971       return SDValue();
2972     }
2973 
2974     // We handle most of these in the usual way.
2975     return Op;
2976   }
2977 
2978   // If we're comparing for equality to zero, expose the fact that this is
2979   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2980   // fold the new nodes.
2981   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2982     return V;
2983 
2984   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2985     // Leave comparisons against 0 and -1 alone for now, since they're usually
2986     // optimized.  FIXME: revisit this when we can custom lower all setcc
2987     // optimizations.
2988     if (C->isAllOnesValue() || C->isNullValue())
2989       return SDValue();
2990   }
2991 
2992   // If we have an integer seteq/setne, turn it into a compare against zero
2993   // by xor'ing the rhs with the lhs, which is faster than setting a
2994   // condition register, reading it back out, and masking the correct bit.  The
2995   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2996   // the result to other bit-twiddling opportunities.
2997   EVT LHSVT = Op.getOperand(0).getValueType();
2998   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2999     EVT VT = Op.getValueType();
3000     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3001                                 Op.getOperand(1));
3002     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3003   }
3004   return SDValue();
3005 }
3006 
3007 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3008   SDNode *Node = Op.getNode();
3009   EVT VT = Node->getValueType(0);
3010   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3011   SDValue InChain = Node->getOperand(0);
3012   SDValue VAListPtr = Node->getOperand(1);
3013   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3014   SDLoc dl(Node);
3015 
3016   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3017 
3018   // gpr_index
3019   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3020                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3021   InChain = GprIndex.getValue(1);
3022 
3023   if (VT == MVT::i64) {
3024     // Check if GprIndex is even
3025     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3026                                  DAG.getConstant(1, dl, MVT::i32));
3027     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3028                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3029     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3030                                           DAG.getConstant(1, dl, MVT::i32));
3031     // Align GprIndex to be even if it isn't
3032     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3033                            GprIndex);
3034   }
3035 
3036   // fpr index is 1 byte after gpr
3037   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3038                                DAG.getConstant(1, dl, MVT::i32));
3039 
3040   // fpr
3041   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3042                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3043   InChain = FprIndex.getValue(1);
3044 
3045   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3046                                        DAG.getConstant(8, dl, MVT::i32));
3047 
3048   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3049                                         DAG.getConstant(4, dl, MVT::i32));
3050 
3051   // areas
3052   SDValue OverflowArea =
3053       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3054   InChain = OverflowArea.getValue(1);
3055 
3056   SDValue RegSaveArea =
3057       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3058   InChain = RegSaveArea.getValue(1);
3059 
3060   // select overflow_area if index > 8
3061   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3062                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3063 
3064   // adjustment constant gpr_index * 4/8
3065   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3066                                     VT.isInteger() ? GprIndex : FprIndex,
3067                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3068                                                     MVT::i32));
3069 
3070   // OurReg = RegSaveArea + RegConstant
3071   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3072                                RegConstant);
3073 
3074   // Floating types are 32 bytes into RegSaveArea
3075   if (VT.isFloatingPoint())
3076     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3077                          DAG.getConstant(32, dl, MVT::i32));
3078 
3079   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3080   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3081                                    VT.isInteger() ? GprIndex : FprIndex,
3082                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3083                                                    MVT::i32));
3084 
3085   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3086                               VT.isInteger() ? VAListPtr : FprPtr,
3087                               MachinePointerInfo(SV), MVT::i8);
3088 
3089   // determine if we should load from reg_save_area or overflow_area
3090   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3091 
3092   // increase overflow_area by 4/8 if gpr/fpr > 8
3093   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3094                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3095                                           dl, MVT::i32));
3096 
3097   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3098                              OverflowAreaPlusN);
3099 
3100   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3101                               MachinePointerInfo(), MVT::i32);
3102 
3103   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3104 }
3105 
3106 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3107   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3108 
3109   // We have to copy the entire va_list struct:
3110   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3111   return DAG.getMemcpy(Op.getOperand(0), Op,
3112                        Op.getOperand(1), Op.getOperand(2),
3113                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3114                        false, MachinePointerInfo(), MachinePointerInfo());
3115 }
3116 
3117 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3118                                                   SelectionDAG &DAG) const {
3119   return Op.getOperand(0);
3120 }
3121 
3122 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3123                                                 SelectionDAG &DAG) const {
3124   SDValue Chain = Op.getOperand(0);
3125   SDValue Trmp = Op.getOperand(1); // trampoline
3126   SDValue FPtr = Op.getOperand(2); // nested function
3127   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3128   SDLoc dl(Op);
3129 
3130   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3131   bool isPPC64 = (PtrVT == MVT::i64);
3132   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3133 
3134   TargetLowering::ArgListTy Args;
3135   TargetLowering::ArgListEntry Entry;
3136 
3137   Entry.Ty = IntPtrTy;
3138   Entry.Node = Trmp; Args.push_back(Entry);
3139 
3140   // TrampSize == (isPPC64 ? 48 : 40);
3141   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3142                                isPPC64 ? MVT::i64 : MVT::i32);
3143   Args.push_back(Entry);
3144 
3145   Entry.Node = FPtr; Args.push_back(Entry);
3146   Entry.Node = Nest; Args.push_back(Entry);
3147 
3148   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3149   TargetLowering::CallLoweringInfo CLI(DAG);
3150   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3151       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3152       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3153 
3154   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3155   return CallResult.second;
3156 }
3157 
3158 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3159   MachineFunction &MF = DAG.getMachineFunction();
3160   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3161   EVT PtrVT = getPointerTy(MF.getDataLayout());
3162 
3163   SDLoc dl(Op);
3164 
3165   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3166     // vastart just stores the address of the VarArgsFrameIndex slot into the
3167     // memory location argument.
3168     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3169     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3170     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3171                         MachinePointerInfo(SV));
3172   }
3173 
3174   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3175   // We suppose the given va_list is already allocated.
3176   //
3177   // typedef struct {
3178   //  char gpr;     /* index into the array of 8 GPRs
3179   //                 * stored in the register save area
3180   //                 * gpr=0 corresponds to r3,
3181   //                 * gpr=1 to r4, etc.
3182   //                 */
3183   //  char fpr;     /* index into the array of 8 FPRs
3184   //                 * stored in the register save area
3185   //                 * fpr=0 corresponds to f1,
3186   //                 * fpr=1 to f2, etc.
3187   //                 */
3188   //  char *overflow_arg_area;
3189   //                /* location on stack that holds
3190   //                 * the next overflow argument
3191   //                 */
3192   //  char *reg_save_area;
3193   //               /* where r3:r10 and f1:f8 (if saved)
3194   //                * are stored
3195   //                */
3196   // } va_list[1];
3197 
3198   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3199   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3200   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3201                                             PtrVT);
3202   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3203                                  PtrVT);
3204 
3205   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3206   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3207 
3208   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3209   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3210 
3211   uint64_t FPROffset = 1;
3212   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3213 
3214   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3215 
3216   // Store first byte : number of int regs
3217   SDValue firstStore =
3218       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3219                         MachinePointerInfo(SV), MVT::i8);
3220   uint64_t nextOffset = FPROffset;
3221   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3222                                   ConstFPROffset);
3223 
3224   // Store second byte : number of float regs
3225   SDValue secondStore =
3226       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3227                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3228   nextOffset += StackOffset;
3229   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3230 
3231   // Store second word : arguments given on stack
3232   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3233                                     MachinePointerInfo(SV, nextOffset));
3234   nextOffset += FrameOffset;
3235   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3236 
3237   // Store third word : arguments given in registers
3238   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3239                       MachinePointerInfo(SV, nextOffset));
3240 }
3241 
3242 /// FPR - The set of FP registers that should be allocated for arguments,
3243 /// on Darwin.
3244 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3245                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3246                                 PPC::F11, PPC::F12, PPC::F13};
3247 
3248 /// QFPR - The set of QPX registers that should be allocated for arguments.
3249 static const MCPhysReg QFPR[] = {
3250     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3251     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3252 
3253 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3254 /// the stack.
3255 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3256                                        unsigned PtrByteSize) {
3257   unsigned ArgSize = ArgVT.getStoreSize();
3258   if (Flags.isByVal())
3259     ArgSize = Flags.getByValSize();
3260 
3261   // Round up to multiples of the pointer size, except for array members,
3262   // which are always packed.
3263   if (!Flags.isInConsecutiveRegs())
3264     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3265 
3266   return ArgSize;
3267 }
3268 
3269 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3270 /// on the stack.
3271 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3272                                             ISD::ArgFlagsTy Flags,
3273                                             unsigned PtrByteSize) {
3274   unsigned Align = PtrByteSize;
3275 
3276   // Altivec parameters are padded to a 16 byte boundary.
3277   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3278       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3279       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3280       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3281     Align = 16;
3282   // QPX vector types stored in double-precision are padded to a 32 byte
3283   // boundary.
3284   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3285     Align = 32;
3286 
3287   // ByVal parameters are aligned as requested.
3288   if (Flags.isByVal()) {
3289     unsigned BVAlign = Flags.getByValAlign();
3290     if (BVAlign > PtrByteSize) {
3291       if (BVAlign % PtrByteSize != 0)
3292           llvm_unreachable(
3293             "ByVal alignment is not a multiple of the pointer size");
3294 
3295       Align = BVAlign;
3296     }
3297   }
3298 
3299   // Array members are always packed to their original alignment.
3300   if (Flags.isInConsecutiveRegs()) {
3301     // If the array member was split into multiple registers, the first
3302     // needs to be aligned to the size of the full type.  (Except for
3303     // ppcf128, which is only aligned as its f64 components.)
3304     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3305       Align = OrigVT.getStoreSize();
3306     else
3307       Align = ArgVT.getStoreSize();
3308   }
3309 
3310   return Align;
3311 }
3312 
3313 /// CalculateStackSlotUsed - Return whether this argument will use its
3314 /// stack slot (instead of being passed in registers).  ArgOffset,
3315 /// AvailableFPRs, and AvailableVRs must hold the current argument
3316 /// position, and will be updated to account for this argument.
3317 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3318                                    ISD::ArgFlagsTy Flags,
3319                                    unsigned PtrByteSize,
3320                                    unsigned LinkageSize,
3321                                    unsigned ParamAreaSize,
3322                                    unsigned &ArgOffset,
3323                                    unsigned &AvailableFPRs,
3324                                    unsigned &AvailableVRs, bool HasQPX) {
3325   bool UseMemory = false;
3326 
3327   // Respect alignment of argument on the stack.
3328   unsigned Align =
3329     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3330   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3331   // If there's no space left in the argument save area, we must
3332   // use memory (this check also catches zero-sized arguments).
3333   if (ArgOffset >= LinkageSize + ParamAreaSize)
3334     UseMemory = true;
3335 
3336   // Allocate argument on the stack.
3337   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3338   if (Flags.isInConsecutiveRegsLast())
3339     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3340   // If we overran the argument save area, we must use memory
3341   // (this check catches arguments passed partially in memory)
3342   if (ArgOffset > LinkageSize + ParamAreaSize)
3343     UseMemory = true;
3344 
3345   // However, if the argument is actually passed in an FPR or a VR,
3346   // we don't use memory after all.
3347   if (!Flags.isByVal()) {
3348     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3349         // QPX registers overlap with the scalar FP registers.
3350         (HasQPX && (ArgVT == MVT::v4f32 ||
3351                     ArgVT == MVT::v4f64 ||
3352                     ArgVT == MVT::v4i1)))
3353       if (AvailableFPRs > 0) {
3354         --AvailableFPRs;
3355         return false;
3356       }
3357     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3358         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3359         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3360         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3361       if (AvailableVRs > 0) {
3362         --AvailableVRs;
3363         return false;
3364       }
3365   }
3366 
3367   return UseMemory;
3368 }
3369 
3370 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3371 /// ensure minimum alignment required for target.
3372 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3373                                      unsigned NumBytes) {
3374   unsigned TargetAlign = Lowering->getStackAlignment();
3375   unsigned AlignMask = TargetAlign - 1;
3376   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3377   return NumBytes;
3378 }
3379 
3380 SDValue PPCTargetLowering::LowerFormalArguments(
3381     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3382     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3383     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3384   if (Subtarget.isSVR4ABI()) {
3385     if (Subtarget.isPPC64())
3386       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3387                                          dl, DAG, InVals);
3388     else
3389       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3390                                          dl, DAG, InVals);
3391   } else {
3392     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3393                                        dl, DAG, InVals);
3394   }
3395 }
3396 
3397 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3398     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3399     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3400     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3401 
3402   // 32-bit SVR4 ABI Stack Frame Layout:
3403   //              +-----------------------------------+
3404   //        +-->  |            Back chain             |
3405   //        |     +-----------------------------------+
3406   //        |     | Floating-point register save area |
3407   //        |     +-----------------------------------+
3408   //        |     |    General register save area     |
3409   //        |     +-----------------------------------+
3410   //        |     |          CR save word             |
3411   //        |     +-----------------------------------+
3412   //        |     |         VRSAVE save word          |
3413   //        |     +-----------------------------------+
3414   //        |     |         Alignment padding         |
3415   //        |     +-----------------------------------+
3416   //        |     |     Vector register save area     |
3417   //        |     +-----------------------------------+
3418   //        |     |       Local variable space        |
3419   //        |     +-----------------------------------+
3420   //        |     |        Parameter list area        |
3421   //        |     +-----------------------------------+
3422   //        |     |           LR save word            |
3423   //        |     +-----------------------------------+
3424   // SP-->  +---  |            Back chain             |
3425   //              +-----------------------------------+
3426   //
3427   // Specifications:
3428   //   System V Application Binary Interface PowerPC Processor Supplement
3429   //   AltiVec Technology Programming Interface Manual
3430 
3431   MachineFunction &MF = DAG.getMachineFunction();
3432   MachineFrameInfo &MFI = MF.getFrameInfo();
3433   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3434 
3435   EVT PtrVT = getPointerTy(MF.getDataLayout());
3436   // Potential tail calls could cause overwriting of argument stack slots.
3437   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3438                        (CallConv == CallingConv::Fast));
3439   unsigned PtrByteSize = 4;
3440 
3441   // Assign locations to all of the incoming arguments.
3442   SmallVector<CCValAssign, 16> ArgLocs;
3443   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3444                  *DAG.getContext());
3445 
3446   // Reserve space for the linkage area on the stack.
3447   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3448   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3449   if (useSoftFloat())
3450     CCInfo.PreAnalyzeFormalArguments(Ins);
3451 
3452   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3453   CCInfo.clearWasPPCF128();
3454 
3455   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3456     CCValAssign &VA = ArgLocs[i];
3457 
3458     // Arguments stored in registers.
3459     if (VA.isRegLoc()) {
3460       const TargetRegisterClass *RC;
3461       EVT ValVT = VA.getValVT();
3462 
3463       switch (ValVT.getSimpleVT().SimpleTy) {
3464         default:
3465           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3466         case MVT::i1:
3467         case MVT::i32:
3468           RC = &PPC::GPRCRegClass;
3469           break;
3470         case MVT::f32:
3471           if (Subtarget.hasP8Vector())
3472             RC = &PPC::VSSRCRegClass;
3473           else if (Subtarget.hasSPE())
3474             RC = &PPC::SPE4RCRegClass;
3475           else
3476             RC = &PPC::F4RCRegClass;
3477           break;
3478         case MVT::f64:
3479           if (Subtarget.hasVSX())
3480             RC = &PPC::VSFRCRegClass;
3481           else if (Subtarget.hasSPE())
3482             // SPE passes doubles in GPR pairs.
3483             RC = &PPC::GPRCRegClass;
3484           else
3485             RC = &PPC::F8RCRegClass;
3486           break;
3487         case MVT::v16i8:
3488         case MVT::v8i16:
3489         case MVT::v4i32:
3490           RC = &PPC::VRRCRegClass;
3491           break;
3492         case MVT::v4f32:
3493           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3494           break;
3495         case MVT::v2f64:
3496         case MVT::v2i64:
3497           RC = &PPC::VRRCRegClass;
3498           break;
3499         case MVT::v4f64:
3500           RC = &PPC::QFRCRegClass;
3501           break;
3502         case MVT::v4i1:
3503           RC = &PPC::QBRCRegClass;
3504           break;
3505       }
3506 
3507       SDValue ArgValue;
3508       // Transform the arguments stored in physical registers into
3509       // virtual ones.
3510       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3511         assert(i + 1 < e && "No second half of double precision argument");
3512         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3513         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3514         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3515         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3516         if (!Subtarget.isLittleEndian())
3517           std::swap (ArgValueLo, ArgValueHi);
3518         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3519                                ArgValueHi);
3520       } else {
3521         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3522         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3523                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3524         if (ValVT == MVT::i1)
3525           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3526       }
3527 
3528       InVals.push_back(ArgValue);
3529     } else {
3530       // Argument stored in memory.
3531       assert(VA.isMemLoc());
3532 
3533       // Get the extended size of the argument type in stack
3534       unsigned ArgSize = VA.getLocVT().getStoreSize();
3535       // Get the actual size of the argument type
3536       unsigned ObjSize = VA.getValVT().getStoreSize();
3537       unsigned ArgOffset = VA.getLocMemOffset();
3538       // Stack objects in PPC32 are right justified.
3539       ArgOffset += ArgSize - ObjSize;
3540       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3541 
3542       // Create load nodes to retrieve arguments from the stack.
3543       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3544       InVals.push_back(
3545           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3546     }
3547   }
3548 
3549   // Assign locations to all of the incoming aggregate by value arguments.
3550   // Aggregates passed by value are stored in the local variable space of the
3551   // caller's stack frame, right above the parameter list area.
3552   SmallVector<CCValAssign, 16> ByValArgLocs;
3553   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3554                       ByValArgLocs, *DAG.getContext());
3555 
3556   // Reserve stack space for the allocations in CCInfo.
3557   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3558 
3559   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3560 
3561   // Area that is at least reserved in the caller of this function.
3562   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3563   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3564 
3565   // Set the size that is at least reserved in caller of this function.  Tail
3566   // call optimized function's reserved stack space needs to be aligned so that
3567   // taking the difference between two stack areas will result in an aligned
3568   // stack.
3569   MinReservedArea =
3570       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3571   FuncInfo->setMinReservedArea(MinReservedArea);
3572 
3573   SmallVector<SDValue, 8> MemOps;
3574 
3575   // If the function takes variable number of arguments, make a frame index for
3576   // the start of the first vararg value... for expansion of llvm.va_start.
3577   if (isVarArg) {
3578     static const MCPhysReg GPArgRegs[] = {
3579       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3580       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3581     };
3582     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3583 
3584     static const MCPhysReg FPArgRegs[] = {
3585       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3586       PPC::F8
3587     };
3588     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3589 
3590     if (useSoftFloat() || hasSPE())
3591        NumFPArgRegs = 0;
3592 
3593     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3594     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3595 
3596     // Make room for NumGPArgRegs and NumFPArgRegs.
3597     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3598                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3599 
3600     FuncInfo->setVarArgsStackOffset(
3601       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3602                             CCInfo.getNextStackOffset(), true));
3603 
3604     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3605     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3606 
3607     // The fixed integer arguments of a variadic function are stored to the
3608     // VarArgsFrameIndex on the stack so that they may be loaded by
3609     // dereferencing the result of va_next.
3610     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3611       // Get an existing live-in vreg, or add a new one.
3612       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3613       if (!VReg)
3614         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3615 
3616       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3617       SDValue Store =
3618           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3619       MemOps.push_back(Store);
3620       // Increment the address by four for the next argument to store
3621       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3622       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3623     }
3624 
3625     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3626     // is set.
3627     // The double arguments are stored to the VarArgsFrameIndex
3628     // on the stack.
3629     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3630       // Get an existing live-in vreg, or add a new one.
3631       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3632       if (!VReg)
3633         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3634 
3635       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3636       SDValue Store =
3637           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3638       MemOps.push_back(Store);
3639       // Increment the address by eight for the next argument to store
3640       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3641                                          PtrVT);
3642       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3643     }
3644   }
3645 
3646   if (!MemOps.empty())
3647     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3648 
3649   return Chain;
3650 }
3651 
3652 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3653 // value to MVT::i64 and then truncate to the correct register size.
3654 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3655                                              EVT ObjectVT, SelectionDAG &DAG,
3656                                              SDValue ArgVal,
3657                                              const SDLoc &dl) const {
3658   if (Flags.isSExt())
3659     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3660                          DAG.getValueType(ObjectVT));
3661   else if (Flags.isZExt())
3662     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3663                          DAG.getValueType(ObjectVT));
3664 
3665   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3666 }
3667 
3668 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3669     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3670     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3671     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3672   // TODO: add description of PPC stack frame format, or at least some docs.
3673   //
3674   bool isELFv2ABI = Subtarget.isELFv2ABI();
3675   bool isLittleEndian = Subtarget.isLittleEndian();
3676   MachineFunction &MF = DAG.getMachineFunction();
3677   MachineFrameInfo &MFI = MF.getFrameInfo();
3678   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3679 
3680   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3681          "fastcc not supported on varargs functions");
3682 
3683   EVT PtrVT = getPointerTy(MF.getDataLayout());
3684   // Potential tail calls could cause overwriting of argument stack slots.
3685   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3686                        (CallConv == CallingConv::Fast));
3687   unsigned PtrByteSize = 8;
3688   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3689 
3690   static const MCPhysReg GPR[] = {
3691     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3692     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3693   };
3694   static const MCPhysReg VR[] = {
3695     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3696     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3697   };
3698 
3699   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3700   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3701   const unsigned Num_VR_Regs  = array_lengthof(VR);
3702   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3703 
3704   // Do a first pass over the arguments to determine whether the ABI
3705   // guarantees that our caller has allocated the parameter save area
3706   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3707   // in the ELFv2 ABI, it is true if this is a vararg function or if
3708   // any parameter is located in a stack slot.
3709 
3710   bool HasParameterArea = !isELFv2ABI || isVarArg;
3711   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3712   unsigned NumBytes = LinkageSize;
3713   unsigned AvailableFPRs = Num_FPR_Regs;
3714   unsigned AvailableVRs = Num_VR_Regs;
3715   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3716     if (Ins[i].Flags.isNest())
3717       continue;
3718 
3719     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3720                                PtrByteSize, LinkageSize, ParamAreaSize,
3721                                NumBytes, AvailableFPRs, AvailableVRs,
3722                                Subtarget.hasQPX()))
3723       HasParameterArea = true;
3724   }
3725 
3726   // Add DAG nodes to load the arguments or copy them out of registers.  On
3727   // entry to a function on PPC, the arguments start after the linkage area,
3728   // although the first ones are often in registers.
3729 
3730   unsigned ArgOffset = LinkageSize;
3731   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3732   unsigned &QFPR_idx = FPR_idx;
3733   SmallVector<SDValue, 8> MemOps;
3734   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3735   unsigned CurArgIdx = 0;
3736   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3737     SDValue ArgVal;
3738     bool needsLoad = false;
3739     EVT ObjectVT = Ins[ArgNo].VT;
3740     EVT OrigVT = Ins[ArgNo].ArgVT;
3741     unsigned ObjSize = ObjectVT.getStoreSize();
3742     unsigned ArgSize = ObjSize;
3743     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3744     if (Ins[ArgNo].isOrigArg()) {
3745       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3746       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3747     }
3748     // We re-align the argument offset for each argument, except when using the
3749     // fast calling convention, when we need to make sure we do that only when
3750     // we'll actually use a stack slot.
3751     unsigned CurArgOffset, Align;
3752     auto ComputeArgOffset = [&]() {
3753       /* Respect alignment of argument on the stack.  */
3754       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3755       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3756       CurArgOffset = ArgOffset;
3757     };
3758 
3759     if (CallConv != CallingConv::Fast) {
3760       ComputeArgOffset();
3761 
3762       /* Compute GPR index associated with argument offset.  */
3763       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3764       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3765     }
3766 
3767     // FIXME the codegen can be much improved in some cases.
3768     // We do not have to keep everything in memory.
3769     if (Flags.isByVal()) {
3770       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3771 
3772       if (CallConv == CallingConv::Fast)
3773         ComputeArgOffset();
3774 
3775       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3776       ObjSize = Flags.getByValSize();
3777       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3778       // Empty aggregate parameters do not take up registers.  Examples:
3779       //   struct { } a;
3780       //   union  { } b;
3781       //   int c[0];
3782       // etc.  However, we have to provide a place-holder in InVals, so
3783       // pretend we have an 8-byte item at the current address for that
3784       // purpose.
3785       if (!ObjSize) {
3786         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3787         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3788         InVals.push_back(FIN);
3789         continue;
3790       }
3791 
3792       // Create a stack object covering all stack doublewords occupied
3793       // by the argument.  If the argument is (fully or partially) on
3794       // the stack, or if the argument is fully in registers but the
3795       // caller has allocated the parameter save anyway, we can refer
3796       // directly to the caller's stack frame.  Otherwise, create a
3797       // local copy in our own frame.
3798       int FI;
3799       if (HasParameterArea ||
3800           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3801         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3802       else
3803         FI = MFI.CreateStackObject(ArgSize, Align, false);
3804       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3805 
3806       // Handle aggregates smaller than 8 bytes.
3807       if (ObjSize < PtrByteSize) {
3808         // The value of the object is its address, which differs from the
3809         // address of the enclosing doubleword on big-endian systems.
3810         SDValue Arg = FIN;
3811         if (!isLittleEndian) {
3812           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3813           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3814         }
3815         InVals.push_back(Arg);
3816 
3817         if (GPR_idx != Num_GPR_Regs) {
3818           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3819           FuncInfo->addLiveInAttr(VReg, Flags);
3820           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3821           SDValue Store;
3822 
3823           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3824             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3825                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3826             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3827                                       MachinePointerInfo(&*FuncArg), ObjType);
3828           } else {
3829             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3830             // store the whole register as-is to the parameter save area
3831             // slot.
3832             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3833                                  MachinePointerInfo(&*FuncArg));
3834           }
3835 
3836           MemOps.push_back(Store);
3837         }
3838         // Whether we copied from a register or not, advance the offset
3839         // into the parameter save area by a full doubleword.
3840         ArgOffset += PtrByteSize;
3841         continue;
3842       }
3843 
3844       // The value of the object is its address, which is the address of
3845       // its first stack doubleword.
3846       InVals.push_back(FIN);
3847 
3848       // Store whatever pieces of the object are in registers to memory.
3849       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3850         if (GPR_idx == Num_GPR_Regs)
3851           break;
3852 
3853         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3854         FuncInfo->addLiveInAttr(VReg, Flags);
3855         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3856         SDValue Addr = FIN;
3857         if (j) {
3858           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3859           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3860         }
3861         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3862                                      MachinePointerInfo(&*FuncArg, j));
3863         MemOps.push_back(Store);
3864         ++GPR_idx;
3865       }
3866       ArgOffset += ArgSize;
3867       continue;
3868     }
3869 
3870     switch (ObjectVT.getSimpleVT().SimpleTy) {
3871     default: llvm_unreachable("Unhandled argument type!");
3872     case MVT::i1:
3873     case MVT::i32:
3874     case MVT::i64:
3875       if (Flags.isNest()) {
3876         // The 'nest' parameter, if any, is passed in R11.
3877         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3878         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3879 
3880         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3881           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3882 
3883         break;
3884       }
3885 
3886       // These can be scalar arguments or elements of an integer array type
3887       // passed directly.  Clang may use those instead of "byval" aggregate
3888       // types to avoid forcing arguments to memory unnecessarily.
3889       if (GPR_idx != Num_GPR_Regs) {
3890         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3891         FuncInfo->addLiveInAttr(VReg, Flags);
3892         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3893 
3894         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3895           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3896           // value to MVT::i64 and then truncate to the correct register size.
3897           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3898       } else {
3899         if (CallConv == CallingConv::Fast)
3900           ComputeArgOffset();
3901 
3902         needsLoad = true;
3903         ArgSize = PtrByteSize;
3904       }
3905       if (CallConv != CallingConv::Fast || needsLoad)
3906         ArgOffset += 8;
3907       break;
3908 
3909     case MVT::f32:
3910     case MVT::f64:
3911       // These can be scalar arguments or elements of a float array type
3912       // passed directly.  The latter are used to implement ELFv2 homogenous
3913       // float aggregates.
3914       if (FPR_idx != Num_FPR_Regs) {
3915         unsigned VReg;
3916 
3917         if (ObjectVT == MVT::f32)
3918           VReg = MF.addLiveIn(FPR[FPR_idx],
3919                               Subtarget.hasP8Vector()
3920                                   ? &PPC::VSSRCRegClass
3921                                   : &PPC::F4RCRegClass);
3922         else
3923           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3924                                                 ? &PPC::VSFRCRegClass
3925                                                 : &PPC::F8RCRegClass);
3926 
3927         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3928         ++FPR_idx;
3929       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3930         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3931         // once we support fp <-> gpr moves.
3932 
3933         // This can only ever happen in the presence of f32 array types,
3934         // since otherwise we never run out of FPRs before running out
3935         // of GPRs.
3936         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3937         FuncInfo->addLiveInAttr(VReg, Flags);
3938         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3939 
3940         if (ObjectVT == MVT::f32) {
3941           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3942             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3943                                  DAG.getConstant(32, dl, MVT::i32));
3944           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3945         }
3946 
3947         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3948       } else {
3949         if (CallConv == CallingConv::Fast)
3950           ComputeArgOffset();
3951 
3952         needsLoad = true;
3953       }
3954 
3955       // When passing an array of floats, the array occupies consecutive
3956       // space in the argument area; only round up to the next doubleword
3957       // at the end of the array.  Otherwise, each float takes 8 bytes.
3958       if (CallConv != CallingConv::Fast || needsLoad) {
3959         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3960         ArgOffset += ArgSize;
3961         if (Flags.isInConsecutiveRegsLast())
3962           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3963       }
3964       break;
3965     case MVT::v4f32:
3966     case MVT::v4i32:
3967     case MVT::v8i16:
3968     case MVT::v16i8:
3969     case MVT::v2f64:
3970     case MVT::v2i64:
3971     case MVT::v1i128:
3972     case MVT::f128:
3973       if (!Subtarget.hasQPX()) {
3974         // These can be scalar arguments or elements of a vector array type
3975         // passed directly.  The latter are used to implement ELFv2 homogenous
3976         // vector aggregates.
3977         if (VR_idx != Num_VR_Regs) {
3978           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3979           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3980           ++VR_idx;
3981         } else {
3982           if (CallConv == CallingConv::Fast)
3983             ComputeArgOffset();
3984           needsLoad = true;
3985         }
3986         if (CallConv != CallingConv::Fast || needsLoad)
3987           ArgOffset += 16;
3988         break;
3989       } // not QPX
3990 
3991       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3992              "Invalid QPX parameter type");
3993       LLVM_FALLTHROUGH;
3994 
3995     case MVT::v4f64:
3996     case MVT::v4i1:
3997       // QPX vectors are treated like their scalar floating-point subregisters
3998       // (except that they're larger).
3999       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4000       if (QFPR_idx != Num_QFPR_Regs) {
4001         const TargetRegisterClass *RC;
4002         switch (ObjectVT.getSimpleVT().SimpleTy) {
4003         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4004         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4005         default:         RC = &PPC::QBRCRegClass; break;
4006         }
4007 
4008         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4009         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4010         ++QFPR_idx;
4011       } else {
4012         if (CallConv == CallingConv::Fast)
4013           ComputeArgOffset();
4014         needsLoad = true;
4015       }
4016       if (CallConv != CallingConv::Fast || needsLoad)
4017         ArgOffset += Sz;
4018       break;
4019     }
4020 
4021     // We need to load the argument to a virtual register if we determined
4022     // above that we ran out of physical registers of the appropriate type.
4023     if (needsLoad) {
4024       if (ObjSize < ArgSize && !isLittleEndian)
4025         CurArgOffset += ArgSize - ObjSize;
4026       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4027       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4028       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4029     }
4030 
4031     InVals.push_back(ArgVal);
4032   }
4033 
4034   // Area that is at least reserved in the caller of this function.
4035   unsigned MinReservedArea;
4036   if (HasParameterArea)
4037     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4038   else
4039     MinReservedArea = LinkageSize;
4040 
4041   // Set the size that is at least reserved in caller of this function.  Tail
4042   // call optimized functions' reserved stack space needs to be aligned so that
4043   // taking the difference between two stack areas will result in an aligned
4044   // stack.
4045   MinReservedArea =
4046       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4047   FuncInfo->setMinReservedArea(MinReservedArea);
4048 
4049   // If the function takes variable number of arguments, make a frame index for
4050   // the start of the first vararg value... for expansion of llvm.va_start.
4051   if (isVarArg) {
4052     int Depth = ArgOffset;
4053 
4054     FuncInfo->setVarArgsFrameIndex(
4055       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4056     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4057 
4058     // If this function is vararg, store any remaining integer argument regs
4059     // to their spots on the stack so that they may be loaded by dereferencing
4060     // the result of va_next.
4061     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4062          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4063       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4064       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4065       SDValue Store =
4066           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4067       MemOps.push_back(Store);
4068       // Increment the address by four for the next argument to store
4069       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4070       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4071     }
4072   }
4073 
4074   if (!MemOps.empty())
4075     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4076 
4077   return Chain;
4078 }
4079 
4080 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4081     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4082     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4083     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4084   // TODO: add description of PPC stack frame format, or at least some docs.
4085   //
4086   MachineFunction &MF = DAG.getMachineFunction();
4087   MachineFrameInfo &MFI = MF.getFrameInfo();
4088   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4089 
4090   EVT PtrVT = getPointerTy(MF.getDataLayout());
4091   bool isPPC64 = PtrVT == MVT::i64;
4092   // Potential tail calls could cause overwriting of argument stack slots.
4093   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4094                        (CallConv == CallingConv::Fast));
4095   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4096   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4097   unsigned ArgOffset = LinkageSize;
4098   // Area that is at least reserved in caller of this function.
4099   unsigned MinReservedArea = ArgOffset;
4100 
4101   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4102     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4103     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4104   };
4105   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4106     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4107     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4108   };
4109   static const MCPhysReg VR[] = {
4110     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4111     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4112   };
4113 
4114   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4115   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4116   const unsigned Num_VR_Regs  = array_lengthof( VR);
4117 
4118   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4119 
4120   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4121 
4122   // In 32-bit non-varargs functions, the stack space for vectors is after the
4123   // stack space for non-vectors.  We do not use this space unless we have
4124   // too many vectors to fit in registers, something that only occurs in
4125   // constructed examples:), but we have to walk the arglist to figure
4126   // that out...for the pathological case, compute VecArgOffset as the
4127   // start of the vector parameter area.  Computing VecArgOffset is the
4128   // entire point of the following loop.
4129   unsigned VecArgOffset = ArgOffset;
4130   if (!isVarArg && !isPPC64) {
4131     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4132          ++ArgNo) {
4133       EVT ObjectVT = Ins[ArgNo].VT;
4134       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4135 
4136       if (Flags.isByVal()) {
4137         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4138         unsigned ObjSize = Flags.getByValSize();
4139         unsigned ArgSize =
4140                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4141         VecArgOffset += ArgSize;
4142         continue;
4143       }
4144 
4145       switch(ObjectVT.getSimpleVT().SimpleTy) {
4146       default: llvm_unreachable("Unhandled argument type!");
4147       case MVT::i1:
4148       case MVT::i32:
4149       case MVT::f32:
4150         VecArgOffset += 4;
4151         break;
4152       case MVT::i64:  // PPC64
4153       case MVT::f64:
4154         // FIXME: We are guaranteed to be !isPPC64 at this point.
4155         // Does MVT::i64 apply?
4156         VecArgOffset += 8;
4157         break;
4158       case MVT::v4f32:
4159       case MVT::v4i32:
4160       case MVT::v8i16:
4161       case MVT::v16i8:
4162         // Nothing to do, we're only looking at Nonvector args here.
4163         break;
4164       }
4165     }
4166   }
4167   // We've found where the vector parameter area in memory is.  Skip the
4168   // first 12 parameters; these don't use that memory.
4169   VecArgOffset = ((VecArgOffset+15)/16)*16;
4170   VecArgOffset += 12*16;
4171 
4172   // Add DAG nodes to load the arguments or copy them out of registers.  On
4173   // entry to a function on PPC, the arguments start after the linkage area,
4174   // although the first ones are often in registers.
4175 
4176   SmallVector<SDValue, 8> MemOps;
4177   unsigned nAltivecParamsAtEnd = 0;
4178   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4179   unsigned CurArgIdx = 0;
4180   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4181     SDValue ArgVal;
4182     bool needsLoad = false;
4183     EVT ObjectVT = Ins[ArgNo].VT;
4184     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4185     unsigned ArgSize = ObjSize;
4186     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4187     if (Ins[ArgNo].isOrigArg()) {
4188       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4189       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4190     }
4191     unsigned CurArgOffset = ArgOffset;
4192 
4193     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4194     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4195         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4196       if (isVarArg || isPPC64) {
4197         MinReservedArea = ((MinReservedArea+15)/16)*16;
4198         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4199                                                   Flags,
4200                                                   PtrByteSize);
4201       } else  nAltivecParamsAtEnd++;
4202     } else
4203       // Calculate min reserved area.
4204       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4205                                                 Flags,
4206                                                 PtrByteSize);
4207 
4208     // FIXME the codegen can be much improved in some cases.
4209     // We do not have to keep everything in memory.
4210     if (Flags.isByVal()) {
4211       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4212 
4213       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4214       ObjSize = Flags.getByValSize();
4215       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4216       // Objects of size 1 and 2 are right justified, everything else is
4217       // left justified.  This means the memory address is adjusted forwards.
4218       if (ObjSize==1 || ObjSize==2) {
4219         CurArgOffset = CurArgOffset + (4 - ObjSize);
4220       }
4221       // The value of the object is its address.
4222       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4223       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4224       InVals.push_back(FIN);
4225       if (ObjSize==1 || ObjSize==2) {
4226         if (GPR_idx != Num_GPR_Regs) {
4227           unsigned VReg;
4228           if (isPPC64)
4229             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4230           else
4231             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4232           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4233           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4234           SDValue Store =
4235               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4236                                 MachinePointerInfo(&*FuncArg), ObjType);
4237           MemOps.push_back(Store);
4238           ++GPR_idx;
4239         }
4240 
4241         ArgOffset += PtrByteSize;
4242 
4243         continue;
4244       }
4245       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4246         // Store whatever pieces of the object are in registers
4247         // to memory.  ArgOffset will be the address of the beginning
4248         // of the object.
4249         if (GPR_idx != Num_GPR_Regs) {
4250           unsigned VReg;
4251           if (isPPC64)
4252             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4253           else
4254             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4255           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4256           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4257           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4258           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4259                                        MachinePointerInfo(&*FuncArg, j));
4260           MemOps.push_back(Store);
4261           ++GPR_idx;
4262           ArgOffset += PtrByteSize;
4263         } else {
4264           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4265           break;
4266         }
4267       }
4268       continue;
4269     }
4270 
4271     switch (ObjectVT.getSimpleVT().SimpleTy) {
4272     default: llvm_unreachable("Unhandled argument type!");
4273     case MVT::i1:
4274     case MVT::i32:
4275       if (!isPPC64) {
4276         if (GPR_idx != Num_GPR_Regs) {
4277           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4278           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4279 
4280           if (ObjectVT == MVT::i1)
4281             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4282 
4283           ++GPR_idx;
4284         } else {
4285           needsLoad = true;
4286           ArgSize = PtrByteSize;
4287         }
4288         // All int arguments reserve stack space in the Darwin ABI.
4289         ArgOffset += PtrByteSize;
4290         break;
4291       }
4292       LLVM_FALLTHROUGH;
4293     case MVT::i64:  // PPC64
4294       if (GPR_idx != Num_GPR_Regs) {
4295         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4296         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4297 
4298         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4299           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4300           // value to MVT::i64 and then truncate to the correct register size.
4301           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4302 
4303         ++GPR_idx;
4304       } else {
4305         needsLoad = true;
4306         ArgSize = PtrByteSize;
4307       }
4308       // All int arguments reserve stack space in the Darwin ABI.
4309       ArgOffset += 8;
4310       break;
4311 
4312     case MVT::f32:
4313     case MVT::f64:
4314       // Every 4 bytes of argument space consumes one of the GPRs available for
4315       // argument passing.
4316       if (GPR_idx != Num_GPR_Regs) {
4317         ++GPR_idx;
4318         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4319           ++GPR_idx;
4320       }
4321       if (FPR_idx != Num_FPR_Regs) {
4322         unsigned VReg;
4323 
4324         if (ObjectVT == MVT::f32)
4325           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4326         else
4327           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4328 
4329         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4330         ++FPR_idx;
4331       } else {
4332         needsLoad = true;
4333       }
4334 
4335       // All FP arguments reserve stack space in the Darwin ABI.
4336       ArgOffset += isPPC64 ? 8 : ObjSize;
4337       break;
4338     case MVT::v4f32:
4339     case MVT::v4i32:
4340     case MVT::v8i16:
4341     case MVT::v16i8:
4342       // Note that vector arguments in registers don't reserve stack space,
4343       // except in varargs functions.
4344       if (VR_idx != Num_VR_Regs) {
4345         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4346         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4347         if (isVarArg) {
4348           while ((ArgOffset % 16) != 0) {
4349             ArgOffset += PtrByteSize;
4350             if (GPR_idx != Num_GPR_Regs)
4351               GPR_idx++;
4352           }
4353           ArgOffset += 16;
4354           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4355         }
4356         ++VR_idx;
4357       } else {
4358         if (!isVarArg && !isPPC64) {
4359           // Vectors go after all the nonvectors.
4360           CurArgOffset = VecArgOffset;
4361           VecArgOffset += 16;
4362         } else {
4363           // Vectors are aligned.
4364           ArgOffset = ((ArgOffset+15)/16)*16;
4365           CurArgOffset = ArgOffset;
4366           ArgOffset += 16;
4367         }
4368         needsLoad = true;
4369       }
4370       break;
4371     }
4372 
4373     // We need to load the argument to a virtual register if we determined above
4374     // that we ran out of physical registers of the appropriate type.
4375     if (needsLoad) {
4376       int FI = MFI.CreateFixedObject(ObjSize,
4377                                      CurArgOffset + (ArgSize - ObjSize),
4378                                      isImmutable);
4379       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4380       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4381     }
4382 
4383     InVals.push_back(ArgVal);
4384   }
4385 
4386   // Allow for Altivec parameters at the end, if needed.
4387   if (nAltivecParamsAtEnd) {
4388     MinReservedArea = ((MinReservedArea+15)/16)*16;
4389     MinReservedArea += 16*nAltivecParamsAtEnd;
4390   }
4391 
4392   // Area that is at least reserved in the caller of this function.
4393   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4394 
4395   // Set the size that is at least reserved in caller of this function.  Tail
4396   // call optimized functions' reserved stack space needs to be aligned so that
4397   // taking the difference between two stack areas will result in an aligned
4398   // stack.
4399   MinReservedArea =
4400       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4401   FuncInfo->setMinReservedArea(MinReservedArea);
4402 
4403   // If the function takes variable number of arguments, make a frame index for
4404   // the start of the first vararg value... for expansion of llvm.va_start.
4405   if (isVarArg) {
4406     int Depth = ArgOffset;
4407 
4408     FuncInfo->setVarArgsFrameIndex(
4409       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4410                             Depth, true));
4411     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4412 
4413     // If this function is vararg, store any remaining integer argument regs
4414     // to their spots on the stack so that they may be loaded by dereferencing
4415     // the result of va_next.
4416     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4417       unsigned VReg;
4418 
4419       if (isPPC64)
4420         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4421       else
4422         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4423 
4424       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4425       SDValue Store =
4426           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4427       MemOps.push_back(Store);
4428       // Increment the address by four for the next argument to store
4429       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4430       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4431     }
4432   }
4433 
4434   if (!MemOps.empty())
4435     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4436 
4437   return Chain;
4438 }
4439 
4440 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4441 /// adjusted to accommodate the arguments for the tailcall.
4442 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4443                                    unsigned ParamSize) {
4444 
4445   if (!isTailCall) return 0;
4446 
4447   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4448   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4449   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4450   // Remember only if the new adjustment is bigger.
4451   if (SPDiff < FI->getTailCallSPDelta())
4452     FI->setTailCallSPDelta(SPDiff);
4453 
4454   return SPDiff;
4455 }
4456 
4457 static bool isFunctionGlobalAddress(SDValue Callee);
4458 
4459 static bool
4460 callsShareTOCBase(const Function *Caller, SDValue Callee,
4461                     const TargetMachine &TM) {
4462    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4463    // don't have enough information to determine if the caller and calle share
4464    // the same  TOC base, so we have to pessimistically assume they don't for
4465    // correctness.
4466    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4467    if (!G)
4468      return false;
4469 
4470    const GlobalValue *GV = G->getGlobal();
4471   // The medium and large code models are expected to provide a sufficiently
4472   // large TOC to provide all data addressing needs of a module with a
4473   // single TOC. Since each module will be addressed with a single TOC then we
4474   // only need to check that caller and callee don't cross dso boundaries.
4475   if (CodeModel::Medium == TM.getCodeModel() ||
4476       CodeModel::Large == TM.getCodeModel())
4477     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4478 
4479   // Otherwise we need to ensure callee and caller are in the same section,
4480   // since the linker may allocate multiple TOCs, and we don't know which
4481   // sections will belong to the same TOC base.
4482 
4483   if (!GV->isStrongDefinitionForLinker())
4484     return false;
4485 
4486   // Any explicitly-specified sections and section prefixes must also match.
4487   // Also, if we're using -ffunction-sections, then each function is always in
4488   // a different section (the same is true for COMDAT functions).
4489   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4490       GV->getSection() != Caller->getSection())
4491     return false;
4492   if (const auto *F = dyn_cast<Function>(GV)) {
4493     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4494       return false;
4495   }
4496 
4497   // If the callee might be interposed, then we can't assume the ultimate call
4498   // target will be in the same section. Even in cases where we can assume that
4499   // interposition won't happen, in any case where the linker might insert a
4500   // stub to allow for interposition, we must generate code as though
4501   // interposition might occur. To understand why this matters, consider a
4502   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4503   // in the same section, but a is in a different module (i.e. has a different
4504   // TOC base pointer). If the linker allows for interposition between b and c,
4505   // then it will generate a stub for the call edge between b and c which will
4506   // save the TOC pointer into the designated stack slot allocated by b. If we
4507   // return true here, and therefore allow a tail call between b and c, that
4508   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4509   // pointer into the stack slot allocated by a (where the a -> b stub saved
4510   // a's TOC base pointer). If we're not considering a tail call, but rather,
4511   // whether a nop is needed after the call instruction in b, because the linker
4512   // will insert a stub, it might complain about a missing nop if we omit it
4513   // (although many don't complain in this case).
4514   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4515     return false;
4516 
4517   return true;
4518 }
4519 
4520 static bool
4521 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4522                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4523   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4524 
4525   const unsigned PtrByteSize = 8;
4526   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4527 
4528   static const MCPhysReg GPR[] = {
4529     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4530     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4531   };
4532   static const MCPhysReg VR[] = {
4533     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4534     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4535   };
4536 
4537   const unsigned NumGPRs = array_lengthof(GPR);
4538   const unsigned NumFPRs = 13;
4539   const unsigned NumVRs = array_lengthof(VR);
4540   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4541 
4542   unsigned NumBytes = LinkageSize;
4543   unsigned AvailableFPRs = NumFPRs;
4544   unsigned AvailableVRs = NumVRs;
4545 
4546   for (const ISD::OutputArg& Param : Outs) {
4547     if (Param.Flags.isNest()) continue;
4548 
4549     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4550                                PtrByteSize, LinkageSize, ParamAreaSize,
4551                                NumBytes, AvailableFPRs, AvailableVRs,
4552                                Subtarget.hasQPX()))
4553       return true;
4554   }
4555   return false;
4556 }
4557 
4558 static bool
4559 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4560   if (CS.arg_size() != CallerFn->arg_size())
4561     return false;
4562 
4563   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4564   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4565   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4566 
4567   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4568     const Value* CalleeArg = *CalleeArgIter;
4569     const Value* CallerArg = &(*CallerArgIter);
4570     if (CalleeArg == CallerArg)
4571       continue;
4572 
4573     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4574     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4575     //      }
4576     // 1st argument of callee is undef and has the same type as caller.
4577     if (CalleeArg->getType() == CallerArg->getType() &&
4578         isa<UndefValue>(CalleeArg))
4579       continue;
4580 
4581     return false;
4582   }
4583 
4584   return true;
4585 }
4586 
4587 // Returns true if TCO is possible between the callers and callees
4588 // calling conventions.
4589 static bool
4590 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4591                                     CallingConv::ID CalleeCC) {
4592   // Tail calls are possible with fastcc and ccc.
4593   auto isTailCallableCC  = [] (CallingConv::ID CC){
4594       return  CC == CallingConv::C || CC == CallingConv::Fast;
4595   };
4596   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4597     return false;
4598 
4599   // We can safely tail call both fastcc and ccc callees from a c calling
4600   // convention caller. If the caller is fastcc, we may have less stack space
4601   // than a non-fastcc caller with the same signature so disable tail-calls in
4602   // that case.
4603   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4604 }
4605 
4606 bool
4607 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4608                                     SDValue Callee,
4609                                     CallingConv::ID CalleeCC,
4610                                     ImmutableCallSite CS,
4611                                     bool isVarArg,
4612                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4613                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4614                                     SelectionDAG& DAG) const {
4615   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4616 
4617   if (DisableSCO && !TailCallOpt) return false;
4618 
4619   // Variadic argument functions are not supported.
4620   if (isVarArg) return false;
4621 
4622   auto &Caller = DAG.getMachineFunction().getFunction();
4623   // Check that the calling conventions are compatible for tco.
4624   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4625     return false;
4626 
4627   // Caller contains any byval parameter is not supported.
4628   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4629     return false;
4630 
4631   // Callee contains any byval parameter is not supported, too.
4632   // Note: This is a quick work around, because in some cases, e.g.
4633   // caller's stack size > callee's stack size, we are still able to apply
4634   // sibling call optimization. For example, gcc is able to do SCO for caller1
4635   // in the following example, but not for caller2.
4636   //   struct test {
4637   //     long int a;
4638   //     char ary[56];
4639   //   } gTest;
4640   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4641   //     b->a = v.a;
4642   //     return 0;
4643   //   }
4644   //   void caller1(struct test a, struct test c, struct test *b) {
4645   //     callee(gTest, b); }
4646   //   void caller2(struct test *b) { callee(gTest, b); }
4647   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4648     return false;
4649 
4650   // If callee and caller use different calling conventions, we cannot pass
4651   // parameters on stack since offsets for the parameter area may be different.
4652   if (Caller.getCallingConv() != CalleeCC &&
4653       needStackSlotPassParameters(Subtarget, Outs))
4654     return false;
4655 
4656   // No TCO/SCO on indirect call because Caller have to restore its TOC
4657   if (!isFunctionGlobalAddress(Callee) &&
4658       !isa<ExternalSymbolSDNode>(Callee))
4659     return false;
4660 
4661   // If the caller and callee potentially have different TOC bases then we
4662   // cannot tail call since we need to restore the TOC pointer after the call.
4663   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4664   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4665     return false;
4666 
4667   // TCO allows altering callee ABI, so we don't have to check further.
4668   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4669     return true;
4670 
4671   if (DisableSCO) return false;
4672 
4673   // If callee use the same argument list that caller is using, then we can
4674   // apply SCO on this case. If it is not, then we need to check if callee needs
4675   // stack for passing arguments.
4676   if (!hasSameArgumentList(&Caller, CS) &&
4677       needStackSlotPassParameters(Subtarget, Outs)) {
4678     return false;
4679   }
4680 
4681   return true;
4682 }
4683 
4684 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4685 /// for tail call optimization. Targets which want to do tail call
4686 /// optimization should implement this function.
4687 bool
4688 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4689                                                      CallingConv::ID CalleeCC,
4690                                                      bool isVarArg,
4691                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4692                                                      SelectionDAG& DAG) const {
4693   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4694     return false;
4695 
4696   // Variable argument functions are not supported.
4697   if (isVarArg)
4698     return false;
4699 
4700   MachineFunction &MF = DAG.getMachineFunction();
4701   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4702   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4703     // Functions containing by val parameters are not supported.
4704     for (unsigned i = 0; i != Ins.size(); i++) {
4705        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4706        if (Flags.isByVal()) return false;
4707     }
4708 
4709     // Non-PIC/GOT tail calls are supported.
4710     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4711       return true;
4712 
4713     // At the moment we can only do local tail calls (in same module, hidden
4714     // or protected) if we are generating PIC.
4715     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4716       return G->getGlobal()->hasHiddenVisibility()
4717           || G->getGlobal()->hasProtectedVisibility();
4718   }
4719 
4720   return false;
4721 }
4722 
4723 /// isCallCompatibleAddress - Return the immediate to use if the specified
4724 /// 32-bit value is representable in the immediate field of a BxA instruction.
4725 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4726   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4727   if (!C) return nullptr;
4728 
4729   int Addr = C->getZExtValue();
4730   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4731       SignExtend32<26>(Addr) != Addr)
4732     return nullptr;  // Top 6 bits have to be sext of immediate.
4733 
4734   return DAG
4735       .getConstant(
4736           (int)C->getZExtValue() >> 2, SDLoc(Op),
4737           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4738       .getNode();
4739 }
4740 
4741 namespace {
4742 
4743 struct TailCallArgumentInfo {
4744   SDValue Arg;
4745   SDValue FrameIdxOp;
4746   int FrameIdx = 0;
4747 
4748   TailCallArgumentInfo() = default;
4749 };
4750 
4751 } // end anonymous namespace
4752 
4753 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4754 static void StoreTailCallArgumentsToStackSlot(
4755     SelectionDAG &DAG, SDValue Chain,
4756     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4757     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4758   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4759     SDValue Arg = TailCallArgs[i].Arg;
4760     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4761     int FI = TailCallArgs[i].FrameIdx;
4762     // Store relative to framepointer.
4763     MemOpChains.push_back(DAG.getStore(
4764         Chain, dl, Arg, FIN,
4765         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4766   }
4767 }
4768 
4769 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4770 /// the appropriate stack slot for the tail call optimized function call.
4771 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4772                                              SDValue OldRetAddr, SDValue OldFP,
4773                                              int SPDiff, const SDLoc &dl) {
4774   if (SPDiff) {
4775     // Calculate the new stack slot for the return address.
4776     MachineFunction &MF = DAG.getMachineFunction();
4777     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4778     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4779     bool isPPC64 = Subtarget.isPPC64();
4780     int SlotSize = isPPC64 ? 8 : 4;
4781     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4782     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4783                                                          NewRetAddrLoc, true);
4784     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4785     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4786     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4787                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4788 
4789     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4790     // slot as the FP is never overwritten.
4791     if (Subtarget.isDarwinABI()) {
4792       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4793       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4794                                                          true);
4795       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4796       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4797                            MachinePointerInfo::getFixedStack(
4798                                DAG.getMachineFunction(), NewFPIdx));
4799     }
4800   }
4801   return Chain;
4802 }
4803 
4804 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4805 /// the position of the argument.
4806 static void
4807 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4808                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4809                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4810   int Offset = ArgOffset + SPDiff;
4811   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4812   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4813   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4814   SDValue FIN = DAG.getFrameIndex(FI, VT);
4815   TailCallArgumentInfo Info;
4816   Info.Arg = Arg;
4817   Info.FrameIdxOp = FIN;
4818   Info.FrameIdx = FI;
4819   TailCallArguments.push_back(Info);
4820 }
4821 
4822 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4823 /// stack slot. Returns the chain as result and the loaded frame pointers in
4824 /// LROpOut/FPOpout. Used when tail calling.
4825 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4826     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4827     SDValue &FPOpOut, const SDLoc &dl) const {
4828   if (SPDiff) {
4829     // Load the LR and FP stack slot for later adjusting.
4830     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4831     LROpOut = getReturnAddrFrameIndex(DAG);
4832     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4833     Chain = SDValue(LROpOut.getNode(), 1);
4834 
4835     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4836     // slot as the FP is never overwritten.
4837     if (Subtarget.isDarwinABI()) {
4838       FPOpOut = getFramePointerFrameIndex(DAG);
4839       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4840       Chain = SDValue(FPOpOut.getNode(), 1);
4841     }
4842   }
4843   return Chain;
4844 }
4845 
4846 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4847 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4848 /// specified by the specific parameter attribute. The copy will be passed as
4849 /// a byval function parameter.
4850 /// Sometimes what we are copying is the end of a larger object, the part that
4851 /// does not fit in registers.
4852 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4853                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4854                                          SelectionDAG &DAG, const SDLoc &dl) {
4855   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4856   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4857                        false, false, false, MachinePointerInfo(),
4858                        MachinePointerInfo());
4859 }
4860 
4861 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4862 /// tail calls.
4863 static void LowerMemOpCallTo(
4864     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4865     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4866     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4867     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4868   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4869   if (!isTailCall) {
4870     if (isVector) {
4871       SDValue StackPtr;
4872       if (isPPC64)
4873         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4874       else
4875         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4876       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4877                            DAG.getConstant(ArgOffset, dl, PtrVT));
4878     }
4879     MemOpChains.push_back(
4880         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4881     // Calculate and remember argument location.
4882   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4883                                   TailCallArguments);
4884 }
4885 
4886 static void
4887 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4888                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4889                 SDValue FPOp,
4890                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4891   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4892   // might overwrite each other in case of tail call optimization.
4893   SmallVector<SDValue, 8> MemOpChains2;
4894   // Do not flag preceding copytoreg stuff together with the following stuff.
4895   InFlag = SDValue();
4896   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4897                                     MemOpChains2, dl);
4898   if (!MemOpChains2.empty())
4899     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4900 
4901   // Store the return address to the appropriate stack slot.
4902   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4903 
4904   // Emit callseq_end just before tailcall node.
4905   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4906                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4907   InFlag = Chain.getValue(1);
4908 }
4909 
4910 // Is this global address that of a function that can be called by name? (as
4911 // opposed to something that must hold a descriptor for an indirect call).
4912 static bool isFunctionGlobalAddress(SDValue Callee) {
4913   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4914     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4915         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4916       return false;
4917 
4918     return G->getGlobal()->getValueType()->isFunctionTy();
4919   }
4920 
4921   return false;
4922 }
4923 
4924 static unsigned
4925 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4926             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4927             bool isPatchPoint, bool hasNest,
4928             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4929             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4930             ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4931   bool isPPC64 = Subtarget.isPPC64();
4932   bool isSVR4ABI = Subtarget.isSVR4ABI();
4933   bool isELFv2ABI = Subtarget.isELFv2ABI();
4934   bool isAIXABI = Subtarget.isAIXABI();
4935 
4936   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4937   NodeTys.push_back(MVT::Other);   // Returns a chain
4938   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4939 
4940   unsigned CallOpc = PPCISD::CALL;
4941 
4942   bool needIndirectCall = true;
4943   if (!isSVR4ABI || !isPPC64)
4944     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4945       // If this is an absolute destination address, use the munged value.
4946       Callee = SDValue(Dest, 0);
4947       needIndirectCall = false;
4948     }
4949 
4950   // PC-relative references to external symbols should go through $stub, unless
4951   // we're building with the leopard linker or later, which automatically
4952   // synthesizes these stubs.
4953   const TargetMachine &TM = DAG.getTarget();
4954   const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
4955   const GlobalValue *GV = nullptr;
4956   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4957     GV = G->getGlobal();
4958   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4959   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4960 
4961   // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4962   // every direct call is) turn it into a TargetGlobalAddress /
4963   // TargetExternalSymbol node so that legalize doesn't hack it.
4964   if (isFunctionGlobalAddress(Callee)) {
4965     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4966 
4967     // A call to a TLS address is actually an indirect call to a
4968     // thread-specific pointer.
4969     unsigned OpFlags = 0;
4970     if (UsePlt)
4971       OpFlags = PPCII::MO_PLT;
4972 
4973     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4974                                         Callee.getValueType(), 0, OpFlags);
4975     needIndirectCall = false;
4976   }
4977 
4978   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4979     unsigned char OpFlags = 0;
4980 
4981     if (UsePlt)
4982       OpFlags = PPCII::MO_PLT;
4983 
4984     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4985                                          OpFlags);
4986     needIndirectCall = false;
4987   }
4988 
4989   if (isPatchPoint) {
4990     // We'll form an invalid direct call when lowering a patchpoint; the full
4991     // sequence for an indirect call is complicated, and many of the
4992     // instructions introduced might have side effects (and, thus, can't be
4993     // removed later). The call itself will be removed as soon as the
4994     // argument/return lowering is complete, so the fact that it has the wrong
4995     // kind of operands should not really matter.
4996     needIndirectCall = false;
4997   }
4998 
4999   if (needIndirectCall) {
5000     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
5001     // to do the call, we can't use PPCISD::CALL.
5002     SDValue MTCTROps[] = {Chain, Callee, InFlag};
5003 
5004     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
5005       // Function pointers in the 64-bit SVR4 ABI do not point to the function
5006       // entry point, but to the function descriptor (the function entry point
5007       // address is part of the function descriptor though).
5008       // The function descriptor is a three doubleword structure with the
5009       // following fields: function entry point, TOC base address and
5010       // environment pointer.
5011       // Thus for a call through a function pointer, the following actions need
5012       // to be performed:
5013       //   1. Save the TOC of the caller in the TOC save area of its stack
5014       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5015       //   2. Load the address of the function entry point from the function
5016       //      descriptor.
5017       //   3. Load the TOC of the callee from the function descriptor into r2.
5018       //   4. Load the environment pointer from the function descriptor into
5019       //      r11.
5020       //   5. Branch to the function entry point address.
5021       //   6. On return of the callee, the TOC of the caller needs to be
5022       //      restored (this is done in FinishCall()).
5023       //
5024       // The loads are scheduled at the beginning of the call sequence, and the
5025       // register copies are flagged together to ensure that no other
5026       // operations can be scheduled in between. E.g. without flagging the
5027       // copies together, a TOC access in the caller could be scheduled between
5028       // the assignment of the callee TOC and the branch to the callee, which
5029       // results in the TOC access going through the TOC of the callee instead
5030       // of going through the TOC of the caller, which leads to incorrect code.
5031 
5032       // Load the address of the function entry point from the function
5033       // descriptor.
5034       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
5035       if (LDChain.getValueType() == MVT::Glue)
5036         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
5037 
5038       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5039                           ? (MachineMemOperand::MODereferenceable |
5040                              MachineMemOperand::MOInvariant)
5041                           : MachineMemOperand::MONone;
5042 
5043       MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5044       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
5045                                         /* Alignment = */ 8, MMOFlags);
5046 
5047       // Load environment pointer into r11.
5048       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
5049       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
5050       SDValue LoadEnvPtr =
5051           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
5052                       /* Alignment = */ 8, MMOFlags);
5053 
5054       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
5055       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
5056       SDValue TOCPtr =
5057           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
5058                       /* Alignment = */ 8, MMOFlags);
5059 
5060       setUsesTOCBasePtr(DAG);
5061       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
5062                                         InFlag);
5063       Chain = TOCVal.getValue(0);
5064       InFlag = TOCVal.getValue(1);
5065 
5066       // If the function call has an explicit 'nest' parameter, it takes the
5067       // place of the environment pointer.
5068       if (!hasNest) {
5069         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
5070                                           InFlag);
5071 
5072         Chain = EnvVal.getValue(0);
5073         InFlag = EnvVal.getValue(1);
5074       }
5075 
5076       MTCTROps[0] = Chain;
5077       MTCTROps[1] = LoadFuncPtr;
5078       MTCTROps[2] = InFlag;
5079     }
5080 
5081     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
5082                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
5083     InFlag = Chain.getValue(1);
5084 
5085     NodeTys.clear();
5086     NodeTys.push_back(MVT::Other);
5087     NodeTys.push_back(MVT::Glue);
5088     Ops.push_back(Chain);
5089     CallOpc = PPCISD::BCTRL;
5090     Callee.setNode(nullptr);
5091     // Add use of X11 (holding environment pointer)
5092     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
5093       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
5094     // Add CTR register as callee so a bctr can be emitted later.
5095     if (isTailCall)
5096       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
5097   }
5098 
5099   // If this is a direct call, pass the chain and the callee.
5100   if (Callee.getNode()) {
5101     Ops.push_back(Chain);
5102     Ops.push_back(Callee);
5103   }
5104   // If this is a tail call add stack pointer delta.
5105   if (isTailCall)
5106     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5107 
5108   // Add argument registers to the end of the list so that they are known live
5109   // into the call.
5110   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5111     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5112                                   RegsToPass[i].second.getValueType()));
5113 
5114   // All calls, in the AIX ABI and 64-bit ELF ABIs, need the TOC register
5115   // live into the call.
5116   // We do need to reserve R2/X2 to appease the verifier for the PATCHPOINT.
5117   if ((isSVR4ABI && isPPC64) || isAIXABI) {
5118     setUsesTOCBasePtr(DAG);
5119 
5120     // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5121     // no way to mark dependencies as implicit here.
5122     // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5123     if (!isPatchPoint)
5124       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::X2
5125                                             : PPC::R2, PtrVT));
5126   }
5127 
5128   return CallOpc;
5129 }
5130 
5131 SDValue PPCTargetLowering::LowerCallResult(
5132     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5133     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5134     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5135   SmallVector<CCValAssign, 16> RVLocs;
5136   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5137                     *DAG.getContext());
5138 
5139   CCRetInfo.AnalyzeCallResult(
5140       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5141                ? RetCC_PPC_Cold
5142                : RetCC_PPC);
5143 
5144   // Copy all of the result registers out of their specified physreg.
5145   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5146     CCValAssign &VA = RVLocs[i];
5147     assert(VA.isRegLoc() && "Can only return in registers!");
5148 
5149     SDValue Val;
5150 
5151     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5152       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5153                                       InFlag);
5154       Chain = Lo.getValue(1);
5155       InFlag = Lo.getValue(2);
5156       VA = RVLocs[++i]; // skip ahead to next loc
5157       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5158                                       InFlag);
5159       Chain = Hi.getValue(1);
5160       InFlag = Hi.getValue(2);
5161       if (!Subtarget.isLittleEndian())
5162         std::swap (Lo, Hi);
5163       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5164     } else {
5165       Val = DAG.getCopyFromReg(Chain, dl,
5166                                VA.getLocReg(), VA.getLocVT(), InFlag);
5167       Chain = Val.getValue(1);
5168       InFlag = Val.getValue(2);
5169     }
5170 
5171     switch (VA.getLocInfo()) {
5172     default: llvm_unreachable("Unknown loc info!");
5173     case CCValAssign::Full: break;
5174     case CCValAssign::AExt:
5175       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5176       break;
5177     case CCValAssign::ZExt:
5178       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5179                         DAG.getValueType(VA.getValVT()));
5180       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5181       break;
5182     case CCValAssign::SExt:
5183       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5184                         DAG.getValueType(VA.getValVT()));
5185       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5186       break;
5187     }
5188 
5189     InVals.push_back(Val);
5190   }
5191 
5192   return Chain;
5193 }
5194 
5195 SDValue PPCTargetLowering::FinishCall(
5196     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5197     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5198     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
5199     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5200     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5201     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5202   std::vector<EVT> NodeTys;
5203   SmallVector<SDValue, 8> Ops;
5204   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
5205                                  SPDiff, isTailCall, isPatchPoint, hasNest,
5206                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
5207 
5208   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5209   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
5210     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5211 
5212   // When performing tail call optimization the callee pops its arguments off
5213   // the stack. Account for this here so these bytes can be pushed back on in
5214   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5215   int BytesCalleePops =
5216     (CallConv == CallingConv::Fast &&
5217      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
5218 
5219   // Add a register mask operand representing the call-preserved registers.
5220   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5221   const uint32_t *Mask =
5222       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5223   assert(Mask && "Missing call preserved mask for calling convention");
5224   Ops.push_back(DAG.getRegisterMask(Mask));
5225 
5226   if (InFlag.getNode())
5227     Ops.push_back(InFlag);
5228 
5229   // Emit tail call.
5230   if (isTailCall) {
5231     assert(((Callee.getOpcode() == ISD::Register &&
5232              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5233             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5234             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5235             isa<ConstantSDNode>(Callee)) &&
5236     "Expecting an global address, external symbol, absolute value or register");
5237 
5238     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5239     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5240   }
5241 
5242   // Add a NOP immediately after the branch instruction when using the 64-bit
5243   // SVR4 or the AIX ABI.
5244   // At link time, if caller and callee are in a different module and
5245   // thus have a different TOC, the call will be replaced with a call to a stub
5246   // function which saves the current TOC, loads the TOC of the callee and
5247   // branches to the callee. The NOP will be replaced with a load instruction
5248   // which restores the TOC of the caller from the TOC save slot of the current
5249   // stack frame. If caller and callee belong to the same module (and have the
5250   // same TOC), the NOP will remain unchanged, or become some other NOP.
5251 
5252   MachineFunction &MF = DAG.getMachineFunction();
5253   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5254   if (!isTailCall && !isPatchPoint &&
5255       ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) ||
5256        Subtarget.isAIXABI())) {
5257     if (CallOpc == PPCISD::BCTRL) {
5258       if (Subtarget.isAIXABI())
5259         report_fatal_error("Indirect call on AIX is not implemented.");
5260 
5261       // This is a call through a function pointer.
5262       // Restore the caller TOC from the save area into R2.
5263       // See PrepareCall() for more information about calls through function
5264       // pointers in the 64-bit SVR4 ABI.
5265       // We are using a target-specific load with r2 hard coded, because the
5266       // result of a target-independent load would never go directly into r2,
5267       // since r2 is a reserved register (which prevents the register allocator
5268       // from allocating it), resulting in an additional register being
5269       // allocated and an unnecessary move instruction being generated.
5270       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5271 
5272       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5273       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5274       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5275       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5276 
5277       // The address needs to go after the chain input but before the flag (or
5278       // any other variadic arguments).
5279       Ops.insert(std::next(Ops.begin()), AddTOC);
5280     } else if (CallOpc == PPCISD::CALL &&
5281       !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5282       // Otherwise insert NOP for non-local calls.
5283       CallOpc = PPCISD::CALL_NOP;
5284     }
5285   }
5286 
5287   if (Subtarget.isAIXABI() && isFunctionGlobalAddress(Callee)) {
5288     // On AIX, direct function calls reference the symbol for the function's
5289     // entry point, which is named by inserting a "." before the function's
5290     // C-linkage name.
5291     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5292     auto &Context = DAG.getMachineFunction().getMMI().getContext();
5293     MCSymbol *S = Context.getOrCreateSymbol(Twine(".") +
5294                                             Twine(G->getGlobal()->getName()));
5295     Callee = DAG.getMCSymbol(S, PtrVT);
5296     // Replace the GlobalAddressSDNode Callee with the MCSymbolSDNode.
5297     Ops[1] = Callee;
5298   }
5299 
5300   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5301   InFlag = Chain.getValue(1);
5302 
5303   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5304                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5305                              InFlag, dl);
5306   if (!Ins.empty())
5307     InFlag = Chain.getValue(1);
5308 
5309   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5310                          Ins, dl, DAG, InVals);
5311 }
5312 
5313 SDValue
5314 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5315                              SmallVectorImpl<SDValue> &InVals) const {
5316   SelectionDAG &DAG                     = CLI.DAG;
5317   SDLoc &dl                             = CLI.DL;
5318   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5319   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5320   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5321   SDValue Chain                         = CLI.Chain;
5322   SDValue Callee                        = CLI.Callee;
5323   bool &isTailCall                      = CLI.IsTailCall;
5324   CallingConv::ID CallConv              = CLI.CallConv;
5325   bool isVarArg                         = CLI.IsVarArg;
5326   bool isPatchPoint                     = CLI.IsPatchPoint;
5327   ImmutableCallSite CS                  = CLI.CS;
5328 
5329   if (isTailCall) {
5330     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5331       isTailCall = false;
5332     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5333       isTailCall =
5334         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5335                                                  isVarArg, Outs, Ins, DAG);
5336     else
5337       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5338                                                      Ins, DAG);
5339     if (isTailCall) {
5340       ++NumTailCalls;
5341       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5342         ++NumSiblingCalls;
5343 
5344       assert(isa<GlobalAddressSDNode>(Callee) &&
5345              "Callee should be an llvm::Function object.");
5346       LLVM_DEBUG(
5347           const GlobalValue *GV =
5348               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5349           const unsigned Width =
5350               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5351           dbgs() << "TCO caller: "
5352                  << left_justify(DAG.getMachineFunction().getName(), Width)
5353                  << ", callee linkage: " << GV->getVisibility() << ", "
5354                  << GV->getLinkage() << "\n");
5355     }
5356   }
5357 
5358   if (!isTailCall && CS && CS.isMustTailCall())
5359     report_fatal_error("failed to perform tail call elimination on a call "
5360                        "site marked musttail");
5361 
5362   // When long calls (i.e. indirect calls) are always used, calls are always
5363   // made via function pointer. If we have a function name, first translate it
5364   // into a pointer.
5365   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5366       !isTailCall)
5367     Callee = LowerGlobalAddress(Callee, DAG);
5368 
5369   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5370     return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5371                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5372                             dl, DAG, InVals, CS);
5373 
5374   if (Subtarget.isSVR4ABI())
5375     return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5376                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5377                             dl, DAG, InVals, CS);
5378 
5379   if (Subtarget.isAIXABI())
5380     return LowerCall_AIX(Chain, Callee, CallConv, isVarArg,
5381                          isTailCall, isPatchPoint, Outs, OutVals, Ins,
5382                          dl, DAG, InVals, CS);
5383 
5384   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5385                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5386                           dl, DAG, InVals, CS);
5387 }
5388 
5389 SDValue PPCTargetLowering::LowerCall_32SVR4(
5390     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5391     bool isTailCall, bool isPatchPoint,
5392     const SmallVectorImpl<ISD::OutputArg> &Outs,
5393     const SmallVectorImpl<SDValue> &OutVals,
5394     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5395     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5396     ImmutableCallSite CS) const {
5397   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5398   // of the 32-bit SVR4 ABI stack frame layout.
5399 
5400   assert((CallConv == CallingConv::C ||
5401           CallConv == CallingConv::Cold ||
5402           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5403 
5404   unsigned PtrByteSize = 4;
5405 
5406   MachineFunction &MF = DAG.getMachineFunction();
5407 
5408   // Mark this function as potentially containing a function that contains a
5409   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5410   // and restoring the callers stack pointer in this functions epilog. This is
5411   // done because by tail calling the called function might overwrite the value
5412   // in this function's (MF) stack pointer stack slot 0(SP).
5413   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5414       CallConv == CallingConv::Fast)
5415     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5416 
5417   // Count how many bytes are to be pushed on the stack, including the linkage
5418   // area, parameter list area and the part of the local variable space which
5419   // contains copies of aggregates which are passed by value.
5420 
5421   // Assign locations to all of the outgoing arguments.
5422   SmallVector<CCValAssign, 16> ArgLocs;
5423   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5424 
5425   // Reserve space for the linkage area on the stack.
5426   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5427                        PtrByteSize);
5428   if (useSoftFloat())
5429     CCInfo.PreAnalyzeCallOperands(Outs);
5430 
5431   if (isVarArg) {
5432     // Handle fixed and variable vector arguments differently.
5433     // Fixed vector arguments go into registers as long as registers are
5434     // available. Variable vector arguments always go into memory.
5435     unsigned NumArgs = Outs.size();
5436 
5437     for (unsigned i = 0; i != NumArgs; ++i) {
5438       MVT ArgVT = Outs[i].VT;
5439       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5440       bool Result;
5441 
5442       if (Outs[i].IsFixed) {
5443         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5444                                CCInfo);
5445       } else {
5446         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5447                                       ArgFlags, CCInfo);
5448       }
5449 
5450       if (Result) {
5451 #ifndef NDEBUG
5452         errs() << "Call operand #" << i << " has unhandled type "
5453              << EVT(ArgVT).getEVTString() << "\n";
5454 #endif
5455         llvm_unreachable(nullptr);
5456       }
5457     }
5458   } else {
5459     // All arguments are treated the same.
5460     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5461   }
5462   CCInfo.clearWasPPCF128();
5463 
5464   // Assign locations to all of the outgoing aggregate by value arguments.
5465   SmallVector<CCValAssign, 16> ByValArgLocs;
5466   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5467 
5468   // Reserve stack space for the allocations in CCInfo.
5469   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5470 
5471   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5472 
5473   // Size of the linkage area, parameter list area and the part of the local
5474   // space variable where copies of aggregates which are passed by value are
5475   // stored.
5476   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5477 
5478   // Calculate by how many bytes the stack has to be adjusted in case of tail
5479   // call optimization.
5480   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5481 
5482   // Adjust the stack pointer for the new arguments...
5483   // These operations are automatically eliminated by the prolog/epilog pass
5484   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5485   SDValue CallSeqStart = Chain;
5486 
5487   // Load the return address and frame pointer so it can be moved somewhere else
5488   // later.
5489   SDValue LROp, FPOp;
5490   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5491 
5492   // Set up a copy of the stack pointer for use loading and storing any
5493   // arguments that may not fit in the registers available for argument
5494   // passing.
5495   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5496 
5497   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5498   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5499   SmallVector<SDValue, 8> MemOpChains;
5500 
5501   bool seenFloatArg = false;
5502   // Walk the register/memloc assignments, inserting copies/loads.
5503   // i - Tracks the index into the list of registers allocated for the call
5504   // RealArgIdx - Tracks the index into the list of actual function arguments
5505   // j - Tracks the index into the list of byval arguments
5506   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5507        i != e;
5508        ++i, ++RealArgIdx) {
5509     CCValAssign &VA = ArgLocs[i];
5510     SDValue Arg = OutVals[RealArgIdx];
5511     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5512 
5513     if (Flags.isByVal()) {
5514       // Argument is an aggregate which is passed by value, thus we need to
5515       // create a copy of it in the local variable space of the current stack
5516       // frame (which is the stack frame of the caller) and pass the address of
5517       // this copy to the callee.
5518       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5519       CCValAssign &ByValVA = ByValArgLocs[j++];
5520       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5521 
5522       // Memory reserved in the local variable space of the callers stack frame.
5523       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5524 
5525       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5526       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5527                            StackPtr, PtrOff);
5528 
5529       // Create a copy of the argument in the local area of the current
5530       // stack frame.
5531       SDValue MemcpyCall =
5532         CreateCopyOfByValArgument(Arg, PtrOff,
5533                                   CallSeqStart.getNode()->getOperand(0),
5534                                   Flags, DAG, dl);
5535 
5536       // This must go outside the CALLSEQ_START..END.
5537       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5538                                                      SDLoc(MemcpyCall));
5539       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5540                              NewCallSeqStart.getNode());
5541       Chain = CallSeqStart = NewCallSeqStart;
5542 
5543       // Pass the address of the aggregate copy on the stack either in a
5544       // physical register or in the parameter list area of the current stack
5545       // frame to the callee.
5546       Arg = PtrOff;
5547     }
5548 
5549     // When useCRBits() is true, there can be i1 arguments.
5550     // It is because getRegisterType(MVT::i1) => MVT::i1,
5551     // and for other integer types getRegisterType() => MVT::i32.
5552     // Extend i1 and ensure callee will get i32.
5553     if (Arg.getValueType() == MVT::i1)
5554       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5555                         dl, MVT::i32, Arg);
5556 
5557     if (VA.isRegLoc()) {
5558       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5559       // Put argument in a physical register.
5560       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5561         bool IsLE = Subtarget.isLittleEndian();
5562         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5563                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5564         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5565         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5566                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5567         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5568                              SVal.getValue(0)));
5569       } else
5570         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5571     } else {
5572       // Put argument in the parameter list area of the current stack frame.
5573       assert(VA.isMemLoc());
5574       unsigned LocMemOffset = VA.getLocMemOffset();
5575 
5576       if (!isTailCall) {
5577         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5578         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5579                              StackPtr, PtrOff);
5580 
5581         MemOpChains.push_back(
5582             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5583       } else {
5584         // Calculate and remember argument location.
5585         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5586                                  TailCallArguments);
5587       }
5588     }
5589   }
5590 
5591   if (!MemOpChains.empty())
5592     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5593 
5594   // Build a sequence of copy-to-reg nodes chained together with token chain
5595   // and flag operands which copy the outgoing args into the appropriate regs.
5596   SDValue InFlag;
5597   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5598     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5599                              RegsToPass[i].second, InFlag);
5600     InFlag = Chain.getValue(1);
5601   }
5602 
5603   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5604   // registers.
5605   if (isVarArg) {
5606     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5607     SDValue Ops[] = { Chain, InFlag };
5608 
5609     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5610                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5611 
5612     InFlag = Chain.getValue(1);
5613   }
5614 
5615   if (isTailCall)
5616     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5617                     TailCallArguments);
5618 
5619   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5620                     /* unused except on PPC64 ELFv1 */ false, DAG,
5621                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5622                     NumBytes, Ins, InVals, CS);
5623 }
5624 
5625 // Copy an argument into memory, being careful to do this outside the
5626 // call sequence for the call to which the argument belongs.
5627 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5628     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5629     SelectionDAG &DAG, const SDLoc &dl) const {
5630   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5631                         CallSeqStart.getNode()->getOperand(0),
5632                         Flags, DAG, dl);
5633   // The MEMCPY must go outside the CALLSEQ_START..END.
5634   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5635   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5636                                                  SDLoc(MemcpyCall));
5637   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5638                          NewCallSeqStart.getNode());
5639   return NewCallSeqStart;
5640 }
5641 
5642 SDValue PPCTargetLowering::LowerCall_64SVR4(
5643     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5644     bool isTailCall, bool isPatchPoint,
5645     const SmallVectorImpl<ISD::OutputArg> &Outs,
5646     const SmallVectorImpl<SDValue> &OutVals,
5647     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5648     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5649     ImmutableCallSite CS) const {
5650   bool isELFv2ABI = Subtarget.isELFv2ABI();
5651   bool isLittleEndian = Subtarget.isLittleEndian();
5652   unsigned NumOps = Outs.size();
5653   bool hasNest = false;
5654   bool IsSibCall = false;
5655 
5656   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5657   unsigned PtrByteSize = 8;
5658 
5659   MachineFunction &MF = DAG.getMachineFunction();
5660 
5661   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5662     IsSibCall = true;
5663 
5664   // Mark this function as potentially containing a function that contains a
5665   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5666   // and restoring the callers stack pointer in this functions epilog. This is
5667   // done because by tail calling the called function might overwrite the value
5668   // in this function's (MF) stack pointer stack slot 0(SP).
5669   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5670       CallConv == CallingConv::Fast)
5671     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5672 
5673   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5674          "fastcc not supported on varargs functions");
5675 
5676   // Count how many bytes are to be pushed on the stack, including the linkage
5677   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5678   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5679   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5680   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5681   unsigned NumBytes = LinkageSize;
5682   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5683   unsigned &QFPR_idx = FPR_idx;
5684 
5685   static const MCPhysReg GPR[] = {
5686     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5687     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5688   };
5689   static const MCPhysReg VR[] = {
5690     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5691     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5692   };
5693 
5694   const unsigned NumGPRs = array_lengthof(GPR);
5695   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5696   const unsigned NumVRs  = array_lengthof(VR);
5697   const unsigned NumQFPRs = NumFPRs;
5698 
5699   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5700   // can be passed to the callee in registers.
5701   // For the fast calling convention, there is another check below.
5702   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5703   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5704   if (!HasParameterArea) {
5705     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5706     unsigned AvailableFPRs = NumFPRs;
5707     unsigned AvailableVRs = NumVRs;
5708     unsigned NumBytesTmp = NumBytes;
5709     for (unsigned i = 0; i != NumOps; ++i) {
5710       if (Outs[i].Flags.isNest()) continue;
5711       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5712                                 PtrByteSize, LinkageSize, ParamAreaSize,
5713                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5714                                 Subtarget.hasQPX()))
5715         HasParameterArea = true;
5716     }
5717   }
5718 
5719   // When using the fast calling convention, we don't provide backing for
5720   // arguments that will be in registers.
5721   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5722 
5723   // Avoid allocating parameter area for fastcc functions if all the arguments
5724   // can be passed in the registers.
5725   if (CallConv == CallingConv::Fast)
5726     HasParameterArea = false;
5727 
5728   // Add up all the space actually used.
5729   for (unsigned i = 0; i != NumOps; ++i) {
5730     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5731     EVT ArgVT = Outs[i].VT;
5732     EVT OrigVT = Outs[i].ArgVT;
5733 
5734     if (Flags.isNest())
5735       continue;
5736 
5737     if (CallConv == CallingConv::Fast) {
5738       if (Flags.isByVal()) {
5739         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5740         if (NumGPRsUsed > NumGPRs)
5741           HasParameterArea = true;
5742       } else {
5743         switch (ArgVT.getSimpleVT().SimpleTy) {
5744         default: llvm_unreachable("Unexpected ValueType for argument!");
5745         case MVT::i1:
5746         case MVT::i32:
5747         case MVT::i64:
5748           if (++NumGPRsUsed <= NumGPRs)
5749             continue;
5750           break;
5751         case MVT::v4i32:
5752         case MVT::v8i16:
5753         case MVT::v16i8:
5754         case MVT::v2f64:
5755         case MVT::v2i64:
5756         case MVT::v1i128:
5757         case MVT::f128:
5758           if (++NumVRsUsed <= NumVRs)
5759             continue;
5760           break;
5761         case MVT::v4f32:
5762           // When using QPX, this is handled like a FP register, otherwise, it
5763           // is an Altivec register.
5764           if (Subtarget.hasQPX()) {
5765             if (++NumFPRsUsed <= NumFPRs)
5766               continue;
5767           } else {
5768             if (++NumVRsUsed <= NumVRs)
5769               continue;
5770           }
5771           break;
5772         case MVT::f32:
5773         case MVT::f64:
5774         case MVT::v4f64: // QPX
5775         case MVT::v4i1:  // QPX
5776           if (++NumFPRsUsed <= NumFPRs)
5777             continue;
5778           break;
5779         }
5780         HasParameterArea = true;
5781       }
5782     }
5783 
5784     /* Respect alignment of argument on the stack.  */
5785     unsigned Align =
5786       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5787     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5788 
5789     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5790     if (Flags.isInConsecutiveRegsLast())
5791       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5792   }
5793 
5794   unsigned NumBytesActuallyUsed = NumBytes;
5795 
5796   // In the old ELFv1 ABI,
5797   // the prolog code of the callee may store up to 8 GPR argument registers to
5798   // the stack, allowing va_start to index over them in memory if its varargs.
5799   // Because we cannot tell if this is needed on the caller side, we have to
5800   // conservatively assume that it is needed.  As such, make sure we have at
5801   // least enough stack space for the caller to store the 8 GPRs.
5802   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5803   // really requires memory operands, e.g. a vararg function.
5804   if (HasParameterArea)
5805     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5806   else
5807     NumBytes = LinkageSize;
5808 
5809   // Tail call needs the stack to be aligned.
5810   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5811       CallConv == CallingConv::Fast)
5812     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5813 
5814   int SPDiff = 0;
5815 
5816   // Calculate by how many bytes the stack has to be adjusted in case of tail
5817   // call optimization.
5818   if (!IsSibCall)
5819     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5820 
5821   // To protect arguments on the stack from being clobbered in a tail call,
5822   // force all the loads to happen before doing any other lowering.
5823   if (isTailCall)
5824     Chain = DAG.getStackArgumentTokenFactor(Chain);
5825 
5826   // Adjust the stack pointer for the new arguments...
5827   // These operations are automatically eliminated by the prolog/epilog pass
5828   if (!IsSibCall)
5829     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5830   SDValue CallSeqStart = Chain;
5831 
5832   // Load the return address and frame pointer so it can be move somewhere else
5833   // later.
5834   SDValue LROp, FPOp;
5835   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5836 
5837   // Set up a copy of the stack pointer for use loading and storing any
5838   // arguments that may not fit in the registers available for argument
5839   // passing.
5840   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5841 
5842   // Figure out which arguments are going to go in registers, and which in
5843   // memory.  Also, if this is a vararg function, floating point operations
5844   // must be stored to our stack, and loaded into integer regs as well, if
5845   // any integer regs are available for argument passing.
5846   unsigned ArgOffset = LinkageSize;
5847 
5848   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5849   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5850 
5851   SmallVector<SDValue, 8> MemOpChains;
5852   for (unsigned i = 0; i != NumOps; ++i) {
5853     SDValue Arg = OutVals[i];
5854     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5855     EVT ArgVT = Outs[i].VT;
5856     EVT OrigVT = Outs[i].ArgVT;
5857 
5858     // PtrOff will be used to store the current argument to the stack if a
5859     // register cannot be found for it.
5860     SDValue PtrOff;
5861 
5862     // We re-align the argument offset for each argument, except when using the
5863     // fast calling convention, when we need to make sure we do that only when
5864     // we'll actually use a stack slot.
5865     auto ComputePtrOff = [&]() {
5866       /* Respect alignment of argument on the stack.  */
5867       unsigned Align =
5868         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5869       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5870 
5871       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5872 
5873       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5874     };
5875 
5876     if (CallConv != CallingConv::Fast) {
5877       ComputePtrOff();
5878 
5879       /* Compute GPR index associated with argument offset.  */
5880       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5881       GPR_idx = std::min(GPR_idx, NumGPRs);
5882     }
5883 
5884     // Promote integers to 64-bit values.
5885     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5886       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5887       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5888       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5889     }
5890 
5891     // FIXME memcpy is used way more than necessary.  Correctness first.
5892     // Note: "by value" is code for passing a structure by value, not
5893     // basic types.
5894     if (Flags.isByVal()) {
5895       // Note: Size includes alignment padding, so
5896       //   struct x { short a; char b; }
5897       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5898       // These are the proper values we need for right-justifying the
5899       // aggregate in a parameter register.
5900       unsigned Size = Flags.getByValSize();
5901 
5902       // An empty aggregate parameter takes up no storage and no
5903       // registers.
5904       if (Size == 0)
5905         continue;
5906 
5907       if (CallConv == CallingConv::Fast)
5908         ComputePtrOff();
5909 
5910       // All aggregates smaller than 8 bytes must be passed right-justified.
5911       if (Size==1 || Size==2 || Size==4) {
5912         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5913         if (GPR_idx != NumGPRs) {
5914           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5915                                         MachinePointerInfo(), VT);
5916           MemOpChains.push_back(Load.getValue(1));
5917           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5918 
5919           ArgOffset += PtrByteSize;
5920           continue;
5921         }
5922       }
5923 
5924       if (GPR_idx == NumGPRs && Size < 8) {
5925         SDValue AddPtr = PtrOff;
5926         if (!isLittleEndian) {
5927           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5928                                           PtrOff.getValueType());
5929           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5930         }
5931         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5932                                                           CallSeqStart,
5933                                                           Flags, DAG, dl);
5934         ArgOffset += PtrByteSize;
5935         continue;
5936       }
5937       // Copy entire object into memory.  There are cases where gcc-generated
5938       // code assumes it is there, even if it could be put entirely into
5939       // registers.  (This is not what the doc says.)
5940 
5941       // FIXME: The above statement is likely due to a misunderstanding of the
5942       // documents.  All arguments must be copied into the parameter area BY
5943       // THE CALLEE in the event that the callee takes the address of any
5944       // formal argument.  That has not yet been implemented.  However, it is
5945       // reasonable to use the stack area as a staging area for the register
5946       // load.
5947 
5948       // Skip this for small aggregates, as we will use the same slot for a
5949       // right-justified copy, below.
5950       if (Size >= 8)
5951         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5952                                                           CallSeqStart,
5953                                                           Flags, DAG, dl);
5954 
5955       // When a register is available, pass a small aggregate right-justified.
5956       if (Size < 8 && GPR_idx != NumGPRs) {
5957         // The easiest way to get this right-justified in a register
5958         // is to copy the structure into the rightmost portion of a
5959         // local variable slot, then load the whole slot into the
5960         // register.
5961         // FIXME: The memcpy seems to produce pretty awful code for
5962         // small aggregates, particularly for packed ones.
5963         // FIXME: It would be preferable to use the slot in the
5964         // parameter save area instead of a new local variable.
5965         SDValue AddPtr = PtrOff;
5966         if (!isLittleEndian) {
5967           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5968           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5969         }
5970         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5971                                                           CallSeqStart,
5972                                                           Flags, DAG, dl);
5973 
5974         // Load the slot into the register.
5975         SDValue Load =
5976             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5977         MemOpChains.push_back(Load.getValue(1));
5978         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5979 
5980         // Done with this argument.
5981         ArgOffset += PtrByteSize;
5982         continue;
5983       }
5984 
5985       // For aggregates larger than PtrByteSize, copy the pieces of the
5986       // object that fit into registers from the parameter save area.
5987       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5988         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5989         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5990         if (GPR_idx != NumGPRs) {
5991           SDValue Load =
5992               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5993           MemOpChains.push_back(Load.getValue(1));
5994           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5995           ArgOffset += PtrByteSize;
5996         } else {
5997           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5998           break;
5999         }
6000       }
6001       continue;
6002     }
6003 
6004     switch (Arg.getSimpleValueType().SimpleTy) {
6005     default: llvm_unreachable("Unexpected ValueType for argument!");
6006     case MVT::i1:
6007     case MVT::i32:
6008     case MVT::i64:
6009       if (Flags.isNest()) {
6010         // The 'nest' parameter, if any, is passed in R11.
6011         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6012         hasNest = true;
6013         break;
6014       }
6015 
6016       // These can be scalar arguments or elements of an integer array type
6017       // passed directly.  Clang may use those instead of "byval" aggregate
6018       // types to avoid forcing arguments to memory unnecessarily.
6019       if (GPR_idx != NumGPRs) {
6020         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6021       } else {
6022         if (CallConv == CallingConv::Fast)
6023           ComputePtrOff();
6024 
6025         assert(HasParameterArea &&
6026                "Parameter area must exist to pass an argument in memory.");
6027         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6028                          true, isTailCall, false, MemOpChains,
6029                          TailCallArguments, dl);
6030         if (CallConv == CallingConv::Fast)
6031           ArgOffset += PtrByteSize;
6032       }
6033       if (CallConv != CallingConv::Fast)
6034         ArgOffset += PtrByteSize;
6035       break;
6036     case MVT::f32:
6037     case MVT::f64: {
6038       // These can be scalar arguments or elements of a float array type
6039       // passed directly.  The latter are used to implement ELFv2 homogenous
6040       // float aggregates.
6041 
6042       // Named arguments go into FPRs first, and once they overflow, the
6043       // remaining arguments go into GPRs and then the parameter save area.
6044       // Unnamed arguments for vararg functions always go to GPRs and
6045       // then the parameter save area.  For now, put all arguments to vararg
6046       // routines always in both locations (FPR *and* GPR or stack slot).
6047       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
6048       bool NeededLoad = false;
6049 
6050       // First load the argument into the next available FPR.
6051       if (FPR_idx != NumFPRs)
6052         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6053 
6054       // Next, load the argument into GPR or stack slot if needed.
6055       if (!NeedGPROrStack)
6056         ;
6057       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
6058         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6059         // once we support fp <-> gpr moves.
6060 
6061         // In the non-vararg case, this can only ever happen in the
6062         // presence of f32 array types, since otherwise we never run
6063         // out of FPRs before running out of GPRs.
6064         SDValue ArgVal;
6065 
6066         // Double values are always passed in a single GPR.
6067         if (Arg.getValueType() != MVT::f32) {
6068           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6069 
6070         // Non-array float values are extended and passed in a GPR.
6071         } else if (!Flags.isInConsecutiveRegs()) {
6072           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6073           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6074 
6075         // If we have an array of floats, we collect every odd element
6076         // together with its predecessor into one GPR.
6077         } else if (ArgOffset % PtrByteSize != 0) {
6078           SDValue Lo, Hi;
6079           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6080           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6081           if (!isLittleEndian)
6082             std::swap(Lo, Hi);
6083           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6084 
6085         // The final element, if even, goes into the first half of a GPR.
6086         } else if (Flags.isInConsecutiveRegsLast()) {
6087           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6088           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6089           if (!isLittleEndian)
6090             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6091                                  DAG.getConstant(32, dl, MVT::i32));
6092 
6093         // Non-final even elements are skipped; they will be handled
6094         // together the with subsequent argument on the next go-around.
6095         } else
6096           ArgVal = SDValue();
6097 
6098         if (ArgVal.getNode())
6099           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6100       } else {
6101         if (CallConv == CallingConv::Fast)
6102           ComputePtrOff();
6103 
6104         // Single-precision floating-point values are mapped to the
6105         // second (rightmost) word of the stack doubleword.
6106         if (Arg.getValueType() == MVT::f32 &&
6107             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6108           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6109           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6110         }
6111 
6112         assert(HasParameterArea &&
6113                "Parameter area must exist to pass an argument in memory.");
6114         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6115                          true, isTailCall, false, MemOpChains,
6116                          TailCallArguments, dl);
6117 
6118         NeededLoad = true;
6119       }
6120       // When passing an array of floats, the array occupies consecutive
6121       // space in the argument area; only round up to the next doubleword
6122       // at the end of the array.  Otherwise, each float takes 8 bytes.
6123       if (CallConv != CallingConv::Fast || NeededLoad) {
6124         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6125                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6126         if (Flags.isInConsecutiveRegsLast())
6127           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6128       }
6129       break;
6130     }
6131     case MVT::v4f32:
6132     case MVT::v4i32:
6133     case MVT::v8i16:
6134     case MVT::v16i8:
6135     case MVT::v2f64:
6136     case MVT::v2i64:
6137     case MVT::v1i128:
6138     case MVT::f128:
6139       if (!Subtarget.hasQPX()) {
6140       // These can be scalar arguments or elements of a vector array type
6141       // passed directly.  The latter are used to implement ELFv2 homogenous
6142       // vector aggregates.
6143 
6144       // For a varargs call, named arguments go into VRs or on the stack as
6145       // usual; unnamed arguments always go to the stack or the corresponding
6146       // GPRs when within range.  For now, we always put the value in both
6147       // locations (or even all three).
6148       if (isVarArg) {
6149         assert(HasParameterArea &&
6150                "Parameter area must exist if we have a varargs call.");
6151         // We could elide this store in the case where the object fits
6152         // entirely in R registers.  Maybe later.
6153         SDValue Store =
6154             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6155         MemOpChains.push_back(Store);
6156         if (VR_idx != NumVRs) {
6157           SDValue Load =
6158               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6159           MemOpChains.push_back(Load.getValue(1));
6160           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6161         }
6162         ArgOffset += 16;
6163         for (unsigned i=0; i<16; i+=PtrByteSize) {
6164           if (GPR_idx == NumGPRs)
6165             break;
6166           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6167                                    DAG.getConstant(i, dl, PtrVT));
6168           SDValue Load =
6169               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6170           MemOpChains.push_back(Load.getValue(1));
6171           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6172         }
6173         break;
6174       }
6175 
6176       // Non-varargs Altivec params go into VRs or on the stack.
6177       if (VR_idx != NumVRs) {
6178         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6179       } else {
6180         if (CallConv == CallingConv::Fast)
6181           ComputePtrOff();
6182 
6183         assert(HasParameterArea &&
6184                "Parameter area must exist to pass an argument in memory.");
6185         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6186                          true, isTailCall, true, MemOpChains,
6187                          TailCallArguments, dl);
6188         if (CallConv == CallingConv::Fast)
6189           ArgOffset += 16;
6190       }
6191 
6192       if (CallConv != CallingConv::Fast)
6193         ArgOffset += 16;
6194       break;
6195       } // not QPX
6196 
6197       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6198              "Invalid QPX parameter type");
6199 
6200       LLVM_FALLTHROUGH;
6201     case MVT::v4f64:
6202     case MVT::v4i1: {
6203       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6204       if (isVarArg) {
6205         assert(HasParameterArea &&
6206                "Parameter area must exist if we have a varargs call.");
6207         // We could elide this store in the case where the object fits
6208         // entirely in R registers.  Maybe later.
6209         SDValue Store =
6210             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6211         MemOpChains.push_back(Store);
6212         if (QFPR_idx != NumQFPRs) {
6213           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6214                                      PtrOff, MachinePointerInfo());
6215           MemOpChains.push_back(Load.getValue(1));
6216           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6217         }
6218         ArgOffset += (IsF32 ? 16 : 32);
6219         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6220           if (GPR_idx == NumGPRs)
6221             break;
6222           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6223                                    DAG.getConstant(i, dl, PtrVT));
6224           SDValue Load =
6225               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6226           MemOpChains.push_back(Load.getValue(1));
6227           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6228         }
6229         break;
6230       }
6231 
6232       // Non-varargs QPX params go into registers or on the stack.
6233       if (QFPR_idx != NumQFPRs) {
6234         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6235       } else {
6236         if (CallConv == CallingConv::Fast)
6237           ComputePtrOff();
6238 
6239         assert(HasParameterArea &&
6240                "Parameter area must exist to pass an argument in memory.");
6241         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6242                          true, isTailCall, true, MemOpChains,
6243                          TailCallArguments, dl);
6244         if (CallConv == CallingConv::Fast)
6245           ArgOffset += (IsF32 ? 16 : 32);
6246       }
6247 
6248       if (CallConv != CallingConv::Fast)
6249         ArgOffset += (IsF32 ? 16 : 32);
6250       break;
6251       }
6252     }
6253   }
6254 
6255   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6256          "mismatch in size of parameter area");
6257   (void)NumBytesActuallyUsed;
6258 
6259   if (!MemOpChains.empty())
6260     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6261 
6262   // Check if this is an indirect call (MTCTR/BCTRL).
6263   // See PrepareCall() for more information about calls through function
6264   // pointers in the 64-bit SVR4 ABI.
6265   if (!isTailCall && !isPatchPoint &&
6266       !isFunctionGlobalAddress(Callee) &&
6267       !isa<ExternalSymbolSDNode>(Callee)) {
6268     // Load r2 into a virtual register and store it to the TOC save area.
6269     setUsesTOCBasePtr(DAG);
6270     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6271     // TOC save area offset.
6272     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6273     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6274     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6275     Chain = DAG.getStore(
6276         Val.getValue(1), dl, Val, AddPtr,
6277         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6278     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6279     // This does not mean the MTCTR instruction must use R12; it's easier
6280     // to model this as an extra parameter, so do that.
6281     if (isELFv2ABI && !isPatchPoint)
6282       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6283   }
6284 
6285   // Build a sequence of copy-to-reg nodes chained together with token chain
6286   // and flag operands which copy the outgoing args into the appropriate regs.
6287   SDValue InFlag;
6288   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6289     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6290                              RegsToPass[i].second, InFlag);
6291     InFlag = Chain.getValue(1);
6292   }
6293 
6294   if (isTailCall && !IsSibCall)
6295     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6296                     TailCallArguments);
6297 
6298   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6299                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6300                     SPDiff, NumBytes, Ins, InVals, CS);
6301 }
6302 
6303 SDValue PPCTargetLowering::LowerCall_Darwin(
6304     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6305     bool isTailCall, bool isPatchPoint,
6306     const SmallVectorImpl<ISD::OutputArg> &Outs,
6307     const SmallVectorImpl<SDValue> &OutVals,
6308     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6309     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6310     ImmutableCallSite CS) const {
6311   unsigned NumOps = Outs.size();
6312 
6313   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6314   bool isPPC64 = PtrVT == MVT::i64;
6315   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6316 
6317   MachineFunction &MF = DAG.getMachineFunction();
6318 
6319   // Mark this function as potentially containing a function that contains a
6320   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6321   // and restoring the callers stack pointer in this functions epilog. This is
6322   // done because by tail calling the called function might overwrite the value
6323   // in this function's (MF) stack pointer stack slot 0(SP).
6324   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6325       CallConv == CallingConv::Fast)
6326     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6327 
6328   // Count how many bytes are to be pushed on the stack, including the linkage
6329   // area, and parameter passing area.  We start with 24/48 bytes, which is
6330   // prereserved space for [SP][CR][LR][3 x unused].
6331   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6332   unsigned NumBytes = LinkageSize;
6333 
6334   // Add up all the space actually used.
6335   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6336   // they all go in registers, but we must reserve stack space for them for
6337   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6338   // assigned stack space in order, with padding so Altivec parameters are
6339   // 16-byte aligned.
6340   unsigned nAltivecParamsAtEnd = 0;
6341   for (unsigned i = 0; i != NumOps; ++i) {
6342     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6343     EVT ArgVT = Outs[i].VT;
6344     // Varargs Altivec parameters are padded to a 16 byte boundary.
6345     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6346         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6347         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6348       if (!isVarArg && !isPPC64) {
6349         // Non-varargs Altivec parameters go after all the non-Altivec
6350         // parameters; handle those later so we know how much padding we need.
6351         nAltivecParamsAtEnd++;
6352         continue;
6353       }
6354       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6355       NumBytes = ((NumBytes+15)/16)*16;
6356     }
6357     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6358   }
6359 
6360   // Allow for Altivec parameters at the end, if needed.
6361   if (nAltivecParamsAtEnd) {
6362     NumBytes = ((NumBytes+15)/16)*16;
6363     NumBytes += 16*nAltivecParamsAtEnd;
6364   }
6365 
6366   // The prolog code of the callee may store up to 8 GPR argument registers to
6367   // the stack, allowing va_start to index over them in memory if its varargs.
6368   // Because we cannot tell if this is needed on the caller side, we have to
6369   // conservatively assume that it is needed.  As such, make sure we have at
6370   // least enough stack space for the caller to store the 8 GPRs.
6371   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6372 
6373   // Tail call needs the stack to be aligned.
6374   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6375       CallConv == CallingConv::Fast)
6376     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6377 
6378   // Calculate by how many bytes the stack has to be adjusted in case of tail
6379   // call optimization.
6380   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6381 
6382   // To protect arguments on the stack from being clobbered in a tail call,
6383   // force all the loads to happen before doing any other lowering.
6384   if (isTailCall)
6385     Chain = DAG.getStackArgumentTokenFactor(Chain);
6386 
6387   // Adjust the stack pointer for the new arguments...
6388   // These operations are automatically eliminated by the prolog/epilog pass
6389   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6390   SDValue CallSeqStart = Chain;
6391 
6392   // Load the return address and frame pointer so it can be move somewhere else
6393   // later.
6394   SDValue LROp, FPOp;
6395   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6396 
6397   // Set up a copy of the stack pointer for use loading and storing any
6398   // arguments that may not fit in the registers available for argument
6399   // passing.
6400   SDValue StackPtr;
6401   if (isPPC64)
6402     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6403   else
6404     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6405 
6406   // Figure out which arguments are going to go in registers, and which in
6407   // memory.  Also, if this is a vararg function, floating point operations
6408   // must be stored to our stack, and loaded into integer regs as well, if
6409   // any integer regs are available for argument passing.
6410   unsigned ArgOffset = LinkageSize;
6411   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6412 
6413   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6414     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6415     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6416   };
6417   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6418     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6419     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6420   };
6421   static const MCPhysReg VR[] = {
6422     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6423     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6424   };
6425   const unsigned NumGPRs = array_lengthof(GPR_32);
6426   const unsigned NumFPRs = 13;
6427   const unsigned NumVRs  = array_lengthof(VR);
6428 
6429   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6430 
6431   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6432   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6433 
6434   SmallVector<SDValue, 8> MemOpChains;
6435   for (unsigned i = 0; i != NumOps; ++i) {
6436     SDValue Arg = OutVals[i];
6437     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6438 
6439     // PtrOff will be used to store the current argument to the stack if a
6440     // register cannot be found for it.
6441     SDValue PtrOff;
6442 
6443     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6444 
6445     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6446 
6447     // On PPC64, promote integers to 64-bit values.
6448     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6449       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6450       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6451       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6452     }
6453 
6454     // FIXME memcpy is used way more than necessary.  Correctness first.
6455     // Note: "by value" is code for passing a structure by value, not
6456     // basic types.
6457     if (Flags.isByVal()) {
6458       unsigned Size = Flags.getByValSize();
6459       // Very small objects are passed right-justified.  Everything else is
6460       // passed left-justified.
6461       if (Size==1 || Size==2) {
6462         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6463         if (GPR_idx != NumGPRs) {
6464           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6465                                         MachinePointerInfo(), VT);
6466           MemOpChains.push_back(Load.getValue(1));
6467           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6468 
6469           ArgOffset += PtrByteSize;
6470         } else {
6471           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6472                                           PtrOff.getValueType());
6473           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6474           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6475                                                             CallSeqStart,
6476                                                             Flags, DAG, dl);
6477           ArgOffset += PtrByteSize;
6478         }
6479         continue;
6480       }
6481       // Copy entire object into memory.  There are cases where gcc-generated
6482       // code assumes it is there, even if it could be put entirely into
6483       // registers.  (This is not what the doc says.)
6484       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6485                                                         CallSeqStart,
6486                                                         Flags, DAG, dl);
6487 
6488       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6489       // copy the pieces of the object that fit into registers from the
6490       // parameter save area.
6491       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6492         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6493         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6494         if (GPR_idx != NumGPRs) {
6495           SDValue Load =
6496               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6497           MemOpChains.push_back(Load.getValue(1));
6498           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6499           ArgOffset += PtrByteSize;
6500         } else {
6501           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6502           break;
6503         }
6504       }
6505       continue;
6506     }
6507 
6508     switch (Arg.getSimpleValueType().SimpleTy) {
6509     default: llvm_unreachable("Unexpected ValueType for argument!");
6510     case MVT::i1:
6511     case MVT::i32:
6512     case MVT::i64:
6513       if (GPR_idx != NumGPRs) {
6514         if (Arg.getValueType() == MVT::i1)
6515           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6516 
6517         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6518       } else {
6519         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6520                          isPPC64, isTailCall, false, MemOpChains,
6521                          TailCallArguments, dl);
6522       }
6523       ArgOffset += PtrByteSize;
6524       break;
6525     case MVT::f32:
6526     case MVT::f64:
6527       if (FPR_idx != NumFPRs) {
6528         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6529 
6530         if (isVarArg) {
6531           SDValue Store =
6532               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6533           MemOpChains.push_back(Store);
6534 
6535           // Float varargs are always shadowed in available integer registers
6536           if (GPR_idx != NumGPRs) {
6537             SDValue Load =
6538                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6539             MemOpChains.push_back(Load.getValue(1));
6540             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6541           }
6542           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6543             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6544             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6545             SDValue Load =
6546                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6547             MemOpChains.push_back(Load.getValue(1));
6548             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6549           }
6550         } else {
6551           // If we have any FPRs remaining, we may also have GPRs remaining.
6552           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6553           // GPRs.
6554           if (GPR_idx != NumGPRs)
6555             ++GPR_idx;
6556           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6557               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6558             ++GPR_idx;
6559         }
6560       } else
6561         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6562                          isPPC64, isTailCall, false, MemOpChains,
6563                          TailCallArguments, dl);
6564       if (isPPC64)
6565         ArgOffset += 8;
6566       else
6567         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6568       break;
6569     case MVT::v4f32:
6570     case MVT::v4i32:
6571     case MVT::v8i16:
6572     case MVT::v16i8:
6573       if (isVarArg) {
6574         // These go aligned on the stack, or in the corresponding R registers
6575         // when within range.  The Darwin PPC ABI doc claims they also go in
6576         // V registers; in fact gcc does this only for arguments that are
6577         // prototyped, not for those that match the ...  We do it for all
6578         // arguments, seems to work.
6579         while (ArgOffset % 16 !=0) {
6580           ArgOffset += PtrByteSize;
6581           if (GPR_idx != NumGPRs)
6582             GPR_idx++;
6583         }
6584         // We could elide this store in the case where the object fits
6585         // entirely in R registers.  Maybe later.
6586         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6587                              DAG.getConstant(ArgOffset, dl, PtrVT));
6588         SDValue Store =
6589             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6590         MemOpChains.push_back(Store);
6591         if (VR_idx != NumVRs) {
6592           SDValue Load =
6593               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6594           MemOpChains.push_back(Load.getValue(1));
6595           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6596         }
6597         ArgOffset += 16;
6598         for (unsigned i=0; i<16; i+=PtrByteSize) {
6599           if (GPR_idx == NumGPRs)
6600             break;
6601           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6602                                    DAG.getConstant(i, dl, PtrVT));
6603           SDValue Load =
6604               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6605           MemOpChains.push_back(Load.getValue(1));
6606           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6607         }
6608         break;
6609       }
6610 
6611       // Non-varargs Altivec params generally go in registers, but have
6612       // stack space allocated at the end.
6613       if (VR_idx != NumVRs) {
6614         // Doesn't have GPR space allocated.
6615         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6616       } else if (nAltivecParamsAtEnd==0) {
6617         // We are emitting Altivec params in order.
6618         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6619                          isPPC64, isTailCall, true, MemOpChains,
6620                          TailCallArguments, dl);
6621         ArgOffset += 16;
6622       }
6623       break;
6624     }
6625   }
6626   // If all Altivec parameters fit in registers, as they usually do,
6627   // they get stack space following the non-Altivec parameters.  We
6628   // don't track this here because nobody below needs it.
6629   // If there are more Altivec parameters than fit in registers emit
6630   // the stores here.
6631   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6632     unsigned j = 0;
6633     // Offset is aligned; skip 1st 12 params which go in V registers.
6634     ArgOffset = ((ArgOffset+15)/16)*16;
6635     ArgOffset += 12*16;
6636     for (unsigned i = 0; i != NumOps; ++i) {
6637       SDValue Arg = OutVals[i];
6638       EVT ArgType = Outs[i].VT;
6639       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6640           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6641         if (++j > NumVRs) {
6642           SDValue PtrOff;
6643           // We are emitting Altivec params in order.
6644           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6645                            isPPC64, isTailCall, true, MemOpChains,
6646                            TailCallArguments, dl);
6647           ArgOffset += 16;
6648         }
6649       }
6650     }
6651   }
6652 
6653   if (!MemOpChains.empty())
6654     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6655 
6656   // On Darwin, R12 must contain the address of an indirect callee.  This does
6657   // not mean the MTCTR instruction must use R12; it's easier to model this as
6658   // an extra parameter, so do that.
6659   if (!isTailCall &&
6660       !isFunctionGlobalAddress(Callee) &&
6661       !isa<ExternalSymbolSDNode>(Callee) &&
6662       !isBLACompatibleAddress(Callee, DAG))
6663     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6664                                                    PPC::R12), Callee));
6665 
6666   // Build a sequence of copy-to-reg nodes chained together with token chain
6667   // and flag operands which copy the outgoing args into the appropriate regs.
6668   SDValue InFlag;
6669   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6670     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6671                              RegsToPass[i].second, InFlag);
6672     InFlag = Chain.getValue(1);
6673   }
6674 
6675   if (isTailCall)
6676     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6677                     TailCallArguments);
6678 
6679   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6680                     /* unused except on PPC64 ELFv1 */ false, DAG,
6681                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6682                     NumBytes, Ins, InVals, CS);
6683 }
6684 
6685 
6686 SDValue PPCTargetLowering::LowerCall_AIX(
6687     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6688     bool isTailCall, bool isPatchPoint,
6689     const SmallVectorImpl<ISD::OutputArg> &Outs,
6690     const SmallVectorImpl<SDValue> &OutVals,
6691     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6692     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6693     ImmutableCallSite CS) const {
6694 
6695   assert((CallConv == CallingConv::C || CallConv == CallingConv::Fast) &&
6696          "Unimplemented calling convention!");
6697   if (isVarArg || isPatchPoint)
6698     report_fatal_error("This call type is unimplemented on AIX.");
6699 
6700   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6701   bool isPPC64 = PtrVT == MVT::i64;
6702   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6703   unsigned NumOps = Outs.size();
6704 
6705 
6706   // Count how many bytes are to be pushed on the stack, including the linkage
6707   // area, parameter list area.
6708   // On XCOFF, we start with 24/48, which is reserved space for
6709   // [SP][CR][LR][2 x reserved][TOC].
6710   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6711 
6712   // The prolog code of the callee may store up to 8 GPR argument registers to
6713   // the stack, allowing va_start to index over them in memory if the callee
6714   // is variadic.
6715   // Because we cannot tell if this is needed on the caller side, we have to
6716   // conservatively assume that it is needed.  As such, make sure we have at
6717   // least enough stack space for the caller to store the 8 GPRs.
6718   unsigned NumBytes = LinkageSize + 8 * PtrByteSize;
6719 
6720   // Adjust the stack pointer for the new arguments...
6721   // These operations are automatically eliminated by the prolog/epilog
6722   // inserter pass.
6723   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6724   SDValue CallSeqStart = Chain;
6725 
6726   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6727     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6728     PPC::R7, PPC::R8, PPC::R9, PPC::R10
6729   };
6730   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6731     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6732     PPC::X7, PPC::X8, PPC::X9, PPC::X10
6733   };
6734 
6735   const unsigned NumGPRs = isPPC64 ? array_lengthof(GPR_64)
6736                                    : array_lengthof(GPR_32);
6737   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6738   unsigned GPR_idx = 0;
6739 
6740   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6741 
6742   if (isTailCall)
6743     report_fatal_error("Handling of tail call is unimplemented!");
6744   int SPDiff = 0;
6745 
6746   for (unsigned i = 0; i != NumOps; ++i) {
6747     SDValue Arg = OutVals[i];
6748     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6749 
6750     // Promote integers if needed.
6751     if (Arg.getValueType() == MVT::i1 ||
6752         (isPPC64 && Arg.getValueType() == MVT::i32)) {
6753       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6754       Arg = DAG.getNode(ExtOp, dl, PtrVT, Arg);
6755     }
6756 
6757     // Note: "by value" is code for passing a structure by value, not
6758     // basic types.
6759     if (Flags.isByVal())
6760       report_fatal_error("Passing structure by value is unimplemented!");
6761 
6762     switch (Arg.getSimpleValueType().SimpleTy) {
6763     default: llvm_unreachable("Unexpected ValueType for argument!");
6764     case MVT::i1:
6765     case MVT::i32:
6766     case MVT::i64:
6767       if (GPR_idx != NumGPRs)
6768         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6769       else
6770         report_fatal_error("Handling of placing parameters on the stack is "
6771                            "unimplemented!");
6772       break;
6773     case MVT::f32:
6774     case MVT::f64:
6775     case MVT::v4f32:
6776     case MVT::v4i32:
6777     case MVT::v8i16:
6778     case MVT::v16i8:
6779     case MVT::v2f64:
6780     case MVT::v2i64:
6781     case MVT::v1i128:
6782     case MVT::f128:
6783     case MVT::v4f64:
6784     case MVT::v4i1:
6785       report_fatal_error("Handling of this parameter type is unimplemented!");
6786     }
6787   }
6788 
6789   if (!isFunctionGlobalAddress(Callee) &&
6790       !isa<ExternalSymbolSDNode>(Callee))
6791     report_fatal_error("Handling of indirect call is unimplemented!");
6792 
6793   // Build a sequence of copy-to-reg nodes chained together with token chain
6794   // and flag operands which copy the outgoing args into the appropriate regs.
6795   SDValue InFlag;
6796   for (auto Reg : RegsToPass) {
6797     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
6798     InFlag = Chain.getValue(1);
6799   }
6800 
6801   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6802                     /* unused except on PPC64 ELFv1 */ false, DAG,
6803                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6804                     NumBytes, Ins, InVals, CS);
6805 }
6806 
6807 bool
6808 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6809                                   MachineFunction &MF, bool isVarArg,
6810                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6811                                   LLVMContext &Context) const {
6812   SmallVector<CCValAssign, 16> RVLocs;
6813   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6814   return CCInfo.CheckReturn(
6815       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6816                 ? RetCC_PPC_Cold
6817                 : RetCC_PPC);
6818 }
6819 
6820 SDValue
6821 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6822                                bool isVarArg,
6823                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6824                                const SmallVectorImpl<SDValue> &OutVals,
6825                                const SDLoc &dl, SelectionDAG &DAG) const {
6826   SmallVector<CCValAssign, 16> RVLocs;
6827   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6828                  *DAG.getContext());
6829   CCInfo.AnalyzeReturn(Outs,
6830                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6831                            ? RetCC_PPC_Cold
6832                            : RetCC_PPC);
6833 
6834   SDValue Flag;
6835   SmallVector<SDValue, 4> RetOps(1, Chain);
6836 
6837   // Copy the result values into the output registers.
6838   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
6839     CCValAssign &VA = RVLocs[i];
6840     assert(VA.isRegLoc() && "Can only return in registers!");
6841 
6842     SDValue Arg = OutVals[RealResIdx];
6843 
6844     switch (VA.getLocInfo()) {
6845     default: llvm_unreachable("Unknown loc info!");
6846     case CCValAssign::Full: break;
6847     case CCValAssign::AExt:
6848       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6849       break;
6850     case CCValAssign::ZExt:
6851       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6852       break;
6853     case CCValAssign::SExt:
6854       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6855       break;
6856     }
6857     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
6858       bool isLittleEndian = Subtarget.isLittleEndian();
6859       // Legalize ret f64 -> ret 2 x i32.
6860       SDValue SVal =
6861           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6862                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
6863       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
6864       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6865       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6866                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
6867       Flag = Chain.getValue(1);
6868       VA = RVLocs[++i]; // skip ahead to next loc
6869       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
6870     } else
6871       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6872     Flag = Chain.getValue(1);
6873     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6874   }
6875 
6876   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6877   const MCPhysReg *I =
6878     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6879   if (I) {
6880     for (; *I; ++I) {
6881 
6882       if (PPC::G8RCRegClass.contains(*I))
6883         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6884       else if (PPC::F8RCRegClass.contains(*I))
6885         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6886       else if (PPC::CRRCRegClass.contains(*I))
6887         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6888       else if (PPC::VRRCRegClass.contains(*I))
6889         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6890       else
6891         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6892     }
6893   }
6894 
6895   RetOps[0] = Chain;  // Update chain.
6896 
6897   // Add the flag if we have it.
6898   if (Flag.getNode())
6899     RetOps.push_back(Flag);
6900 
6901   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6902 }
6903 
6904 SDValue
6905 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6906                                                 SelectionDAG &DAG) const {
6907   SDLoc dl(Op);
6908 
6909   // Get the correct type for integers.
6910   EVT IntVT = Op.getValueType();
6911 
6912   // Get the inputs.
6913   SDValue Chain = Op.getOperand(0);
6914   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6915   // Build a DYNAREAOFFSET node.
6916   SDValue Ops[2] = {Chain, FPSIdx};
6917   SDVTList VTs = DAG.getVTList(IntVT);
6918   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6919 }
6920 
6921 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6922                                              SelectionDAG &DAG) const {
6923   // When we pop the dynamic allocation we need to restore the SP link.
6924   SDLoc dl(Op);
6925 
6926   // Get the correct type for pointers.
6927   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6928 
6929   // Construct the stack pointer operand.
6930   bool isPPC64 = Subtarget.isPPC64();
6931   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6932   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6933 
6934   // Get the operands for the STACKRESTORE.
6935   SDValue Chain = Op.getOperand(0);
6936   SDValue SaveSP = Op.getOperand(1);
6937 
6938   // Load the old link SP.
6939   SDValue LoadLinkSP =
6940       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6941 
6942   // Restore the stack pointer.
6943   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6944 
6945   // Store the old link SP.
6946   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6947 }
6948 
6949 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6950   MachineFunction &MF = DAG.getMachineFunction();
6951   bool isPPC64 = Subtarget.isPPC64();
6952   EVT PtrVT = getPointerTy(MF.getDataLayout());
6953 
6954   // Get current frame pointer save index.  The users of this index will be
6955   // primarily DYNALLOC instructions.
6956   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6957   int RASI = FI->getReturnAddrSaveIndex();
6958 
6959   // If the frame pointer save index hasn't been defined yet.
6960   if (!RASI) {
6961     // Find out what the fix offset of the frame pointer save area.
6962     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6963     // Allocate the frame index for frame pointer save area.
6964     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6965     // Save the result.
6966     FI->setReturnAddrSaveIndex(RASI);
6967   }
6968   return DAG.getFrameIndex(RASI, PtrVT);
6969 }
6970 
6971 SDValue
6972 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6973   MachineFunction &MF = DAG.getMachineFunction();
6974   bool isPPC64 = Subtarget.isPPC64();
6975   EVT PtrVT = getPointerTy(MF.getDataLayout());
6976 
6977   // Get current frame pointer save index.  The users of this index will be
6978   // primarily DYNALLOC instructions.
6979   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6980   int FPSI = FI->getFramePointerSaveIndex();
6981 
6982   // If the frame pointer save index hasn't been defined yet.
6983   if (!FPSI) {
6984     // Find out what the fix offset of the frame pointer save area.
6985     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6986     // Allocate the frame index for frame pointer save area.
6987     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6988     // Save the result.
6989     FI->setFramePointerSaveIndex(FPSI);
6990   }
6991   return DAG.getFrameIndex(FPSI, PtrVT);
6992 }
6993 
6994 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6995                                                    SelectionDAG &DAG) const {
6996   // Get the inputs.
6997   SDValue Chain = Op.getOperand(0);
6998   SDValue Size  = Op.getOperand(1);
6999   SDLoc dl(Op);
7000 
7001   // Get the correct type for pointers.
7002   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7003   // Negate the size.
7004   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7005                                 DAG.getConstant(0, dl, PtrVT), Size);
7006   // Construct a node for the frame pointer save index.
7007   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7008   // Build a DYNALLOC node.
7009   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7010   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7011   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7012 }
7013 
7014 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7015                                                      SelectionDAG &DAG) const {
7016   MachineFunction &MF = DAG.getMachineFunction();
7017 
7018   bool isPPC64 = Subtarget.isPPC64();
7019   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7020 
7021   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7022   return DAG.getFrameIndex(FI, PtrVT);
7023 }
7024 
7025 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7026                                                SelectionDAG &DAG) const {
7027   SDLoc DL(Op);
7028   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7029                      DAG.getVTList(MVT::i32, MVT::Other),
7030                      Op.getOperand(0), Op.getOperand(1));
7031 }
7032 
7033 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7034                                                 SelectionDAG &DAG) const {
7035   SDLoc DL(Op);
7036   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7037                      Op.getOperand(0), Op.getOperand(1));
7038 }
7039 
7040 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7041   if (Op.getValueType().isVector())
7042     return LowerVectorLoad(Op, DAG);
7043 
7044   assert(Op.getValueType() == MVT::i1 &&
7045          "Custom lowering only for i1 loads");
7046 
7047   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7048 
7049   SDLoc dl(Op);
7050   LoadSDNode *LD = cast<LoadSDNode>(Op);
7051 
7052   SDValue Chain = LD->getChain();
7053   SDValue BasePtr = LD->getBasePtr();
7054   MachineMemOperand *MMO = LD->getMemOperand();
7055 
7056   SDValue NewLD =
7057       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7058                      BasePtr, MVT::i8, MMO);
7059   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7060 
7061   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7062   return DAG.getMergeValues(Ops, dl);
7063 }
7064 
7065 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7066   if (Op.getOperand(1).getValueType().isVector())
7067     return LowerVectorStore(Op, DAG);
7068 
7069   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7070          "Custom lowering only for i1 stores");
7071 
7072   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7073 
7074   SDLoc dl(Op);
7075   StoreSDNode *ST = cast<StoreSDNode>(Op);
7076 
7077   SDValue Chain = ST->getChain();
7078   SDValue BasePtr = ST->getBasePtr();
7079   SDValue Value = ST->getValue();
7080   MachineMemOperand *MMO = ST->getMemOperand();
7081 
7082   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7083                       Value);
7084   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7085 }
7086 
7087 // FIXME: Remove this once the ANDI glue bug is fixed:
7088 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7089   assert(Op.getValueType() == MVT::i1 &&
7090          "Custom lowering only for i1 results");
7091 
7092   SDLoc DL(Op);
7093   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
7094                      Op.getOperand(0));
7095 }
7096 
7097 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7098                                                SelectionDAG &DAG) const {
7099 
7100   // Implements a vector truncate that fits in a vector register as a shuffle.
7101   // We want to legalize vector truncates down to where the source fits in
7102   // a vector register (and target is therefore smaller than vector register
7103   // size).  At that point legalization will try to custom lower the sub-legal
7104   // result and get here - where we can contain the truncate as a single target
7105   // operation.
7106 
7107   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7108   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7109   //
7110   // We will implement it for big-endian ordering as this (where x denotes
7111   // undefined):
7112   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7113   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7114   //
7115   // The same operation in little-endian ordering will be:
7116   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7117   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7118 
7119   assert(Op.getValueType().isVector() && "Vector type expected.");
7120 
7121   SDLoc DL(Op);
7122   SDValue N1 = Op.getOperand(0);
7123   unsigned SrcSize = N1.getValueType().getSizeInBits();
7124   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7125   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7126 
7127   EVT TrgVT = Op.getValueType();
7128   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7129   EVT EltVT = TrgVT.getVectorElementType();
7130   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7131   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7132 
7133   // First list the elements we want to keep.
7134   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7135   SmallVector<int, 16> ShuffV;
7136   if (Subtarget.isLittleEndian())
7137     for (unsigned i = 0; i < TrgNumElts; ++i)
7138       ShuffV.push_back(i * SizeMult);
7139   else
7140     for (unsigned i = 1; i <= TrgNumElts; ++i)
7141       ShuffV.push_back(i * SizeMult - 1);
7142 
7143   // Populate the remaining elements with undefs.
7144   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7145     // ShuffV.push_back(i + WideNumElts);
7146     ShuffV.push_back(WideNumElts + 1);
7147 
7148   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7149   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7150 }
7151 
7152 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7153 /// possible.
7154 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7155   // Not FP? Not a fsel.
7156   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7157       !Op.getOperand(2).getValueType().isFloatingPoint())
7158     return Op;
7159 
7160   // We might be able to do better than this under some circumstances, but in
7161   // general, fsel-based lowering of select is a finite-math-only optimization.
7162   // For more information, see section F.3 of the 2.06 ISA specification.
7163   if (!DAG.getTarget().Options.NoInfsFPMath ||
7164       !DAG.getTarget().Options.NoNaNsFPMath)
7165     return Op;
7166   // TODO: Propagate flags from the select rather than global settings.
7167   SDNodeFlags Flags;
7168   Flags.setNoInfs(true);
7169   Flags.setNoNaNs(true);
7170 
7171   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7172 
7173   EVT ResVT = Op.getValueType();
7174   EVT CmpVT = Op.getOperand(0).getValueType();
7175   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7176   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7177   SDLoc dl(Op);
7178 
7179   // If the RHS of the comparison is a 0.0, we don't need to do the
7180   // subtraction at all.
7181   SDValue Sel1;
7182   if (isFloatingPointZero(RHS))
7183     switch (CC) {
7184     default: break;       // SETUO etc aren't handled by fsel.
7185     case ISD::SETNE:
7186       std::swap(TV, FV);
7187       LLVM_FALLTHROUGH;
7188     case ISD::SETEQ:
7189       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7190         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7191       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7192       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7193         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7194       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7195                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7196     case ISD::SETULT:
7197     case ISD::SETLT:
7198       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7199       LLVM_FALLTHROUGH;
7200     case ISD::SETOGE:
7201     case ISD::SETGE:
7202       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7203         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7204       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7205     case ISD::SETUGT:
7206     case ISD::SETGT:
7207       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7208       LLVM_FALLTHROUGH;
7209     case ISD::SETOLE:
7210     case ISD::SETLE:
7211       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7212         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7213       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7214                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7215     }
7216 
7217   SDValue Cmp;
7218   switch (CC) {
7219   default: break;       // SETUO etc aren't handled by fsel.
7220   case ISD::SETNE:
7221     std::swap(TV, FV);
7222     LLVM_FALLTHROUGH;
7223   case ISD::SETEQ:
7224     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7225     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7226       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7227     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7228     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7229       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7230     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7231                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7232   case ISD::SETULT:
7233   case ISD::SETLT:
7234     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7235     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7236       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7237     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7238   case ISD::SETOGE:
7239   case ISD::SETGE:
7240     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7241     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7242       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7243     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7244   case ISD::SETUGT:
7245   case ISD::SETGT:
7246     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7247     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7248       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7249     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7250   case ISD::SETOLE:
7251   case ISD::SETLE:
7252     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7253     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7254       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7255     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7256   }
7257   return Op;
7258 }
7259 
7260 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7261                                                SelectionDAG &DAG,
7262                                                const SDLoc &dl) const {
7263   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7264   SDValue Src = Op.getOperand(0);
7265   if (Src.getValueType() == MVT::f32)
7266     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7267 
7268   SDValue Tmp;
7269   switch (Op.getSimpleValueType().SimpleTy) {
7270   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7271   case MVT::i32:
7272     Tmp = DAG.getNode(
7273         Op.getOpcode() == ISD::FP_TO_SINT
7274             ? PPCISD::FCTIWZ
7275             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7276         dl, MVT::f64, Src);
7277     break;
7278   case MVT::i64:
7279     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7280            "i64 FP_TO_UINT is supported only with FPCVT");
7281     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7282                                                         PPCISD::FCTIDUZ,
7283                       dl, MVT::f64, Src);
7284     break;
7285   }
7286 
7287   // Convert the FP value to an int value through memory.
7288   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7289     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7290   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7291   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7292   MachinePointerInfo MPI =
7293       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7294 
7295   // Emit a store to the stack slot.
7296   SDValue Chain;
7297   if (i32Stack) {
7298     MachineFunction &MF = DAG.getMachineFunction();
7299     MachineMemOperand *MMO =
7300       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7301     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7302     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7303               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7304   } else
7305     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7306 
7307   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7308   // add in a bias on big endian.
7309   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7310     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7311                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7312     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7313   }
7314 
7315   RLI.Chain = Chain;
7316   RLI.Ptr = FIPtr;
7317   RLI.MPI = MPI;
7318 }
7319 
7320 /// Custom lowers floating point to integer conversions to use
7321 /// the direct move instructions available in ISA 2.07 to avoid the
7322 /// need for load/store combinations.
7323 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7324                                                     SelectionDAG &DAG,
7325                                                     const SDLoc &dl) const {
7326   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7327   SDValue Src = Op.getOperand(0);
7328 
7329   if (Src.getValueType() == MVT::f32)
7330     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7331 
7332   SDValue Tmp;
7333   switch (Op.getSimpleValueType().SimpleTy) {
7334   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7335   case MVT::i32:
7336     Tmp = DAG.getNode(
7337         Op.getOpcode() == ISD::FP_TO_SINT
7338             ? PPCISD::FCTIWZ
7339             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7340         dl, MVT::f64, Src);
7341     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7342     break;
7343   case MVT::i64:
7344     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7345            "i64 FP_TO_UINT is supported only with FPCVT");
7346     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7347                                                         PPCISD::FCTIDUZ,
7348                       dl, MVT::f64, Src);
7349     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7350     break;
7351   }
7352   return Tmp;
7353 }
7354 
7355 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7356                                           const SDLoc &dl) const {
7357 
7358   // FP to INT conversions are legal for f128.
7359   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7360     return Op;
7361 
7362   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7363   // PPC (the libcall is not available).
7364   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7365     if (Op.getValueType() == MVT::i32) {
7366       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7367         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7368                                  MVT::f64, Op.getOperand(0),
7369                                  DAG.getIntPtrConstant(0, dl));
7370         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7371                                  MVT::f64, Op.getOperand(0),
7372                                  DAG.getIntPtrConstant(1, dl));
7373 
7374         // Add the two halves of the long double in round-to-zero mode.
7375         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7376 
7377         // Now use a smaller FP_TO_SINT.
7378         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7379       }
7380       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7381         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7382         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7383         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7384         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7385         // FIXME: generated code sucks.
7386         // TODO: Are there fast-math-flags to propagate to this FSUB?
7387         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7388                                    Op.getOperand(0), Tmp);
7389         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7390         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7391                            DAG.getConstant(0x80000000, dl, MVT::i32));
7392         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7393                                     Op.getOperand(0));
7394         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7395                                ISD::SETGE);
7396       }
7397     }
7398 
7399     return SDValue();
7400   }
7401 
7402   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7403     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7404 
7405   ReuseLoadInfo RLI;
7406   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7407 
7408   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7409                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7410 }
7411 
7412 // We're trying to insert a regular store, S, and then a load, L. If the
7413 // incoming value, O, is a load, we might just be able to have our load use the
7414 // address used by O. However, we don't know if anything else will store to
7415 // that address before we can load from it. To prevent this situation, we need
7416 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7417 // the same chain operand as O, we create a token factor from the chain results
7418 // of O and L, and we replace all uses of O's chain result with that token
7419 // factor (see spliceIntoChain below for this last part).
7420 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7421                                             ReuseLoadInfo &RLI,
7422                                             SelectionDAG &DAG,
7423                                             ISD::LoadExtType ET) const {
7424   SDLoc dl(Op);
7425   if (ET == ISD::NON_EXTLOAD &&
7426       (Op.getOpcode() == ISD::FP_TO_UINT ||
7427        Op.getOpcode() == ISD::FP_TO_SINT) &&
7428       isOperationLegalOrCustom(Op.getOpcode(),
7429                                Op.getOperand(0).getValueType())) {
7430 
7431     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7432     return true;
7433   }
7434 
7435   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7436   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7437       LD->isNonTemporal())
7438     return false;
7439   if (LD->getMemoryVT() != MemVT)
7440     return false;
7441 
7442   RLI.Ptr = LD->getBasePtr();
7443   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7444     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7445            "Non-pre-inc AM on PPC?");
7446     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7447                           LD->getOffset());
7448   }
7449 
7450   RLI.Chain = LD->getChain();
7451   RLI.MPI = LD->getPointerInfo();
7452   RLI.IsDereferenceable = LD->isDereferenceable();
7453   RLI.IsInvariant = LD->isInvariant();
7454   RLI.Alignment = LD->getAlignment();
7455   RLI.AAInfo = LD->getAAInfo();
7456   RLI.Ranges = LD->getRanges();
7457 
7458   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7459   return true;
7460 }
7461 
7462 // Given the head of the old chain, ResChain, insert a token factor containing
7463 // it and NewResChain, and make users of ResChain now be users of that token
7464 // factor.
7465 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7466 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7467                                         SDValue NewResChain,
7468                                         SelectionDAG &DAG) const {
7469   if (!ResChain)
7470     return;
7471 
7472   SDLoc dl(NewResChain);
7473 
7474   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7475                            NewResChain, DAG.getUNDEF(MVT::Other));
7476   assert(TF.getNode() != NewResChain.getNode() &&
7477          "A new TF really is required here");
7478 
7479   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7480   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7481 }
7482 
7483 /// Analyze profitability of direct move
7484 /// prefer float load to int load plus direct move
7485 /// when there is no integer use of int load
7486 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7487   SDNode *Origin = Op.getOperand(0).getNode();
7488   if (Origin->getOpcode() != ISD::LOAD)
7489     return true;
7490 
7491   // If there is no LXSIBZX/LXSIHZX, like Power8,
7492   // prefer direct move if the memory size is 1 or 2 bytes.
7493   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7494   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7495     return true;
7496 
7497   for (SDNode::use_iterator UI = Origin->use_begin(),
7498                             UE = Origin->use_end();
7499        UI != UE; ++UI) {
7500 
7501     // Only look at the users of the loaded value.
7502     if (UI.getUse().get().getResNo() != 0)
7503       continue;
7504 
7505     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7506         UI->getOpcode() != ISD::UINT_TO_FP)
7507       return true;
7508   }
7509 
7510   return false;
7511 }
7512 
7513 /// Custom lowers integer to floating point conversions to use
7514 /// the direct move instructions available in ISA 2.07 to avoid the
7515 /// need for load/store combinations.
7516 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7517                                                     SelectionDAG &DAG,
7518                                                     const SDLoc &dl) const {
7519   assert((Op.getValueType() == MVT::f32 ||
7520           Op.getValueType() == MVT::f64) &&
7521          "Invalid floating point type as target of conversion");
7522   assert(Subtarget.hasFPCVT() &&
7523          "Int to FP conversions with direct moves require FPCVT");
7524   SDValue FP;
7525   SDValue Src = Op.getOperand(0);
7526   bool SinglePrec = Op.getValueType() == MVT::f32;
7527   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7528   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7529   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7530                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7531 
7532   if (WordInt) {
7533     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7534                      dl, MVT::f64, Src);
7535     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7536   }
7537   else {
7538     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7539     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7540   }
7541 
7542   return FP;
7543 }
7544 
7545 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7546 
7547   EVT VecVT = Vec.getValueType();
7548   assert(VecVT.isVector() && "Expected a vector type.");
7549   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7550 
7551   EVT EltVT = VecVT.getVectorElementType();
7552   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7553   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7554 
7555   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7556   SmallVector<SDValue, 16> Ops(NumConcat);
7557   Ops[0] = Vec;
7558   SDValue UndefVec = DAG.getUNDEF(VecVT);
7559   for (unsigned i = 1; i < NumConcat; ++i)
7560     Ops[i] = UndefVec;
7561 
7562   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7563 }
7564 
7565 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7566                                                 const SDLoc &dl) const {
7567 
7568   unsigned Opc = Op.getOpcode();
7569   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7570          "Unexpected conversion type");
7571   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7572          "Supports conversions to v2f64/v4f32 only.");
7573 
7574   bool SignedConv = Opc == ISD::SINT_TO_FP;
7575   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7576 
7577   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7578   EVT WideVT = Wide.getValueType();
7579   unsigned WideNumElts = WideVT.getVectorNumElements();
7580   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7581 
7582   SmallVector<int, 16> ShuffV;
7583   for (unsigned i = 0; i < WideNumElts; ++i)
7584     ShuffV.push_back(i + WideNumElts);
7585 
7586   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7587   int SaveElts = FourEltRes ? 4 : 2;
7588   if (Subtarget.isLittleEndian())
7589     for (int i = 0; i < SaveElts; i++)
7590       ShuffV[i * Stride] = i;
7591   else
7592     for (int i = 1; i <= SaveElts; i++)
7593       ShuffV[i * Stride - 1] = i - 1;
7594 
7595   SDValue ShuffleSrc2 =
7596       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7597   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7598   unsigned ExtendOp =
7599       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7600 
7601   SDValue Extend;
7602   if (!Subtarget.hasP9Altivec() && SignedConv) {
7603     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7604     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7605                          DAG.getValueType(Op.getOperand(0).getValueType()));
7606   } else
7607     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7608 
7609   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7610 }
7611 
7612 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7613                                           SelectionDAG &DAG) const {
7614   SDLoc dl(Op);
7615 
7616   EVT InVT = Op.getOperand(0).getValueType();
7617   EVT OutVT = Op.getValueType();
7618   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7619       isOperationCustom(Op.getOpcode(), InVT))
7620     return LowerINT_TO_FPVector(Op, DAG, dl);
7621 
7622   // Conversions to f128 are legal.
7623   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7624     return Op;
7625 
7626   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7627     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7628       return SDValue();
7629 
7630     SDValue Value = Op.getOperand(0);
7631     // The values are now known to be -1 (false) or 1 (true). To convert this
7632     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7633     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7634     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7635 
7636     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7637 
7638     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7639 
7640     if (Op.getValueType() != MVT::v4f64)
7641       Value = DAG.getNode(ISD::FP_ROUND, dl,
7642                           Op.getValueType(), Value,
7643                           DAG.getIntPtrConstant(1, dl));
7644     return Value;
7645   }
7646 
7647   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7648   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7649     return SDValue();
7650 
7651   if (Op.getOperand(0).getValueType() == MVT::i1)
7652     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7653                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7654                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7655 
7656   // If we have direct moves, we can do all the conversion, skip the store/load
7657   // however, without FPCVT we can't do most conversions.
7658   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7659       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7660     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7661 
7662   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7663          "UINT_TO_FP is supported only with FPCVT");
7664 
7665   // If we have FCFIDS, then use it when converting to single-precision.
7666   // Otherwise, convert to double-precision and then round.
7667   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7668                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7669                                                             : PPCISD::FCFIDS)
7670                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7671                                                             : PPCISD::FCFID);
7672   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7673                   ? MVT::f32
7674                   : MVT::f64;
7675 
7676   if (Op.getOperand(0).getValueType() == MVT::i64) {
7677     SDValue SINT = Op.getOperand(0);
7678     // When converting to single-precision, we actually need to convert
7679     // to double-precision first and then round to single-precision.
7680     // To avoid double-rounding effects during that operation, we have
7681     // to prepare the input operand.  Bits that might be truncated when
7682     // converting to double-precision are replaced by a bit that won't
7683     // be lost at this stage, but is below the single-precision rounding
7684     // position.
7685     //
7686     // However, if -enable-unsafe-fp-math is in effect, accept double
7687     // rounding to avoid the extra overhead.
7688     if (Op.getValueType() == MVT::f32 &&
7689         !Subtarget.hasFPCVT() &&
7690         !DAG.getTarget().Options.UnsafeFPMath) {
7691 
7692       // Twiddle input to make sure the low 11 bits are zero.  (If this
7693       // is the case, we are guaranteed the value will fit into the 53 bit
7694       // mantissa of an IEEE double-precision value without rounding.)
7695       // If any of those low 11 bits were not zero originally, make sure
7696       // bit 12 (value 2048) is set instead, so that the final rounding
7697       // to single-precision gets the correct result.
7698       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7699                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7700       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7701                           Round, DAG.getConstant(2047, dl, MVT::i64));
7702       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7703       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7704                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7705 
7706       // However, we cannot use that value unconditionally: if the magnitude
7707       // of the input value is small, the bit-twiddling we did above might
7708       // end up visibly changing the output.  Fortunately, in that case, we
7709       // don't need to twiddle bits since the original input will convert
7710       // exactly to double-precision floating-point already.  Therefore,
7711       // construct a conditional to use the original value if the top 11
7712       // bits are all sign-bit copies, and use the rounded value computed
7713       // above otherwise.
7714       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7715                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7716       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7717                          Cond, DAG.getConstant(1, dl, MVT::i64));
7718       Cond = DAG.getSetCC(dl, MVT::i32,
7719                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7720 
7721       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7722     }
7723 
7724     ReuseLoadInfo RLI;
7725     SDValue Bits;
7726 
7727     MachineFunction &MF = DAG.getMachineFunction();
7728     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7729       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7730                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7731       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7732     } else if (Subtarget.hasLFIWAX() &&
7733                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7734       MachineMemOperand *MMO =
7735         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7736                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7737       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7738       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7739                                      DAG.getVTList(MVT::f64, MVT::Other),
7740                                      Ops, MVT::i32, MMO);
7741       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7742     } else if (Subtarget.hasFPCVT() &&
7743                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7744       MachineMemOperand *MMO =
7745         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7746                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7747       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7748       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7749                                      DAG.getVTList(MVT::f64, MVT::Other),
7750                                      Ops, MVT::i32, MMO);
7751       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7752     } else if (((Subtarget.hasLFIWAX() &&
7753                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7754                 (Subtarget.hasFPCVT() &&
7755                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7756                SINT.getOperand(0).getValueType() == MVT::i32) {
7757       MachineFrameInfo &MFI = MF.getFrameInfo();
7758       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7759 
7760       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7761       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7762 
7763       SDValue Store =
7764           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7765                        MachinePointerInfo::getFixedStack(
7766                            DAG.getMachineFunction(), FrameIdx));
7767 
7768       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7769              "Expected an i32 store");
7770 
7771       RLI.Ptr = FIdx;
7772       RLI.Chain = Store;
7773       RLI.MPI =
7774           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7775       RLI.Alignment = 4;
7776 
7777       MachineMemOperand *MMO =
7778         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7779                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7780       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7781       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7782                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7783                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7784                                      Ops, MVT::i32, MMO);
7785     } else
7786       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7787 
7788     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7789 
7790     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7791       FP = DAG.getNode(ISD::FP_ROUND, dl,
7792                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7793     return FP;
7794   }
7795 
7796   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7797          "Unhandled INT_TO_FP type in custom expander!");
7798   // Since we only generate this in 64-bit mode, we can take advantage of
7799   // 64-bit registers.  In particular, sign extend the input value into the
7800   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7801   // then lfd it and fcfid it.
7802   MachineFunction &MF = DAG.getMachineFunction();
7803   MachineFrameInfo &MFI = MF.getFrameInfo();
7804   EVT PtrVT = getPointerTy(MF.getDataLayout());
7805 
7806   SDValue Ld;
7807   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7808     ReuseLoadInfo RLI;
7809     bool ReusingLoad;
7810     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7811                                             DAG))) {
7812       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7813       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7814 
7815       SDValue Store =
7816           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7817                        MachinePointerInfo::getFixedStack(
7818                            DAG.getMachineFunction(), FrameIdx));
7819 
7820       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7821              "Expected an i32 store");
7822 
7823       RLI.Ptr = FIdx;
7824       RLI.Chain = Store;
7825       RLI.MPI =
7826           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7827       RLI.Alignment = 4;
7828     }
7829 
7830     MachineMemOperand *MMO =
7831       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7832                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7833     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7834     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7835                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7836                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7837                                  Ops, MVT::i32, MMO);
7838     if (ReusingLoad)
7839       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7840   } else {
7841     assert(Subtarget.isPPC64() &&
7842            "i32->FP without LFIWAX supported only on PPC64");
7843 
7844     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7845     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7846 
7847     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7848                                 Op.getOperand(0));
7849 
7850     // STD the extended value into the stack slot.
7851     SDValue Store = DAG.getStore(
7852         DAG.getEntryNode(), dl, Ext64, FIdx,
7853         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7854 
7855     // Load the value as a double.
7856     Ld = DAG.getLoad(
7857         MVT::f64, dl, Store, FIdx,
7858         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7859   }
7860 
7861   // FCFID it and return it.
7862   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7863   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7864     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7865                      DAG.getIntPtrConstant(0, dl));
7866   return FP;
7867 }
7868 
7869 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7870                                             SelectionDAG &DAG) const {
7871   SDLoc dl(Op);
7872   /*
7873    The rounding mode is in bits 30:31 of FPSR, and has the following
7874    settings:
7875      00 Round to nearest
7876      01 Round to 0
7877      10 Round to +inf
7878      11 Round to -inf
7879 
7880   FLT_ROUNDS, on the other hand, expects the following:
7881     -1 Undefined
7882      0 Round to 0
7883      1 Round to nearest
7884      2 Round to +inf
7885      3 Round to -inf
7886 
7887   To perform the conversion, we do:
7888     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7889   */
7890 
7891   MachineFunction &MF = DAG.getMachineFunction();
7892   EVT VT = Op.getValueType();
7893   EVT PtrVT = getPointerTy(MF.getDataLayout());
7894 
7895   // Save FP Control Word to register
7896   EVT NodeTys[] = {
7897     MVT::f64,    // return register
7898     MVT::Glue    // unused in this context
7899   };
7900   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7901 
7902   // Save FP register to stack slot
7903   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7904   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7905   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7906                                MachinePointerInfo());
7907 
7908   // Load FP Control Word from low 32 bits of stack slot.
7909   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7910   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7911   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7912 
7913   // Transform as necessary
7914   SDValue CWD1 =
7915     DAG.getNode(ISD::AND, dl, MVT::i32,
7916                 CWD, DAG.getConstant(3, dl, MVT::i32));
7917   SDValue CWD2 =
7918     DAG.getNode(ISD::SRL, dl, MVT::i32,
7919                 DAG.getNode(ISD::AND, dl, MVT::i32,
7920                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7921                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7922                             DAG.getConstant(3, dl, MVT::i32)),
7923                 DAG.getConstant(1, dl, MVT::i32));
7924 
7925   SDValue RetVal =
7926     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7927 
7928   return DAG.getNode((VT.getSizeInBits() < 16 ?
7929                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7930 }
7931 
7932 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7933   EVT VT = Op.getValueType();
7934   unsigned BitWidth = VT.getSizeInBits();
7935   SDLoc dl(Op);
7936   assert(Op.getNumOperands() == 3 &&
7937          VT == Op.getOperand(1).getValueType() &&
7938          "Unexpected SHL!");
7939 
7940   // Expand into a bunch of logical ops.  Note that these ops
7941   // depend on the PPC behavior for oversized shift amounts.
7942   SDValue Lo = Op.getOperand(0);
7943   SDValue Hi = Op.getOperand(1);
7944   SDValue Amt = Op.getOperand(2);
7945   EVT AmtVT = Amt.getValueType();
7946 
7947   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7948                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7949   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7950   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7951   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7952   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7953                              DAG.getConstant(-BitWidth, dl, AmtVT));
7954   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7955   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7956   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7957   SDValue OutOps[] = { OutLo, OutHi };
7958   return DAG.getMergeValues(OutOps, dl);
7959 }
7960 
7961 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7962   EVT VT = Op.getValueType();
7963   SDLoc dl(Op);
7964   unsigned BitWidth = VT.getSizeInBits();
7965   assert(Op.getNumOperands() == 3 &&
7966          VT == Op.getOperand(1).getValueType() &&
7967          "Unexpected SRL!");
7968 
7969   // Expand into a bunch of logical ops.  Note that these ops
7970   // depend on the PPC behavior for oversized shift amounts.
7971   SDValue Lo = Op.getOperand(0);
7972   SDValue Hi = Op.getOperand(1);
7973   SDValue Amt = Op.getOperand(2);
7974   EVT AmtVT = Amt.getValueType();
7975 
7976   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7977                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7978   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7979   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7980   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7981   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7982                              DAG.getConstant(-BitWidth, dl, AmtVT));
7983   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7984   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7985   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7986   SDValue OutOps[] = { OutLo, OutHi };
7987   return DAG.getMergeValues(OutOps, dl);
7988 }
7989 
7990 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7991   SDLoc dl(Op);
7992   EVT VT = Op.getValueType();
7993   unsigned BitWidth = VT.getSizeInBits();
7994   assert(Op.getNumOperands() == 3 &&
7995          VT == Op.getOperand(1).getValueType() &&
7996          "Unexpected SRA!");
7997 
7998   // Expand into a bunch of logical ops, followed by a select_cc.
7999   SDValue Lo = Op.getOperand(0);
8000   SDValue Hi = Op.getOperand(1);
8001   SDValue Amt = Op.getOperand(2);
8002   EVT AmtVT = Amt.getValueType();
8003 
8004   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8005                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8006   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8007   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8008   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8009   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8010                              DAG.getConstant(-BitWidth, dl, AmtVT));
8011   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8012   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8013   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8014                                   Tmp4, Tmp6, ISD::SETLE);
8015   SDValue OutOps[] = { OutLo, OutHi };
8016   return DAG.getMergeValues(OutOps, dl);
8017 }
8018 
8019 //===----------------------------------------------------------------------===//
8020 // Vector related lowering.
8021 //
8022 
8023 /// BuildSplatI - Build a canonical splati of Val with an element size of
8024 /// SplatSize.  Cast the result to VT.
8025 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8026                            SelectionDAG &DAG, const SDLoc &dl) {
8027   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
8028 
8029   static const MVT VTys[] = { // canonical VT to use for each size.
8030     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8031   };
8032 
8033   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8034 
8035   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8036   if (Val == -1)
8037     SplatSize = 1;
8038 
8039   EVT CanonicalVT = VTys[SplatSize-1];
8040 
8041   // Build a canonical splat for this value.
8042   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8043 }
8044 
8045 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8046 /// specified intrinsic ID.
8047 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8048                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8049   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8050   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8051                      DAG.getConstant(IID, dl, MVT::i32), Op);
8052 }
8053 
8054 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8055 /// specified intrinsic ID.
8056 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8057                                 SelectionDAG &DAG, const SDLoc &dl,
8058                                 EVT DestVT = MVT::Other) {
8059   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8060   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8061                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8062 }
8063 
8064 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8065 /// specified intrinsic ID.
8066 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8067                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8068                                 EVT DestVT = MVT::Other) {
8069   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8070   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8071                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8072 }
8073 
8074 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8075 /// amount.  The result has the specified value type.
8076 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8077                            SelectionDAG &DAG, const SDLoc &dl) {
8078   // Force LHS/RHS to be the right type.
8079   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8080   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8081 
8082   int Ops[16];
8083   for (unsigned i = 0; i != 16; ++i)
8084     Ops[i] = i + Amt;
8085   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8086   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8087 }
8088 
8089 /// Do we have an efficient pattern in a .td file for this node?
8090 ///
8091 /// \param V - pointer to the BuildVectorSDNode being matched
8092 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8093 ///
8094 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8095 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8096 /// the opposite is true (expansion is beneficial) are:
8097 /// - The node builds a vector out of integers that are not 32 or 64-bits
8098 /// - The node builds a vector out of constants
8099 /// - The node is a "load-and-splat"
8100 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8101 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8102                                             bool HasDirectMove,
8103                                             bool HasP8Vector) {
8104   EVT VecVT = V->getValueType(0);
8105   bool RightType = VecVT == MVT::v2f64 ||
8106     (HasP8Vector && VecVT == MVT::v4f32) ||
8107     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8108   if (!RightType)
8109     return false;
8110 
8111   bool IsSplat = true;
8112   bool IsLoad = false;
8113   SDValue Op0 = V->getOperand(0);
8114 
8115   // This function is called in a block that confirms the node is not a constant
8116   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8117   // different constants.
8118   if (V->isConstant())
8119     return false;
8120   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8121     if (V->getOperand(i).isUndef())
8122       return false;
8123     // We want to expand nodes that represent load-and-splat even if the
8124     // loaded value is a floating point truncation or conversion to int.
8125     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8126         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8127          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8128         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8129          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8130         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8131          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8132       IsLoad = true;
8133     // If the operands are different or the input is not a load and has more
8134     // uses than just this BV node, then it isn't a splat.
8135     if (V->getOperand(i) != Op0 ||
8136         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8137       IsSplat = false;
8138   }
8139   return !(IsSplat && IsLoad);
8140 }
8141 
8142 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8143 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8144 
8145   SDLoc dl(Op);
8146   SDValue Op0 = Op->getOperand(0);
8147 
8148   if (!EnableQuadPrecision ||
8149       (Op.getValueType() != MVT::f128 ) ||
8150       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8151       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8152       (Op0.getOperand(1).getValueType() != MVT::i64))
8153     return SDValue();
8154 
8155   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8156                      Op0.getOperand(1));
8157 }
8158 
8159 // If this is a case we can't handle, return null and let the default
8160 // expansion code take care of it.  If we CAN select this case, and if it
8161 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8162 // this case more efficiently than a constant pool load, lower it to the
8163 // sequence of ops that should be used.
8164 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8165                                              SelectionDAG &DAG) const {
8166   SDLoc dl(Op);
8167   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8168   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8169 
8170   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8171     // We first build an i32 vector, load it into a QPX register,
8172     // then convert it to a floating-point vector and compare it
8173     // to a zero vector to get the boolean result.
8174     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8175     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8176     MachinePointerInfo PtrInfo =
8177         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8178     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8179     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8180 
8181     assert(BVN->getNumOperands() == 4 &&
8182       "BUILD_VECTOR for v4i1 does not have 4 operands");
8183 
8184     bool IsConst = true;
8185     for (unsigned i = 0; i < 4; ++i) {
8186       if (BVN->getOperand(i).isUndef()) continue;
8187       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8188         IsConst = false;
8189         break;
8190       }
8191     }
8192 
8193     if (IsConst) {
8194       Constant *One =
8195         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8196       Constant *NegOne =
8197         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8198 
8199       Constant *CV[4];
8200       for (unsigned i = 0; i < 4; ++i) {
8201         if (BVN->getOperand(i).isUndef())
8202           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8203         else if (isNullConstant(BVN->getOperand(i)))
8204           CV[i] = NegOne;
8205         else
8206           CV[i] = One;
8207       }
8208 
8209       Constant *CP = ConstantVector::get(CV);
8210       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8211                                           16 /* alignment */);
8212 
8213       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8214       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8215       return DAG.getMemIntrinsicNode(
8216           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8217           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8218     }
8219 
8220     SmallVector<SDValue, 4> Stores;
8221     for (unsigned i = 0; i < 4; ++i) {
8222       if (BVN->getOperand(i).isUndef()) continue;
8223 
8224       unsigned Offset = 4*i;
8225       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8226       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8227 
8228       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8229       if (StoreSize > 4) {
8230         Stores.push_back(
8231             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8232                               PtrInfo.getWithOffset(Offset), MVT::i32));
8233       } else {
8234         SDValue StoreValue = BVN->getOperand(i);
8235         if (StoreSize < 4)
8236           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8237 
8238         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8239                                       PtrInfo.getWithOffset(Offset)));
8240       }
8241     }
8242 
8243     SDValue StoreChain;
8244     if (!Stores.empty())
8245       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8246     else
8247       StoreChain = DAG.getEntryNode();
8248 
8249     // Now load from v4i32 into the QPX register; this will extend it to
8250     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8251     // is typed as v4f64 because the QPX register integer states are not
8252     // explicitly represented.
8253 
8254     SDValue Ops[] = {StoreChain,
8255                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8256                      FIdx};
8257     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8258 
8259     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8260       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8261     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8262       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8263       LoadedVect);
8264 
8265     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8266 
8267     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8268   }
8269 
8270   // All other QPX vectors are handled by generic code.
8271   if (Subtarget.hasQPX())
8272     return SDValue();
8273 
8274   // Check if this is a splat of a constant value.
8275   APInt APSplatBits, APSplatUndef;
8276   unsigned SplatBitSize;
8277   bool HasAnyUndefs;
8278   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8279                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8280       SplatBitSize > 32) {
8281     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8282     // lowered to VSX instructions under certain conditions.
8283     // Without VSX, there is no pattern more efficient than expanding the node.
8284     if (Subtarget.hasVSX() &&
8285         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8286                                         Subtarget.hasP8Vector()))
8287       return Op;
8288     return SDValue();
8289   }
8290 
8291   unsigned SplatBits = APSplatBits.getZExtValue();
8292   unsigned SplatUndef = APSplatUndef.getZExtValue();
8293   unsigned SplatSize = SplatBitSize / 8;
8294 
8295   // First, handle single instruction cases.
8296 
8297   // All zeros?
8298   if (SplatBits == 0) {
8299     // Canonicalize all zero vectors to be v4i32.
8300     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8301       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8302       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8303     }
8304     return Op;
8305   }
8306 
8307   // We have XXSPLTIB for constant splats one byte wide
8308   if (Subtarget.hasP9Vector() && SplatSize == 1) {
8309     // This is a splat of 1-byte elements with some elements potentially undef.
8310     // Rather than trying to match undef in the SDAG patterns, ensure that all
8311     // elements are the same constant.
8312     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
8313       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
8314                                                        dl, MVT::i32));
8315       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
8316       if (Op.getValueType() != MVT::v16i8)
8317         return DAG.getBitcast(Op.getValueType(), NewBV);
8318       return NewBV;
8319     }
8320 
8321     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
8322     // detect that constant splats like v8i16: 0xABAB are really just splats
8323     // of a 1-byte constant. In this case, we need to convert the node to a
8324     // splat of v16i8 and a bitcast.
8325     if (Op.getValueType() != MVT::v16i8)
8326       return DAG.getBitcast(Op.getValueType(),
8327                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
8328 
8329     return Op;
8330   }
8331 
8332   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8333   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8334                     (32-SplatBitSize));
8335   if (SextVal >= -16 && SextVal <= 15)
8336     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8337 
8338   // Two instruction sequences.
8339 
8340   // If this value is in the range [-32,30] and is even, use:
8341   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8342   // If this value is in the range [17,31] and is odd, use:
8343   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8344   // If this value is in the range [-31,-17] and is odd, use:
8345   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8346   // Note the last two are three-instruction sequences.
8347   if (SextVal >= -32 && SextVal <= 31) {
8348     // To avoid having these optimizations undone by constant folding,
8349     // we convert to a pseudo that will be expanded later into one of
8350     // the above forms.
8351     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8352     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8353               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8354     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8355     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8356     if (VT == Op.getValueType())
8357       return RetVal;
8358     else
8359       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8360   }
8361 
8362   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8363   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8364   // for fneg/fabs.
8365   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8366     // Make -1 and vspltisw -1:
8367     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8368 
8369     // Make the VSLW intrinsic, computing 0x8000_0000.
8370     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8371                                    OnesV, DAG, dl);
8372 
8373     // xor by OnesV to invert it.
8374     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8375     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8376   }
8377 
8378   // Check to see if this is a wide variety of vsplti*, binop self cases.
8379   static const signed char SplatCsts[] = {
8380     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8381     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8382   };
8383 
8384   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8385     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8386     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8387     int i = SplatCsts[idx];
8388 
8389     // Figure out what shift amount will be used by altivec if shifted by i in
8390     // this splat size.
8391     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8392 
8393     // vsplti + shl self.
8394     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8395       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8396       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8397         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8398         Intrinsic::ppc_altivec_vslw
8399       };
8400       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8401       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8402     }
8403 
8404     // vsplti + srl self.
8405     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8406       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8407       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8408         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8409         Intrinsic::ppc_altivec_vsrw
8410       };
8411       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8412       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8413     }
8414 
8415     // vsplti + sra self.
8416     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8417       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8418       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8419         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8420         Intrinsic::ppc_altivec_vsraw
8421       };
8422       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8423       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8424     }
8425 
8426     // vsplti + rol self.
8427     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8428                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8429       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8430       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8431         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8432         Intrinsic::ppc_altivec_vrlw
8433       };
8434       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8435       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8436     }
8437 
8438     // t = vsplti c, result = vsldoi t, t, 1
8439     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8440       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8441       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8442       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8443     }
8444     // t = vsplti c, result = vsldoi t, t, 2
8445     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8446       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8447       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8448       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8449     }
8450     // t = vsplti c, result = vsldoi t, t, 3
8451     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8452       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8453       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8454       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8455     }
8456   }
8457 
8458   return SDValue();
8459 }
8460 
8461 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8462 /// the specified operations to build the shuffle.
8463 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8464                                       SDValue RHS, SelectionDAG &DAG,
8465                                       const SDLoc &dl) {
8466   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8467   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8468   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8469 
8470   enum {
8471     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8472     OP_VMRGHW,
8473     OP_VMRGLW,
8474     OP_VSPLTISW0,
8475     OP_VSPLTISW1,
8476     OP_VSPLTISW2,
8477     OP_VSPLTISW3,
8478     OP_VSLDOI4,
8479     OP_VSLDOI8,
8480     OP_VSLDOI12
8481   };
8482 
8483   if (OpNum == OP_COPY) {
8484     if (LHSID == (1*9+2)*9+3) return LHS;
8485     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8486     return RHS;
8487   }
8488 
8489   SDValue OpLHS, OpRHS;
8490   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8491   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8492 
8493   int ShufIdxs[16];
8494   switch (OpNum) {
8495   default: llvm_unreachable("Unknown i32 permute!");
8496   case OP_VMRGHW:
8497     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8498     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8499     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8500     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8501     break;
8502   case OP_VMRGLW:
8503     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8504     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8505     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8506     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8507     break;
8508   case OP_VSPLTISW0:
8509     for (unsigned i = 0; i != 16; ++i)
8510       ShufIdxs[i] = (i&3)+0;
8511     break;
8512   case OP_VSPLTISW1:
8513     for (unsigned i = 0; i != 16; ++i)
8514       ShufIdxs[i] = (i&3)+4;
8515     break;
8516   case OP_VSPLTISW2:
8517     for (unsigned i = 0; i != 16; ++i)
8518       ShufIdxs[i] = (i&3)+8;
8519     break;
8520   case OP_VSPLTISW3:
8521     for (unsigned i = 0; i != 16; ++i)
8522       ShufIdxs[i] = (i&3)+12;
8523     break;
8524   case OP_VSLDOI4:
8525     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8526   case OP_VSLDOI8:
8527     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8528   case OP_VSLDOI12:
8529     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8530   }
8531   EVT VT = OpLHS.getValueType();
8532   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8533   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8534   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8535   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8536 }
8537 
8538 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8539 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8540 /// SDValue.
8541 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8542                                            SelectionDAG &DAG) const {
8543   const unsigned BytesInVector = 16;
8544   bool IsLE = Subtarget.isLittleEndian();
8545   SDLoc dl(N);
8546   SDValue V1 = N->getOperand(0);
8547   SDValue V2 = N->getOperand(1);
8548   unsigned ShiftElts = 0, InsertAtByte = 0;
8549   bool Swap = false;
8550 
8551   // Shifts required to get the byte we want at element 7.
8552   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8553                                    0, 15, 14, 13, 12, 11, 10, 9};
8554   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8555                                 1, 2,  3,  4,  5,  6,  7,  8};
8556 
8557   ArrayRef<int> Mask = N->getMask();
8558   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8559 
8560   // For each mask element, find out if we're just inserting something
8561   // from V2 into V1 or vice versa.
8562   // Possible permutations inserting an element from V2 into V1:
8563   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8564   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8565   //   ...
8566   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8567   // Inserting from V1 into V2 will be similar, except mask range will be
8568   // [16,31].
8569 
8570   bool FoundCandidate = false;
8571   // If both vector operands for the shuffle are the same vector, the mask
8572   // will contain only elements from the first one and the second one will be
8573   // undef.
8574   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8575   // Go through the mask of half-words to find an element that's being moved
8576   // from one vector to the other.
8577   for (unsigned i = 0; i < BytesInVector; ++i) {
8578     unsigned CurrentElement = Mask[i];
8579     // If 2nd operand is undefined, we should only look for element 7 in the
8580     // Mask.
8581     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8582       continue;
8583 
8584     bool OtherElementsInOrder = true;
8585     // Examine the other elements in the Mask to see if they're in original
8586     // order.
8587     for (unsigned j = 0; j < BytesInVector; ++j) {
8588       if (j == i)
8589         continue;
8590       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8591       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8592       // in which we always assume we're always picking from the 1st operand.
8593       int MaskOffset =
8594           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8595       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8596         OtherElementsInOrder = false;
8597         break;
8598       }
8599     }
8600     // If other elements are in original order, we record the number of shifts
8601     // we need to get the element we want into element 7. Also record which byte
8602     // in the vector we should insert into.
8603     if (OtherElementsInOrder) {
8604       // If 2nd operand is undefined, we assume no shifts and no swapping.
8605       if (V2.isUndef()) {
8606         ShiftElts = 0;
8607         Swap = false;
8608       } else {
8609         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8610         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8611                          : BigEndianShifts[CurrentElement & 0xF];
8612         Swap = CurrentElement < BytesInVector;
8613       }
8614       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8615       FoundCandidate = true;
8616       break;
8617     }
8618   }
8619 
8620   if (!FoundCandidate)
8621     return SDValue();
8622 
8623   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8624   // optionally with VECSHL if shift is required.
8625   if (Swap)
8626     std::swap(V1, V2);
8627   if (V2.isUndef())
8628     V2 = V1;
8629   if (ShiftElts) {
8630     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8631                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8632     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8633                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8634   }
8635   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8636                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8637 }
8638 
8639 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8640 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8641 /// SDValue.
8642 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8643                                            SelectionDAG &DAG) const {
8644   const unsigned NumHalfWords = 8;
8645   const unsigned BytesInVector = NumHalfWords * 2;
8646   // Check that the shuffle is on half-words.
8647   if (!isNByteElemShuffleMask(N, 2, 1))
8648     return SDValue();
8649 
8650   bool IsLE = Subtarget.isLittleEndian();
8651   SDLoc dl(N);
8652   SDValue V1 = N->getOperand(0);
8653   SDValue V2 = N->getOperand(1);
8654   unsigned ShiftElts = 0, InsertAtByte = 0;
8655   bool Swap = false;
8656 
8657   // Shifts required to get the half-word we want at element 3.
8658   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8659   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8660 
8661   uint32_t Mask = 0;
8662   uint32_t OriginalOrderLow = 0x1234567;
8663   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8664   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8665   // 32-bit space, only need 4-bit nibbles per element.
8666   for (unsigned i = 0; i < NumHalfWords; ++i) {
8667     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8668     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8669   }
8670 
8671   // For each mask element, find out if we're just inserting something
8672   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8673   // from V2 into V1:
8674   //   X, 1, 2, 3, 4, 5, 6, 7
8675   //   0, X, 2, 3, 4, 5, 6, 7
8676   //   0, 1, X, 3, 4, 5, 6, 7
8677   //   0, 1, 2, X, 4, 5, 6, 7
8678   //   0, 1, 2, 3, X, 5, 6, 7
8679   //   0, 1, 2, 3, 4, X, 6, 7
8680   //   0, 1, 2, 3, 4, 5, X, 7
8681   //   0, 1, 2, 3, 4, 5, 6, X
8682   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8683 
8684   bool FoundCandidate = false;
8685   // Go through the mask of half-words to find an element that's being moved
8686   // from one vector to the other.
8687   for (unsigned i = 0; i < NumHalfWords; ++i) {
8688     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8689     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8690     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8691     uint32_t TargetOrder = 0x0;
8692 
8693     // If both vector operands for the shuffle are the same vector, the mask
8694     // will contain only elements from the first one and the second one will be
8695     // undef.
8696     if (V2.isUndef()) {
8697       ShiftElts = 0;
8698       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8699       TargetOrder = OriginalOrderLow;
8700       Swap = false;
8701       // Skip if not the correct element or mask of other elements don't equal
8702       // to our expected order.
8703       if (MaskOneElt == VINSERTHSrcElem &&
8704           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8705         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8706         FoundCandidate = true;
8707         break;
8708       }
8709     } else { // If both operands are defined.
8710       // Target order is [8,15] if the current mask is between [0,7].
8711       TargetOrder =
8712           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8713       // Skip if mask of other elements don't equal our expected order.
8714       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8715         // We only need the last 3 bits for the number of shifts.
8716         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8717                          : BigEndianShifts[MaskOneElt & 0x7];
8718         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8719         Swap = MaskOneElt < NumHalfWords;
8720         FoundCandidate = true;
8721         break;
8722       }
8723     }
8724   }
8725 
8726   if (!FoundCandidate)
8727     return SDValue();
8728 
8729   // Candidate found, construct the proper SDAG sequence with VINSERTH,
8730   // optionally with VECSHL if shift is required.
8731   if (Swap)
8732     std::swap(V1, V2);
8733   if (V2.isUndef())
8734     V2 = V1;
8735   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8736   if (ShiftElts) {
8737     // Double ShiftElts because we're left shifting on v16i8 type.
8738     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8739                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8740     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8741     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8742                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8743     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8744   }
8745   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8746   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8747                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8748   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8749 }
8750 
8751 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8752 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8753 /// return the code it can be lowered into.  Worst case, it can always be
8754 /// lowered into a vperm.
8755 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8756                                                SelectionDAG &DAG) const {
8757   SDLoc dl(Op);
8758   SDValue V1 = Op.getOperand(0);
8759   SDValue V2 = Op.getOperand(1);
8760   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8761   EVT VT = Op.getValueType();
8762   bool isLittleEndian = Subtarget.isLittleEndian();
8763 
8764   unsigned ShiftElts, InsertAtByte;
8765   bool Swap = false;
8766   if (Subtarget.hasP9Vector() &&
8767       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8768                            isLittleEndian)) {
8769     if (Swap)
8770       std::swap(V1, V2);
8771     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8772     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8773     if (ShiftElts) {
8774       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8775                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8776       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8777                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8778       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8779     }
8780     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8781                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8782     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8783   }
8784 
8785   if (Subtarget.hasP9Altivec()) {
8786     SDValue NewISDNode;
8787     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8788       return NewISDNode;
8789 
8790     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8791       return NewISDNode;
8792   }
8793 
8794   if (Subtarget.hasVSX() &&
8795       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8796     if (Swap)
8797       std::swap(V1, V2);
8798     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8799     SDValue Conv2 =
8800         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8801 
8802     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8803                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8804     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8805   }
8806 
8807   if (Subtarget.hasVSX() &&
8808     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8809     if (Swap)
8810       std::swap(V1, V2);
8811     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8812     SDValue Conv2 =
8813         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8814 
8815     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8816                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8817     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8818   }
8819 
8820   if (Subtarget.hasP9Vector()) {
8821      if (PPC::isXXBRHShuffleMask(SVOp)) {
8822       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8823       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8824       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8825     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8826       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8827       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8828       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8829     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8830       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8831       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8832       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8833     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8834       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8835       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8836       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8837     }
8838   }
8839 
8840   if (Subtarget.hasVSX()) {
8841     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8842       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8843 
8844       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8845       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8846                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8847       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8848     }
8849 
8850     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8851     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8852       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8853       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8854       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8855     }
8856   }
8857 
8858   if (Subtarget.hasQPX()) {
8859     if (VT.getVectorNumElements() != 4)
8860       return SDValue();
8861 
8862     if (V2.isUndef()) V2 = V1;
8863 
8864     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8865     if (AlignIdx != -1) {
8866       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8867                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8868     } else if (SVOp->isSplat()) {
8869       int SplatIdx = SVOp->getSplatIndex();
8870       if (SplatIdx >= 4) {
8871         std::swap(V1, V2);
8872         SplatIdx -= 4;
8873       }
8874 
8875       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8876                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8877     }
8878 
8879     // Lower this into a qvgpci/qvfperm pair.
8880 
8881     // Compute the qvgpci literal
8882     unsigned idx = 0;
8883     for (unsigned i = 0; i < 4; ++i) {
8884       int m = SVOp->getMaskElt(i);
8885       unsigned mm = m >= 0 ? (unsigned) m : i;
8886       idx |= mm << (3-i)*3;
8887     }
8888 
8889     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8890                              DAG.getConstant(idx, dl, MVT::i32));
8891     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8892   }
8893 
8894   // Cases that are handled by instructions that take permute immediates
8895   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8896   // selected by the instruction selector.
8897   if (V2.isUndef()) {
8898     if (PPC::isSplatShuffleMask(SVOp, 1) ||
8899         PPC::isSplatShuffleMask(SVOp, 2) ||
8900         PPC::isSplatShuffleMask(SVOp, 4) ||
8901         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8902         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8903         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8904         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8905         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8906         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8907         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8908         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8909         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8910         (Subtarget.hasP8Altivec() && (
8911          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8912          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8913          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8914       return Op;
8915     }
8916   }
8917 
8918   // Altivec has a variety of "shuffle immediates" that take two vector inputs
8919   // and produce a fixed permutation.  If any of these match, do not lower to
8920   // VPERM.
8921   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8922   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8923       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8924       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8925       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8926       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8927       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8928       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8929       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8930       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8931       (Subtarget.hasP8Altivec() && (
8932        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8933        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8934        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8935     return Op;
8936 
8937   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
8938   // perfect shuffle table to emit an optimal matching sequence.
8939   ArrayRef<int> PermMask = SVOp->getMask();
8940 
8941   unsigned PFIndexes[4];
8942   bool isFourElementShuffle = true;
8943   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8944     unsigned EltNo = 8;   // Start out undef.
8945     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
8946       if (PermMask[i*4+j] < 0)
8947         continue;   // Undef, ignore it.
8948 
8949       unsigned ByteSource = PermMask[i*4+j];
8950       if ((ByteSource & 3) != j) {
8951         isFourElementShuffle = false;
8952         break;
8953       }
8954 
8955       if (EltNo == 8) {
8956         EltNo = ByteSource/4;
8957       } else if (EltNo != ByteSource/4) {
8958         isFourElementShuffle = false;
8959         break;
8960       }
8961     }
8962     PFIndexes[i] = EltNo;
8963   }
8964 
8965   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8966   // perfect shuffle vector to determine if it is cost effective to do this as
8967   // discrete instructions, or whether we should use a vperm.
8968   // For now, we skip this for little endian until such time as we have a
8969   // little-endian perfect shuffle table.
8970   if (isFourElementShuffle && !isLittleEndian) {
8971     // Compute the index in the perfect shuffle table.
8972     unsigned PFTableIndex =
8973       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8974 
8975     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8976     unsigned Cost  = (PFEntry >> 30);
8977 
8978     // Determining when to avoid vperm is tricky.  Many things affect the cost
8979     // of vperm, particularly how many times the perm mask needs to be computed.
8980     // For example, if the perm mask can be hoisted out of a loop or is already
8981     // used (perhaps because there are multiple permutes with the same shuffle
8982     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
8983     // the loop requires an extra register.
8984     //
8985     // As a compromise, we only emit discrete instructions if the shuffle can be
8986     // generated in 3 or fewer operations.  When we have loop information
8987     // available, if this block is within a loop, we should avoid using vperm
8988     // for 3-operation perms and use a constant pool load instead.
8989     if (Cost < 3)
8990       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8991   }
8992 
8993   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8994   // vector that will get spilled to the constant pool.
8995   if (V2.isUndef()) V2 = V1;
8996 
8997   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8998   // that it is in input element units, not in bytes.  Convert now.
8999 
9000   // For little endian, the order of the input vectors is reversed, and
9001   // the permutation mask is complemented with respect to 31.  This is
9002   // necessary to produce proper semantics with the big-endian-biased vperm
9003   // instruction.
9004   EVT EltVT = V1.getValueType().getVectorElementType();
9005   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9006 
9007   SmallVector<SDValue, 16> ResultMask;
9008   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9009     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9010 
9011     for (unsigned j = 0; j != BytesPerElement; ++j)
9012       if (isLittleEndian)
9013         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9014                                              dl, MVT::i32));
9015       else
9016         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9017                                              MVT::i32));
9018   }
9019 
9020   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9021   if (isLittleEndian)
9022     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9023                        V2, V1, VPermMask);
9024   else
9025     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9026                        V1, V2, VPermMask);
9027 }
9028 
9029 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9030 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9031 /// information about the intrinsic.
9032 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9033                                  bool &isDot, const PPCSubtarget &Subtarget) {
9034   unsigned IntrinsicID =
9035       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9036   CompareOpc = -1;
9037   isDot = false;
9038   switch (IntrinsicID) {
9039   default:
9040     return false;
9041   // Comparison predicates.
9042   case Intrinsic::ppc_altivec_vcmpbfp_p:
9043     CompareOpc = 966;
9044     isDot = true;
9045     break;
9046   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9047     CompareOpc = 198;
9048     isDot = true;
9049     break;
9050   case Intrinsic::ppc_altivec_vcmpequb_p:
9051     CompareOpc = 6;
9052     isDot = true;
9053     break;
9054   case Intrinsic::ppc_altivec_vcmpequh_p:
9055     CompareOpc = 70;
9056     isDot = true;
9057     break;
9058   case Intrinsic::ppc_altivec_vcmpequw_p:
9059     CompareOpc = 134;
9060     isDot = true;
9061     break;
9062   case Intrinsic::ppc_altivec_vcmpequd_p:
9063     if (Subtarget.hasP8Altivec()) {
9064       CompareOpc = 199;
9065       isDot = true;
9066     } else
9067       return false;
9068     break;
9069   case Intrinsic::ppc_altivec_vcmpneb_p:
9070   case Intrinsic::ppc_altivec_vcmpneh_p:
9071   case Intrinsic::ppc_altivec_vcmpnew_p:
9072   case Intrinsic::ppc_altivec_vcmpnezb_p:
9073   case Intrinsic::ppc_altivec_vcmpnezh_p:
9074   case Intrinsic::ppc_altivec_vcmpnezw_p:
9075     if (Subtarget.hasP9Altivec()) {
9076       switch (IntrinsicID) {
9077       default:
9078         llvm_unreachable("Unknown comparison intrinsic.");
9079       case Intrinsic::ppc_altivec_vcmpneb_p:
9080         CompareOpc = 7;
9081         break;
9082       case Intrinsic::ppc_altivec_vcmpneh_p:
9083         CompareOpc = 71;
9084         break;
9085       case Intrinsic::ppc_altivec_vcmpnew_p:
9086         CompareOpc = 135;
9087         break;
9088       case Intrinsic::ppc_altivec_vcmpnezb_p:
9089         CompareOpc = 263;
9090         break;
9091       case Intrinsic::ppc_altivec_vcmpnezh_p:
9092         CompareOpc = 327;
9093         break;
9094       case Intrinsic::ppc_altivec_vcmpnezw_p:
9095         CompareOpc = 391;
9096         break;
9097       }
9098       isDot = true;
9099     } else
9100       return false;
9101     break;
9102   case Intrinsic::ppc_altivec_vcmpgefp_p:
9103     CompareOpc = 454;
9104     isDot = true;
9105     break;
9106   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9107     CompareOpc = 710;
9108     isDot = true;
9109     break;
9110   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9111     CompareOpc = 774;
9112     isDot = true;
9113     break;
9114   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9115     CompareOpc = 838;
9116     isDot = true;
9117     break;
9118   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9119     CompareOpc = 902;
9120     isDot = true;
9121     break;
9122   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9123     if (Subtarget.hasP8Altivec()) {
9124       CompareOpc = 967;
9125       isDot = true;
9126     } else
9127       return false;
9128     break;
9129   case Intrinsic::ppc_altivec_vcmpgtub_p:
9130     CompareOpc = 518;
9131     isDot = true;
9132     break;
9133   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9134     CompareOpc = 582;
9135     isDot = true;
9136     break;
9137   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9138     CompareOpc = 646;
9139     isDot = true;
9140     break;
9141   case Intrinsic::ppc_altivec_vcmpgtud_p:
9142     if (Subtarget.hasP8Altivec()) {
9143       CompareOpc = 711;
9144       isDot = true;
9145     } else
9146       return false;
9147     break;
9148 
9149   // VSX predicate comparisons use the same infrastructure
9150   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9151   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9152   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9153   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9154   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9155   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9156     if (Subtarget.hasVSX()) {
9157       switch (IntrinsicID) {
9158       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9159         CompareOpc = 99;
9160         break;
9161       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9162         CompareOpc = 115;
9163         break;
9164       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9165         CompareOpc = 107;
9166         break;
9167       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9168         CompareOpc = 67;
9169         break;
9170       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9171         CompareOpc = 83;
9172         break;
9173       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9174         CompareOpc = 75;
9175         break;
9176       }
9177       isDot = true;
9178     } else
9179       return false;
9180     break;
9181 
9182   // Normal Comparisons.
9183   case Intrinsic::ppc_altivec_vcmpbfp:
9184     CompareOpc = 966;
9185     break;
9186   case Intrinsic::ppc_altivec_vcmpeqfp:
9187     CompareOpc = 198;
9188     break;
9189   case Intrinsic::ppc_altivec_vcmpequb:
9190     CompareOpc = 6;
9191     break;
9192   case Intrinsic::ppc_altivec_vcmpequh:
9193     CompareOpc = 70;
9194     break;
9195   case Intrinsic::ppc_altivec_vcmpequw:
9196     CompareOpc = 134;
9197     break;
9198   case Intrinsic::ppc_altivec_vcmpequd:
9199     if (Subtarget.hasP8Altivec())
9200       CompareOpc = 199;
9201     else
9202       return false;
9203     break;
9204   case Intrinsic::ppc_altivec_vcmpneb:
9205   case Intrinsic::ppc_altivec_vcmpneh:
9206   case Intrinsic::ppc_altivec_vcmpnew:
9207   case Intrinsic::ppc_altivec_vcmpnezb:
9208   case Intrinsic::ppc_altivec_vcmpnezh:
9209   case Intrinsic::ppc_altivec_vcmpnezw:
9210     if (Subtarget.hasP9Altivec())
9211       switch (IntrinsicID) {
9212       default:
9213         llvm_unreachable("Unknown comparison intrinsic.");
9214       case Intrinsic::ppc_altivec_vcmpneb:
9215         CompareOpc = 7;
9216         break;
9217       case Intrinsic::ppc_altivec_vcmpneh:
9218         CompareOpc = 71;
9219         break;
9220       case Intrinsic::ppc_altivec_vcmpnew:
9221         CompareOpc = 135;
9222         break;
9223       case Intrinsic::ppc_altivec_vcmpnezb:
9224         CompareOpc = 263;
9225         break;
9226       case Intrinsic::ppc_altivec_vcmpnezh:
9227         CompareOpc = 327;
9228         break;
9229       case Intrinsic::ppc_altivec_vcmpnezw:
9230         CompareOpc = 391;
9231         break;
9232       }
9233     else
9234       return false;
9235     break;
9236   case Intrinsic::ppc_altivec_vcmpgefp:
9237     CompareOpc = 454;
9238     break;
9239   case Intrinsic::ppc_altivec_vcmpgtfp:
9240     CompareOpc = 710;
9241     break;
9242   case Intrinsic::ppc_altivec_vcmpgtsb:
9243     CompareOpc = 774;
9244     break;
9245   case Intrinsic::ppc_altivec_vcmpgtsh:
9246     CompareOpc = 838;
9247     break;
9248   case Intrinsic::ppc_altivec_vcmpgtsw:
9249     CompareOpc = 902;
9250     break;
9251   case Intrinsic::ppc_altivec_vcmpgtsd:
9252     if (Subtarget.hasP8Altivec())
9253       CompareOpc = 967;
9254     else
9255       return false;
9256     break;
9257   case Intrinsic::ppc_altivec_vcmpgtub:
9258     CompareOpc = 518;
9259     break;
9260   case Intrinsic::ppc_altivec_vcmpgtuh:
9261     CompareOpc = 582;
9262     break;
9263   case Intrinsic::ppc_altivec_vcmpgtuw:
9264     CompareOpc = 646;
9265     break;
9266   case Intrinsic::ppc_altivec_vcmpgtud:
9267     if (Subtarget.hasP8Altivec())
9268       CompareOpc = 711;
9269     else
9270       return false;
9271     break;
9272   }
9273   return true;
9274 }
9275 
9276 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9277 /// lower, do it, otherwise return null.
9278 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9279                                                    SelectionDAG &DAG) const {
9280   unsigned IntrinsicID =
9281     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9282 
9283   SDLoc dl(Op);
9284 
9285   if (IntrinsicID == Intrinsic::thread_pointer) {
9286     // Reads the thread pointer register, used for __builtin_thread_pointer.
9287     if (Subtarget.isPPC64())
9288       return DAG.getRegister(PPC::X13, MVT::i64);
9289     return DAG.getRegister(PPC::R2, MVT::i32);
9290   }
9291 
9292   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9293   // opcode number of the comparison.
9294   int CompareOpc;
9295   bool isDot;
9296   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9297     return SDValue();    // Don't custom lower most intrinsics.
9298 
9299   // If this is a non-dot comparison, make the VCMP node and we are done.
9300   if (!isDot) {
9301     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9302                               Op.getOperand(1), Op.getOperand(2),
9303                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9304     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9305   }
9306 
9307   // Create the PPCISD altivec 'dot' comparison node.
9308   SDValue Ops[] = {
9309     Op.getOperand(2),  // LHS
9310     Op.getOperand(3),  // RHS
9311     DAG.getConstant(CompareOpc, dl, MVT::i32)
9312   };
9313   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9314   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9315 
9316   // Now that we have the comparison, emit a copy from the CR to a GPR.
9317   // This is flagged to the above dot comparison.
9318   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9319                                 DAG.getRegister(PPC::CR6, MVT::i32),
9320                                 CompNode.getValue(1));
9321 
9322   // Unpack the result based on how the target uses it.
9323   unsigned BitNo;   // Bit # of CR6.
9324   bool InvertBit;   // Invert result?
9325   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9326   default:  // Can't happen, don't crash on invalid number though.
9327   case 0:   // Return the value of the EQ bit of CR6.
9328     BitNo = 0; InvertBit = false;
9329     break;
9330   case 1:   // Return the inverted value of the EQ bit of CR6.
9331     BitNo = 0; InvertBit = true;
9332     break;
9333   case 2:   // Return the value of the LT bit of CR6.
9334     BitNo = 2; InvertBit = false;
9335     break;
9336   case 3:   // Return the inverted value of the LT bit of CR6.
9337     BitNo = 2; InvertBit = true;
9338     break;
9339   }
9340 
9341   // Shift the bit into the low position.
9342   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9343                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9344   // Isolate the bit.
9345   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9346                       DAG.getConstant(1, dl, MVT::i32));
9347 
9348   // If we are supposed to, toggle the bit.
9349   if (InvertBit)
9350     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9351                         DAG.getConstant(1, dl, MVT::i32));
9352   return Flags;
9353 }
9354 
9355 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9356                                                SelectionDAG &DAG) const {
9357   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9358   // the beginning of the argument list.
9359   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9360   SDLoc DL(Op);
9361   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9362   case Intrinsic::ppc_cfence: {
9363     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9364     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9365     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9366                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9367                                                   Op.getOperand(ArgStart + 1)),
9368                                       Op.getOperand(0)),
9369                    0);
9370   }
9371   default:
9372     break;
9373   }
9374   return SDValue();
9375 }
9376 
9377 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9378   // Check for a DIV with the same operands as this REM.
9379   for (auto UI : Op.getOperand(1)->uses()) {
9380     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9381         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9382       if (UI->getOperand(0) == Op.getOperand(0) &&
9383           UI->getOperand(1) == Op.getOperand(1))
9384         return SDValue();
9385   }
9386   return Op;
9387 }
9388 
9389 // Lower scalar BSWAP64 to xxbrd.
9390 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9391   SDLoc dl(Op);
9392   // MTVSRDD
9393   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9394                    Op.getOperand(0));
9395   // XXBRD
9396   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
9397   // MFVSRD
9398   int VectorIndex = 0;
9399   if (Subtarget.isLittleEndian())
9400     VectorIndex = 1;
9401   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9402                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9403   return Op;
9404 }
9405 
9406 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9407 // compared to a value that is atomically loaded (atomic loads zero-extend).
9408 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9409                                                 SelectionDAG &DAG) const {
9410   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9411          "Expecting an atomic compare-and-swap here.");
9412   SDLoc dl(Op);
9413   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9414   EVT MemVT = AtomicNode->getMemoryVT();
9415   if (MemVT.getSizeInBits() >= 32)
9416     return Op;
9417 
9418   SDValue CmpOp = Op.getOperand(2);
9419   // If this is already correctly zero-extended, leave it alone.
9420   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9421   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9422     return Op;
9423 
9424   // Clear the high bits of the compare operand.
9425   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9426   SDValue NewCmpOp =
9427     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9428                 DAG.getConstant(MaskVal, dl, MVT::i32));
9429 
9430   // Replace the existing compare operand with the properly zero-extended one.
9431   SmallVector<SDValue, 4> Ops;
9432   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9433     Ops.push_back(AtomicNode->getOperand(i));
9434   Ops[2] = NewCmpOp;
9435   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9436   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9437   auto NodeTy =
9438     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9439   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9440 }
9441 
9442 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9443                                                  SelectionDAG &DAG) const {
9444   SDLoc dl(Op);
9445   // Create a stack slot that is 16-byte aligned.
9446   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9447   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9448   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9449   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9450 
9451   // Store the input value into Value#0 of the stack slot.
9452   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9453                                MachinePointerInfo());
9454   // Load it out.
9455   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9456 }
9457 
9458 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9459                                                   SelectionDAG &DAG) const {
9460   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9461          "Should only be called for ISD::INSERT_VECTOR_ELT");
9462 
9463   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9464   // We have legal lowering for constant indices but not for variable ones.
9465   if (!C)
9466     return SDValue();
9467 
9468   EVT VT = Op.getValueType();
9469   SDLoc dl(Op);
9470   SDValue V1 = Op.getOperand(0);
9471   SDValue V2 = Op.getOperand(1);
9472   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9473   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9474     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9475     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9476     unsigned InsertAtElement = C->getZExtValue();
9477     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9478     if (Subtarget.isLittleEndian()) {
9479       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9480     }
9481     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9482                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9483   }
9484   return Op;
9485 }
9486 
9487 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9488                                                    SelectionDAG &DAG) const {
9489   SDLoc dl(Op);
9490   SDNode *N = Op.getNode();
9491 
9492   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9493          "Unknown extract_vector_elt type");
9494 
9495   SDValue Value = N->getOperand(0);
9496 
9497   // The first part of this is like the store lowering except that we don't
9498   // need to track the chain.
9499 
9500   // The values are now known to be -1 (false) or 1 (true). To convert this
9501   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9502   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9503   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9504 
9505   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9506   // understand how to form the extending load.
9507   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9508 
9509   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9510 
9511   // Now convert to an integer and store.
9512   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9513     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9514     Value);
9515 
9516   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9517   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9518   MachinePointerInfo PtrInfo =
9519       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9520   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9521   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9522 
9523   SDValue StoreChain = DAG.getEntryNode();
9524   SDValue Ops[] = {StoreChain,
9525                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9526                    Value, FIdx};
9527   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9528 
9529   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9530     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9531 
9532   // Extract the value requested.
9533   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9534   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9535   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9536 
9537   SDValue IntVal =
9538       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9539 
9540   if (!Subtarget.useCRBits())
9541     return IntVal;
9542 
9543   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9544 }
9545 
9546 /// Lowering for QPX v4i1 loads
9547 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9548                                            SelectionDAG &DAG) const {
9549   SDLoc dl(Op);
9550   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9551   SDValue LoadChain = LN->getChain();
9552   SDValue BasePtr = LN->getBasePtr();
9553 
9554   if (Op.getValueType() == MVT::v4f64 ||
9555       Op.getValueType() == MVT::v4f32) {
9556     EVT MemVT = LN->getMemoryVT();
9557     unsigned Alignment = LN->getAlignment();
9558 
9559     // If this load is properly aligned, then it is legal.
9560     if (Alignment >= MemVT.getStoreSize())
9561       return Op;
9562 
9563     EVT ScalarVT = Op.getValueType().getScalarType(),
9564         ScalarMemVT = MemVT.getScalarType();
9565     unsigned Stride = ScalarMemVT.getStoreSize();
9566 
9567     SDValue Vals[4], LoadChains[4];
9568     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9569       SDValue Load;
9570       if (ScalarVT != ScalarMemVT)
9571         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9572                               BasePtr,
9573                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9574                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9575                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9576       else
9577         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9578                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9579                            MinAlign(Alignment, Idx * Stride),
9580                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9581 
9582       if (Idx == 0 && LN->isIndexed()) {
9583         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9584                "Unknown addressing mode on vector load");
9585         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9586                                   LN->getAddressingMode());
9587       }
9588 
9589       Vals[Idx] = Load;
9590       LoadChains[Idx] = Load.getValue(1);
9591 
9592       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9593                             DAG.getConstant(Stride, dl,
9594                                             BasePtr.getValueType()));
9595     }
9596 
9597     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9598     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9599 
9600     if (LN->isIndexed()) {
9601       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9602       return DAG.getMergeValues(RetOps, dl);
9603     }
9604 
9605     SDValue RetOps[] = { Value, TF };
9606     return DAG.getMergeValues(RetOps, dl);
9607   }
9608 
9609   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9610   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9611 
9612   // To lower v4i1 from a byte array, we load the byte elements of the
9613   // vector and then reuse the BUILD_VECTOR logic.
9614 
9615   SDValue VectElmts[4], VectElmtChains[4];
9616   for (unsigned i = 0; i < 4; ++i) {
9617     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9618     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9619 
9620     VectElmts[i] = DAG.getExtLoad(
9621         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9622         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9623         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9624     VectElmtChains[i] = VectElmts[i].getValue(1);
9625   }
9626 
9627   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9628   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9629 
9630   SDValue RVals[] = { Value, LoadChain };
9631   return DAG.getMergeValues(RVals, dl);
9632 }
9633 
9634 /// Lowering for QPX v4i1 stores
9635 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9636                                             SelectionDAG &DAG) const {
9637   SDLoc dl(Op);
9638   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9639   SDValue StoreChain = SN->getChain();
9640   SDValue BasePtr = SN->getBasePtr();
9641   SDValue Value = SN->getValue();
9642 
9643   if (Value.getValueType() == MVT::v4f64 ||
9644       Value.getValueType() == MVT::v4f32) {
9645     EVT MemVT = SN->getMemoryVT();
9646     unsigned Alignment = SN->getAlignment();
9647 
9648     // If this store is properly aligned, then it is legal.
9649     if (Alignment >= MemVT.getStoreSize())
9650       return Op;
9651 
9652     EVT ScalarVT = Value.getValueType().getScalarType(),
9653         ScalarMemVT = MemVT.getScalarType();
9654     unsigned Stride = ScalarMemVT.getStoreSize();
9655 
9656     SDValue Stores[4];
9657     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9658       SDValue Ex = DAG.getNode(
9659           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9660           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9661       SDValue Store;
9662       if (ScalarVT != ScalarMemVT)
9663         Store =
9664             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9665                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9666                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9667                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9668       else
9669         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9670                              SN->getPointerInfo().getWithOffset(Idx * Stride),
9671                              MinAlign(Alignment, Idx * Stride),
9672                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
9673 
9674       if (Idx == 0 && SN->isIndexed()) {
9675         assert(SN->getAddressingMode() == ISD::PRE_INC &&
9676                "Unknown addressing mode on vector store");
9677         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9678                                     SN->getAddressingMode());
9679       }
9680 
9681       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9682                             DAG.getConstant(Stride, dl,
9683                                             BasePtr.getValueType()));
9684       Stores[Idx] = Store;
9685     }
9686 
9687     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9688 
9689     if (SN->isIndexed()) {
9690       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9691       return DAG.getMergeValues(RetOps, dl);
9692     }
9693 
9694     return TF;
9695   }
9696 
9697   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9698   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9699 
9700   // The values are now known to be -1 (false) or 1 (true). To convert this
9701   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9702   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9703   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9704 
9705   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9706   // understand how to form the extending load.
9707   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9708 
9709   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9710 
9711   // Now convert to an integer and store.
9712   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9713     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9714     Value);
9715 
9716   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9717   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9718   MachinePointerInfo PtrInfo =
9719       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9720   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9721   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9722 
9723   SDValue Ops[] = {StoreChain,
9724                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9725                    Value, FIdx};
9726   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9727 
9728   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9729     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9730 
9731   // Move data into the byte array.
9732   SDValue Loads[4], LoadChains[4];
9733   for (unsigned i = 0; i < 4; ++i) {
9734     unsigned Offset = 4*i;
9735     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9736     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9737 
9738     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9739                            PtrInfo.getWithOffset(Offset));
9740     LoadChains[i] = Loads[i].getValue(1);
9741   }
9742 
9743   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9744 
9745   SDValue Stores[4];
9746   for (unsigned i = 0; i < 4; ++i) {
9747     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9748     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9749 
9750     Stores[i] = DAG.getTruncStore(
9751         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9752         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9753         SN->getAAInfo());
9754   }
9755 
9756   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9757 
9758   return StoreChain;
9759 }
9760 
9761 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9762   SDLoc dl(Op);
9763   if (Op.getValueType() == MVT::v4i32) {
9764     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9765 
9766     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9767     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9768 
9769     SDValue RHSSwap =   // = vrlw RHS, 16
9770       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9771 
9772     // Shrinkify inputs to v8i16.
9773     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9774     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9775     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9776 
9777     // Low parts multiplied together, generating 32-bit results (we ignore the
9778     // top parts).
9779     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9780                                         LHS, RHS, DAG, dl, MVT::v4i32);
9781 
9782     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9783                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9784     // Shift the high parts up 16 bits.
9785     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9786                               Neg16, DAG, dl);
9787     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9788   } else if (Op.getValueType() == MVT::v8i16) {
9789     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9790 
9791     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9792 
9793     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9794                             LHS, RHS, Zero, DAG, dl);
9795   } else if (Op.getValueType() == MVT::v16i8) {
9796     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9797     bool isLittleEndian = Subtarget.isLittleEndian();
9798 
9799     // Multiply the even 8-bit parts, producing 16-bit sums.
9800     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9801                                            LHS, RHS, DAG, dl, MVT::v8i16);
9802     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9803 
9804     // Multiply the odd 8-bit parts, producing 16-bit sums.
9805     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9806                                           LHS, RHS, DAG, dl, MVT::v8i16);
9807     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9808 
9809     // Merge the results together.  Because vmuleub and vmuloub are
9810     // instructions with a big-endian bias, we must reverse the
9811     // element numbering and reverse the meaning of "odd" and "even"
9812     // when generating little endian code.
9813     int Ops[16];
9814     for (unsigned i = 0; i != 8; ++i) {
9815       if (isLittleEndian) {
9816         Ops[i*2  ] = 2*i;
9817         Ops[i*2+1] = 2*i+16;
9818       } else {
9819         Ops[i*2  ] = 2*i+1;
9820         Ops[i*2+1] = 2*i+1+16;
9821       }
9822     }
9823     if (isLittleEndian)
9824       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9825     else
9826       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9827   } else {
9828     llvm_unreachable("Unknown mul to lower!");
9829   }
9830 }
9831 
9832 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
9833 
9834   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
9835 
9836   EVT VT = Op.getValueType();
9837   assert(VT.isVector() &&
9838          "Only set vector abs as custom, scalar abs shouldn't reach here!");
9839   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
9840           VT == MVT::v16i8) &&
9841          "Unexpected vector element type!");
9842   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
9843          "Current subtarget doesn't support smax v2i64!");
9844 
9845   // For vector abs, it can be lowered to:
9846   // abs x
9847   // ==>
9848   // y = -x
9849   // smax(x, y)
9850 
9851   SDLoc dl(Op);
9852   SDValue X = Op.getOperand(0);
9853   SDValue Zero = DAG.getConstant(0, dl, VT);
9854   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
9855 
9856   // SMAX patch https://reviews.llvm.org/D47332
9857   // hasn't landed yet, so use intrinsic first here.
9858   // TODO: Should use SMAX directly once SMAX patch landed
9859   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
9860   if (VT == MVT::v2i64)
9861     BifID = Intrinsic::ppc_altivec_vmaxsd;
9862   else if (VT == MVT::v8i16)
9863     BifID = Intrinsic::ppc_altivec_vmaxsh;
9864   else if (VT == MVT::v16i8)
9865     BifID = Intrinsic::ppc_altivec_vmaxsb;
9866 
9867   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
9868 }
9869 
9870 // Custom lowering for fpext vf32 to v2f64
9871 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
9872 
9873   assert(Op.getOpcode() == ISD::FP_EXTEND &&
9874          "Should only be called for ISD::FP_EXTEND");
9875 
9876   // We only want to custom lower an extend from v2f32 to v2f64.
9877   if (Op.getValueType() != MVT::v2f64 ||
9878       Op.getOperand(0).getValueType() != MVT::v2f32)
9879     return SDValue();
9880 
9881   SDLoc dl(Op);
9882   SDValue Op0 = Op.getOperand(0);
9883 
9884   switch (Op0.getOpcode()) {
9885   default:
9886     return SDValue();
9887   case ISD::FADD:
9888   case ISD::FMUL:
9889   case ISD::FSUB: {
9890     SDValue NewLoad[2];
9891     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
9892       // Ensure both input are loads.
9893       SDValue LdOp = Op0.getOperand(i);
9894       if (LdOp.getOpcode() != ISD::LOAD)
9895         return SDValue();
9896       // Generate new load node.
9897       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
9898       SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() };
9899       NewLoad[i] =
9900         DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl,
9901                                 DAG.getVTList(MVT::v4f32, MVT::Other),
9902                                 LoadOps, LD->getMemoryVT(),
9903                                 LD->getMemOperand());
9904     }
9905     SDValue NewOp = DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32,
9906                               NewLoad[0], NewLoad[1],
9907                               Op0.getNode()->getFlags());
9908     return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewOp);
9909   }
9910   case ISD::LOAD: {
9911     LoadSDNode *LD = cast<LoadSDNode>(Op0);
9912     SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() };
9913     SDValue NewLd =
9914       DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl,
9915                               DAG.getVTList(MVT::v4f32, MVT::Other),
9916                               LoadOps, LD->getMemoryVT(), LD->getMemOperand());
9917     return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewLd);
9918   }
9919   }
9920   llvm_unreachable("ERROR:Should return for all cases within swtich.");
9921 }
9922 
9923 /// LowerOperation - Provide custom lowering hooks for some operations.
9924 ///
9925 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9926   switch (Op.getOpcode()) {
9927   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9928   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9929   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9930   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9931   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9932   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9933   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9934   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
9935   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
9936 
9937   // Variable argument lowering.
9938   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9939   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9940   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9941 
9942   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
9943   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9944   case ISD::GET_DYNAMIC_AREA_OFFSET:
9945     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9946 
9947   // Exception handling lowering.
9948   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
9949   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
9950   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
9951 
9952   case ISD::LOAD:               return LowerLOAD(Op, DAG);
9953   case ISD::STORE:              return LowerSTORE(Op, DAG);
9954   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
9955   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
9956   case ISD::FP_TO_UINT:
9957   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
9958   case ISD::UINT_TO_FP:
9959   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
9960   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9961 
9962   // Lower 64-bit shifts.
9963   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
9964   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
9965   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
9966 
9967   // Vector-related lowering.
9968   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9969   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9970   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9971   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9972   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9973   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9974   case ISD::MUL:                return LowerMUL(Op, DAG);
9975   case ISD::ABS:                return LowerABS(Op, DAG);
9976   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
9977 
9978   // For counter-based loop handling.
9979   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
9980 
9981   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9982 
9983   // Frame & Return address.
9984   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9985   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9986 
9987   case ISD::INTRINSIC_VOID:
9988     return LowerINTRINSIC_VOID(Op, DAG);
9989   case ISD::SREM:
9990   case ISD::UREM:
9991     return LowerREM(Op, DAG);
9992   case ISD::BSWAP:
9993     return LowerBSWAP(Op, DAG);
9994   case ISD::ATOMIC_CMP_SWAP:
9995     return LowerATOMIC_CMP_SWAP(Op, DAG);
9996   }
9997 }
9998 
9999 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10000                                            SmallVectorImpl<SDValue>&Results,
10001                                            SelectionDAG &DAG) const {
10002   SDLoc dl(N);
10003   switch (N->getOpcode()) {
10004   default:
10005     llvm_unreachable("Do not know how to custom type legalize this operation!");
10006   case ISD::READCYCLECOUNTER: {
10007     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10008     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10009 
10010     Results.push_back(RTB);
10011     Results.push_back(RTB.getValue(1));
10012     Results.push_back(RTB.getValue(2));
10013     break;
10014   }
10015   case ISD::INTRINSIC_W_CHAIN: {
10016     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10017         Intrinsic::loop_decrement)
10018       break;
10019 
10020     assert(N->getValueType(0) == MVT::i1 &&
10021            "Unexpected result type for CTR decrement intrinsic");
10022     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10023                                  N->getValueType(0));
10024     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10025     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10026                                  N->getOperand(1));
10027 
10028     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10029     Results.push_back(NewInt.getValue(1));
10030     break;
10031   }
10032   case ISD::VAARG: {
10033     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10034       return;
10035 
10036     EVT VT = N->getValueType(0);
10037 
10038     if (VT == MVT::i64) {
10039       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10040 
10041       Results.push_back(NewNode);
10042       Results.push_back(NewNode.getValue(1));
10043     }
10044     return;
10045   }
10046   case ISD::FP_TO_SINT:
10047   case ISD::FP_TO_UINT:
10048     // LowerFP_TO_INT() can only handle f32 and f64.
10049     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10050       return;
10051     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10052     return;
10053   case ISD::TRUNCATE: {
10054     EVT TrgVT = N->getValueType(0);
10055     EVT OpVT = N->getOperand(0).getValueType();
10056     if (TrgVT.isVector() &&
10057         isOperationCustom(N->getOpcode(), TrgVT) &&
10058         OpVT.getSizeInBits() <= 128 &&
10059         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10060       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10061     return;
10062   }
10063   case ISD::BITCAST:
10064     // Don't handle bitcast here.
10065     return;
10066   }
10067 }
10068 
10069 //===----------------------------------------------------------------------===//
10070 //  Other Lowering Code
10071 //===----------------------------------------------------------------------===//
10072 
10073 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10074   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10075   Function *Func = Intrinsic::getDeclaration(M, Id);
10076   return Builder.CreateCall(Func, {});
10077 }
10078 
10079 // The mappings for emitLeading/TrailingFence is taken from
10080 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10081 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10082                                                  Instruction *Inst,
10083                                                  AtomicOrdering Ord) const {
10084   if (Ord == AtomicOrdering::SequentiallyConsistent)
10085     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10086   if (isReleaseOrStronger(Ord))
10087     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10088   return nullptr;
10089 }
10090 
10091 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10092                                                   Instruction *Inst,
10093                                                   AtomicOrdering Ord) const {
10094   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10095     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10096     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10097     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10098     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10099       return Builder.CreateCall(
10100           Intrinsic::getDeclaration(
10101               Builder.GetInsertBlock()->getParent()->getParent(),
10102               Intrinsic::ppc_cfence, {Inst->getType()}),
10103           {Inst});
10104     // FIXME: Can use isync for rmw operation.
10105     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10106   }
10107   return nullptr;
10108 }
10109 
10110 MachineBasicBlock *
10111 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10112                                     unsigned AtomicSize,
10113                                     unsigned BinOpcode,
10114                                     unsigned CmpOpcode,
10115                                     unsigned CmpPred) const {
10116   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10117   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10118 
10119   auto LoadMnemonic = PPC::LDARX;
10120   auto StoreMnemonic = PPC::STDCX;
10121   switch (AtomicSize) {
10122   default:
10123     llvm_unreachable("Unexpected size of atomic entity");
10124   case 1:
10125     LoadMnemonic = PPC::LBARX;
10126     StoreMnemonic = PPC::STBCX;
10127     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10128     break;
10129   case 2:
10130     LoadMnemonic = PPC::LHARX;
10131     StoreMnemonic = PPC::STHCX;
10132     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10133     break;
10134   case 4:
10135     LoadMnemonic = PPC::LWARX;
10136     StoreMnemonic = PPC::STWCX;
10137     break;
10138   case 8:
10139     LoadMnemonic = PPC::LDARX;
10140     StoreMnemonic = PPC::STDCX;
10141     break;
10142   }
10143 
10144   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10145   MachineFunction *F = BB->getParent();
10146   MachineFunction::iterator It = ++BB->getIterator();
10147 
10148   Register dest = MI.getOperand(0).getReg();
10149   Register ptrA = MI.getOperand(1).getReg();
10150   Register ptrB = MI.getOperand(2).getReg();
10151   Register incr = MI.getOperand(3).getReg();
10152   DebugLoc dl = MI.getDebugLoc();
10153 
10154   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10155   MachineBasicBlock *loop2MBB =
10156     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10157   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10158   F->insert(It, loopMBB);
10159   if (CmpOpcode)
10160     F->insert(It, loop2MBB);
10161   F->insert(It, exitMBB);
10162   exitMBB->splice(exitMBB->begin(), BB,
10163                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10164   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10165 
10166   MachineRegisterInfo &RegInfo = F->getRegInfo();
10167   Register TmpReg = (!BinOpcode) ? incr :
10168     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10169                                            : &PPC::GPRCRegClass);
10170 
10171   //  thisMBB:
10172   //   ...
10173   //   fallthrough --> loopMBB
10174   BB->addSuccessor(loopMBB);
10175 
10176   //  loopMBB:
10177   //   l[wd]arx dest, ptr
10178   //   add r0, dest, incr
10179   //   st[wd]cx. r0, ptr
10180   //   bne- loopMBB
10181   //   fallthrough --> exitMBB
10182 
10183   // For max/min...
10184   //  loopMBB:
10185   //   l[wd]arx dest, ptr
10186   //   cmpl?[wd] incr, dest
10187   //   bgt exitMBB
10188   //  loop2MBB:
10189   //   st[wd]cx. dest, ptr
10190   //   bne- loopMBB
10191   //   fallthrough --> exitMBB
10192 
10193   BB = loopMBB;
10194   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10195     .addReg(ptrA).addReg(ptrB);
10196   if (BinOpcode)
10197     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10198   if (CmpOpcode) {
10199     // Signed comparisons of byte or halfword values must be sign-extended.
10200     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10201       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10202       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10203               ExtReg).addReg(dest);
10204       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10205         .addReg(incr).addReg(ExtReg);
10206     } else
10207       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10208         .addReg(incr).addReg(dest);
10209 
10210     BuildMI(BB, dl, TII->get(PPC::BCC))
10211       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10212     BB->addSuccessor(loop2MBB);
10213     BB->addSuccessor(exitMBB);
10214     BB = loop2MBB;
10215   }
10216   BuildMI(BB, dl, TII->get(StoreMnemonic))
10217     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10218   BuildMI(BB, dl, TII->get(PPC::BCC))
10219     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10220   BB->addSuccessor(loopMBB);
10221   BB->addSuccessor(exitMBB);
10222 
10223   //  exitMBB:
10224   //   ...
10225   BB = exitMBB;
10226   return BB;
10227 }
10228 
10229 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10230     MachineInstr &MI, MachineBasicBlock *BB,
10231     bool is8bit, // operation
10232     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10233   // If we support part-word atomic mnemonics, just use them
10234   if (Subtarget.hasPartwordAtomics())
10235     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10236                             CmpPred);
10237 
10238   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10239   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10240   // In 64 bit mode we have to use 64 bits for addresses, even though the
10241   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10242   // registers without caring whether they're 32 or 64, but here we're
10243   // doing actual arithmetic on the addresses.
10244   bool is64bit = Subtarget.isPPC64();
10245   bool isLittleEndian = Subtarget.isLittleEndian();
10246   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10247 
10248   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10249   MachineFunction *F = BB->getParent();
10250   MachineFunction::iterator It = ++BB->getIterator();
10251 
10252   unsigned dest = MI.getOperand(0).getReg();
10253   unsigned ptrA = MI.getOperand(1).getReg();
10254   unsigned ptrB = MI.getOperand(2).getReg();
10255   unsigned incr = MI.getOperand(3).getReg();
10256   DebugLoc dl = MI.getDebugLoc();
10257 
10258   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10259   MachineBasicBlock *loop2MBB =
10260       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10261   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10262   F->insert(It, loopMBB);
10263   if (CmpOpcode)
10264     F->insert(It, loop2MBB);
10265   F->insert(It, exitMBB);
10266   exitMBB->splice(exitMBB->begin(), BB,
10267                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10268   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10269 
10270   MachineRegisterInfo &RegInfo = F->getRegInfo();
10271   const TargetRegisterClass *RC =
10272       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10273   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10274 
10275   Register PtrReg = RegInfo.createVirtualRegister(RC);
10276   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10277   Register ShiftReg =
10278       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10279   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10280   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10281   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10282   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10283   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10284   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10285   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10286   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10287   Register Ptr1Reg;
10288   Register TmpReg =
10289       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10290 
10291   //  thisMBB:
10292   //   ...
10293   //   fallthrough --> loopMBB
10294   BB->addSuccessor(loopMBB);
10295 
10296   // The 4-byte load must be aligned, while a char or short may be
10297   // anywhere in the word.  Hence all this nasty bookkeeping code.
10298   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10299   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10300   //   xori shift, shift1, 24 [16]
10301   //   rlwinm ptr, ptr1, 0, 0, 29
10302   //   slw incr2, incr, shift
10303   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10304   //   slw mask, mask2, shift
10305   //  loopMBB:
10306   //   lwarx tmpDest, ptr
10307   //   add tmp, tmpDest, incr2
10308   //   andc tmp2, tmpDest, mask
10309   //   and tmp3, tmp, mask
10310   //   or tmp4, tmp3, tmp2
10311   //   stwcx. tmp4, ptr
10312   //   bne- loopMBB
10313   //   fallthrough --> exitMBB
10314   //   srw dest, tmpDest, shift
10315   if (ptrA != ZeroReg) {
10316     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10317     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10318         .addReg(ptrA)
10319         .addReg(ptrB);
10320   } else {
10321     Ptr1Reg = ptrB;
10322   }
10323   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10324   // mode.
10325   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10326       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10327       .addImm(3)
10328       .addImm(27)
10329       .addImm(is8bit ? 28 : 27);
10330   if (!isLittleEndian)
10331     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10332         .addReg(Shift1Reg)
10333         .addImm(is8bit ? 24 : 16);
10334   if (is64bit)
10335     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10336         .addReg(Ptr1Reg)
10337         .addImm(0)
10338         .addImm(61);
10339   else
10340     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10341         .addReg(Ptr1Reg)
10342         .addImm(0)
10343         .addImm(0)
10344         .addImm(29);
10345   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10346   if (is8bit)
10347     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10348   else {
10349     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10350     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10351         .addReg(Mask3Reg)
10352         .addImm(65535);
10353   }
10354   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10355       .addReg(Mask2Reg)
10356       .addReg(ShiftReg);
10357 
10358   BB = loopMBB;
10359   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10360       .addReg(ZeroReg)
10361       .addReg(PtrReg);
10362   if (BinOpcode)
10363     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10364         .addReg(Incr2Reg)
10365         .addReg(TmpDestReg);
10366   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10367       .addReg(TmpDestReg)
10368       .addReg(MaskReg);
10369   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10370   if (CmpOpcode) {
10371     // For unsigned comparisons, we can directly compare the shifted values.
10372     // For signed comparisons we shift and sign extend.
10373     unsigned SReg = RegInfo.createVirtualRegister(GPRC);
10374     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10375         .addReg(TmpDestReg)
10376         .addReg(MaskReg);
10377     unsigned ValueReg = SReg;
10378     unsigned CmpReg = Incr2Reg;
10379     if (CmpOpcode == PPC::CMPW) {
10380       ValueReg = RegInfo.createVirtualRegister(GPRC);
10381       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10382           .addReg(SReg)
10383           .addReg(ShiftReg);
10384       unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC);
10385       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10386           .addReg(ValueReg);
10387       ValueReg = ValueSReg;
10388       CmpReg = incr;
10389     }
10390     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10391         .addReg(CmpReg)
10392         .addReg(ValueReg);
10393     BuildMI(BB, dl, TII->get(PPC::BCC))
10394         .addImm(CmpPred)
10395         .addReg(PPC::CR0)
10396         .addMBB(exitMBB);
10397     BB->addSuccessor(loop2MBB);
10398     BB->addSuccessor(exitMBB);
10399     BB = loop2MBB;
10400   }
10401   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10402   BuildMI(BB, dl, TII->get(PPC::STWCX))
10403       .addReg(Tmp4Reg)
10404       .addReg(ZeroReg)
10405       .addReg(PtrReg);
10406   BuildMI(BB, dl, TII->get(PPC::BCC))
10407       .addImm(PPC::PRED_NE)
10408       .addReg(PPC::CR0)
10409       .addMBB(loopMBB);
10410   BB->addSuccessor(loopMBB);
10411   BB->addSuccessor(exitMBB);
10412 
10413   //  exitMBB:
10414   //   ...
10415   BB = exitMBB;
10416   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10417       .addReg(TmpDestReg)
10418       .addReg(ShiftReg);
10419   return BB;
10420 }
10421 
10422 llvm::MachineBasicBlock *
10423 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10424                                     MachineBasicBlock *MBB) const {
10425   DebugLoc DL = MI.getDebugLoc();
10426   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10427   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10428 
10429   MachineFunction *MF = MBB->getParent();
10430   MachineRegisterInfo &MRI = MF->getRegInfo();
10431 
10432   const BasicBlock *BB = MBB->getBasicBlock();
10433   MachineFunction::iterator I = ++MBB->getIterator();
10434 
10435   unsigned DstReg = MI.getOperand(0).getReg();
10436   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10437   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10438   unsigned mainDstReg = MRI.createVirtualRegister(RC);
10439   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
10440 
10441   MVT PVT = getPointerTy(MF->getDataLayout());
10442   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10443          "Invalid Pointer Size!");
10444   // For v = setjmp(buf), we generate
10445   //
10446   // thisMBB:
10447   //  SjLjSetup mainMBB
10448   //  bl mainMBB
10449   //  v_restore = 1
10450   //  b sinkMBB
10451   //
10452   // mainMBB:
10453   //  buf[LabelOffset] = LR
10454   //  v_main = 0
10455   //
10456   // sinkMBB:
10457   //  v = phi(main, restore)
10458   //
10459 
10460   MachineBasicBlock *thisMBB = MBB;
10461   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10462   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10463   MF->insert(I, mainMBB);
10464   MF->insert(I, sinkMBB);
10465 
10466   MachineInstrBuilder MIB;
10467 
10468   // Transfer the remainder of BB and its successor edges to sinkMBB.
10469   sinkMBB->splice(sinkMBB->begin(), MBB,
10470                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10471   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10472 
10473   // Note that the structure of the jmp_buf used here is not compatible
10474   // with that used by libc, and is not designed to be. Specifically, it
10475   // stores only those 'reserved' registers that LLVM does not otherwise
10476   // understand how to spill. Also, by convention, by the time this
10477   // intrinsic is called, Clang has already stored the frame address in the
10478   // first slot of the buffer and stack address in the third. Following the
10479   // X86 target code, we'll store the jump address in the second slot. We also
10480   // need to save the TOC pointer (R2) to handle jumps between shared
10481   // libraries, and that will be stored in the fourth slot. The thread
10482   // identifier (R13) is not affected.
10483 
10484   // thisMBB:
10485   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10486   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10487   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10488 
10489   // Prepare IP either in reg.
10490   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10491   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
10492   unsigned BufReg = MI.getOperand(1).getReg();
10493 
10494   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
10495     setUsesTOCBasePtr(*MBB->getParent());
10496     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10497               .addReg(PPC::X2)
10498               .addImm(TOCOffset)
10499               .addReg(BufReg)
10500               .cloneMemRefs(MI);
10501   }
10502 
10503   // Naked functions never have a base pointer, and so we use r1. For all
10504   // other functions, this decision must be delayed until during PEI.
10505   unsigned BaseReg;
10506   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10507     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10508   else
10509     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10510 
10511   MIB = BuildMI(*thisMBB, MI, DL,
10512                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10513             .addReg(BaseReg)
10514             .addImm(BPOffset)
10515             .addReg(BufReg)
10516             .cloneMemRefs(MI);
10517 
10518   // Setup
10519   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10520   MIB.addRegMask(TRI->getNoPreservedMask());
10521 
10522   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10523 
10524   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10525           .addMBB(mainMBB);
10526   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10527 
10528   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10529   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10530 
10531   // mainMBB:
10532   //  mainDstReg = 0
10533   MIB =
10534       BuildMI(mainMBB, DL,
10535               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10536 
10537   // Store IP
10538   if (Subtarget.isPPC64()) {
10539     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10540             .addReg(LabelReg)
10541             .addImm(LabelOffset)
10542             .addReg(BufReg);
10543   } else {
10544     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10545             .addReg(LabelReg)
10546             .addImm(LabelOffset)
10547             .addReg(BufReg);
10548   }
10549   MIB.cloneMemRefs(MI);
10550 
10551   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10552   mainMBB->addSuccessor(sinkMBB);
10553 
10554   // sinkMBB:
10555   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10556           TII->get(PPC::PHI), DstReg)
10557     .addReg(mainDstReg).addMBB(mainMBB)
10558     .addReg(restoreDstReg).addMBB(thisMBB);
10559 
10560   MI.eraseFromParent();
10561   return sinkMBB;
10562 }
10563 
10564 MachineBasicBlock *
10565 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10566                                      MachineBasicBlock *MBB) const {
10567   DebugLoc DL = MI.getDebugLoc();
10568   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10569 
10570   MachineFunction *MF = MBB->getParent();
10571   MachineRegisterInfo &MRI = MF->getRegInfo();
10572 
10573   MVT PVT = getPointerTy(MF->getDataLayout());
10574   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10575          "Invalid Pointer Size!");
10576 
10577   const TargetRegisterClass *RC =
10578     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10579   unsigned Tmp = MRI.createVirtualRegister(RC);
10580   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10581   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10582   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10583   unsigned BP =
10584       (PVT == MVT::i64)
10585           ? PPC::X30
10586           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10587                                                               : PPC::R30);
10588 
10589   MachineInstrBuilder MIB;
10590 
10591   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10592   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10593   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10594   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10595 
10596   unsigned BufReg = MI.getOperand(0).getReg();
10597 
10598   // Reload FP (the jumped-to function may not have had a
10599   // frame pointer, and if so, then its r31 will be restored
10600   // as necessary).
10601   if (PVT == MVT::i64) {
10602     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10603             .addImm(0)
10604             .addReg(BufReg);
10605   } else {
10606     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10607             .addImm(0)
10608             .addReg(BufReg);
10609   }
10610   MIB.cloneMemRefs(MI);
10611 
10612   // Reload IP
10613   if (PVT == MVT::i64) {
10614     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10615             .addImm(LabelOffset)
10616             .addReg(BufReg);
10617   } else {
10618     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10619             .addImm(LabelOffset)
10620             .addReg(BufReg);
10621   }
10622   MIB.cloneMemRefs(MI);
10623 
10624   // Reload SP
10625   if (PVT == MVT::i64) {
10626     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10627             .addImm(SPOffset)
10628             .addReg(BufReg);
10629   } else {
10630     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10631             .addImm(SPOffset)
10632             .addReg(BufReg);
10633   }
10634   MIB.cloneMemRefs(MI);
10635 
10636   // Reload BP
10637   if (PVT == MVT::i64) {
10638     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10639             .addImm(BPOffset)
10640             .addReg(BufReg);
10641   } else {
10642     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10643             .addImm(BPOffset)
10644             .addReg(BufReg);
10645   }
10646   MIB.cloneMemRefs(MI);
10647 
10648   // Reload TOC
10649   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
10650     setUsesTOCBasePtr(*MBB->getParent());
10651     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
10652               .addImm(TOCOffset)
10653               .addReg(BufReg)
10654               .cloneMemRefs(MI);
10655   }
10656 
10657   // Jump
10658   BuildMI(*MBB, MI, DL,
10659           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
10660   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
10661 
10662   MI.eraseFromParent();
10663   return MBB;
10664 }
10665 
10666 MachineBasicBlock *
10667 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10668                                                MachineBasicBlock *BB) const {
10669   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
10670       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10671     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
10672         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10673       // Call lowering should have added an r2 operand to indicate a dependence
10674       // on the TOC base pointer value. It can't however, because there is no
10675       // way to mark the dependence as implicit there, and so the stackmap code
10676       // will confuse it with a regular operand. Instead, add the dependence
10677       // here.
10678       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10679     }
10680 
10681     return emitPatchPoint(MI, BB);
10682   }
10683 
10684   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10685       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10686     return emitEHSjLjSetJmp(MI, BB);
10687   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10688              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10689     return emitEHSjLjLongJmp(MI, BB);
10690   }
10691 
10692   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10693 
10694   // To "insert" these instructions we actually have to insert their
10695   // control-flow patterns.
10696   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10697   MachineFunction::iterator It = ++BB->getIterator();
10698 
10699   MachineFunction *F = BB->getParent();
10700 
10701   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10702       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
10703       MI.getOpcode() == PPC::SELECT_I8) {
10704     SmallVector<MachineOperand, 2> Cond;
10705     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10706         MI.getOpcode() == PPC::SELECT_CC_I8)
10707       Cond.push_back(MI.getOperand(4));
10708     else
10709       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10710     Cond.push_back(MI.getOperand(1));
10711 
10712     DebugLoc dl = MI.getDebugLoc();
10713     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10714                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10715   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10716              MI.getOpcode() == PPC::SELECT_CC_I8 ||
10717              MI.getOpcode() == PPC::SELECT_CC_F4 ||
10718              MI.getOpcode() == PPC::SELECT_CC_F8 ||
10719              MI.getOpcode() == PPC::SELECT_CC_F16 ||
10720              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10721              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10722              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10723              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10724              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10725              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10726              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10727              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
10728              MI.getOpcode() == PPC::SELECT_CC_SPE ||
10729              MI.getOpcode() == PPC::SELECT_I4 ||
10730              MI.getOpcode() == PPC::SELECT_I8 ||
10731              MI.getOpcode() == PPC::SELECT_F4 ||
10732              MI.getOpcode() == PPC::SELECT_F8 ||
10733              MI.getOpcode() == PPC::SELECT_F16 ||
10734              MI.getOpcode() == PPC::SELECT_QFRC ||
10735              MI.getOpcode() == PPC::SELECT_QSRC ||
10736              MI.getOpcode() == PPC::SELECT_QBRC ||
10737              MI.getOpcode() == PPC::SELECT_SPE ||
10738              MI.getOpcode() == PPC::SELECT_SPE4 ||
10739              MI.getOpcode() == PPC::SELECT_VRRC ||
10740              MI.getOpcode() == PPC::SELECT_VSFRC ||
10741              MI.getOpcode() == PPC::SELECT_VSSRC ||
10742              MI.getOpcode() == PPC::SELECT_VSRC) {
10743     // The incoming instruction knows the destination vreg to set, the
10744     // condition code register to branch on, the true/false values to
10745     // select between, and a branch opcode to use.
10746 
10747     //  thisMBB:
10748     //  ...
10749     //   TrueVal = ...
10750     //   cmpTY ccX, r1, r2
10751     //   bCC copy1MBB
10752     //   fallthrough --> copy0MBB
10753     MachineBasicBlock *thisMBB = BB;
10754     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10755     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10756     DebugLoc dl = MI.getDebugLoc();
10757     F->insert(It, copy0MBB);
10758     F->insert(It, sinkMBB);
10759 
10760     // Transfer the remainder of BB and its successor edges to sinkMBB.
10761     sinkMBB->splice(sinkMBB->begin(), BB,
10762                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10763     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10764 
10765     // Next, add the true and fallthrough blocks as its successors.
10766     BB->addSuccessor(copy0MBB);
10767     BB->addSuccessor(sinkMBB);
10768 
10769     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10770         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10771         MI.getOpcode() == PPC::SELECT_F16 ||
10772         MI.getOpcode() == PPC::SELECT_SPE4 ||
10773         MI.getOpcode() == PPC::SELECT_SPE ||
10774         MI.getOpcode() == PPC::SELECT_QFRC ||
10775         MI.getOpcode() == PPC::SELECT_QSRC ||
10776         MI.getOpcode() == PPC::SELECT_QBRC ||
10777         MI.getOpcode() == PPC::SELECT_VRRC ||
10778         MI.getOpcode() == PPC::SELECT_VSFRC ||
10779         MI.getOpcode() == PPC::SELECT_VSSRC ||
10780         MI.getOpcode() == PPC::SELECT_VSRC) {
10781       BuildMI(BB, dl, TII->get(PPC::BC))
10782           .addReg(MI.getOperand(1).getReg())
10783           .addMBB(sinkMBB);
10784     } else {
10785       unsigned SelectPred = MI.getOperand(4).getImm();
10786       BuildMI(BB, dl, TII->get(PPC::BCC))
10787           .addImm(SelectPred)
10788           .addReg(MI.getOperand(1).getReg())
10789           .addMBB(sinkMBB);
10790     }
10791 
10792     //  copy0MBB:
10793     //   %FalseValue = ...
10794     //   # fallthrough to sinkMBB
10795     BB = copy0MBB;
10796 
10797     // Update machine-CFG edges
10798     BB->addSuccessor(sinkMBB);
10799 
10800     //  sinkMBB:
10801     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10802     //  ...
10803     BB = sinkMBB;
10804     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10805         .addReg(MI.getOperand(3).getReg())
10806         .addMBB(copy0MBB)
10807         .addReg(MI.getOperand(2).getReg())
10808         .addMBB(thisMBB);
10809   } else if (MI.getOpcode() == PPC::ReadTB) {
10810     // To read the 64-bit time-base register on a 32-bit target, we read the
10811     // two halves. Should the counter have wrapped while it was being read, we
10812     // need to try again.
10813     // ...
10814     // readLoop:
10815     // mfspr Rx,TBU # load from TBU
10816     // mfspr Ry,TB  # load from TB
10817     // mfspr Rz,TBU # load from TBU
10818     // cmpw crX,Rx,Rz # check if 'old'='new'
10819     // bne readLoop   # branch if they're not equal
10820     // ...
10821 
10822     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10823     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10824     DebugLoc dl = MI.getDebugLoc();
10825     F->insert(It, readMBB);
10826     F->insert(It, sinkMBB);
10827 
10828     // Transfer the remainder of BB and its successor edges to sinkMBB.
10829     sinkMBB->splice(sinkMBB->begin(), BB,
10830                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10831     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10832 
10833     BB->addSuccessor(readMBB);
10834     BB = readMBB;
10835 
10836     MachineRegisterInfo &RegInfo = F->getRegInfo();
10837     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10838     unsigned LoReg = MI.getOperand(0).getReg();
10839     unsigned HiReg = MI.getOperand(1).getReg();
10840 
10841     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10842     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10843     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10844 
10845     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10846 
10847     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10848         .addReg(HiReg)
10849         .addReg(ReadAgainReg);
10850     BuildMI(BB, dl, TII->get(PPC::BCC))
10851         .addImm(PPC::PRED_NE)
10852         .addReg(CmpReg)
10853         .addMBB(readMBB);
10854 
10855     BB->addSuccessor(readMBB);
10856     BB->addSuccessor(sinkMBB);
10857   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10858     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10859   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10860     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10861   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10862     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10863   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10864     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10865 
10866   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10867     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10868   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10869     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10870   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10871     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10872   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10873     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10874 
10875   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10876     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10877   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10878     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10879   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10880     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10881   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10882     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10883 
10884   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10885     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10886   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10887     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10888   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10889     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10890   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10891     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10892 
10893   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10894     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10895   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10896     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10897   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10898     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10899   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10900     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10901 
10902   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10903     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10904   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10905     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10906   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10907     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10908   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10909     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10910 
10911   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10912     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10913   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10914     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10915   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10916     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10917   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10918     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10919 
10920   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10921     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10922   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10923     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10924   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10925     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10926   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10927     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10928 
10929   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10930     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10931   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10932     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10933   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10934     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10935   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10936     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10937 
10938   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10939     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10940   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10941     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10942   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10943     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10944   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10945     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10946 
10947   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10948     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10949   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10950     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10951   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10952     BB = EmitAtomicBinary(MI, BB, 4, 0);
10953   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10954     BB = EmitAtomicBinary(MI, BB, 8, 0);
10955   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10956            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10957            (Subtarget.hasPartwordAtomics() &&
10958             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10959            (Subtarget.hasPartwordAtomics() &&
10960             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10961     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10962 
10963     auto LoadMnemonic = PPC::LDARX;
10964     auto StoreMnemonic = PPC::STDCX;
10965     switch (MI.getOpcode()) {
10966     default:
10967       llvm_unreachable("Compare and swap of unknown size");
10968     case PPC::ATOMIC_CMP_SWAP_I8:
10969       LoadMnemonic = PPC::LBARX;
10970       StoreMnemonic = PPC::STBCX;
10971       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10972       break;
10973     case PPC::ATOMIC_CMP_SWAP_I16:
10974       LoadMnemonic = PPC::LHARX;
10975       StoreMnemonic = PPC::STHCX;
10976       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10977       break;
10978     case PPC::ATOMIC_CMP_SWAP_I32:
10979       LoadMnemonic = PPC::LWARX;
10980       StoreMnemonic = PPC::STWCX;
10981       break;
10982     case PPC::ATOMIC_CMP_SWAP_I64:
10983       LoadMnemonic = PPC::LDARX;
10984       StoreMnemonic = PPC::STDCX;
10985       break;
10986     }
10987     unsigned dest = MI.getOperand(0).getReg();
10988     unsigned ptrA = MI.getOperand(1).getReg();
10989     unsigned ptrB = MI.getOperand(2).getReg();
10990     unsigned oldval = MI.getOperand(3).getReg();
10991     unsigned newval = MI.getOperand(4).getReg();
10992     DebugLoc dl = MI.getDebugLoc();
10993 
10994     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10995     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10996     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10997     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10998     F->insert(It, loop1MBB);
10999     F->insert(It, loop2MBB);
11000     F->insert(It, midMBB);
11001     F->insert(It, exitMBB);
11002     exitMBB->splice(exitMBB->begin(), BB,
11003                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11004     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11005 
11006     //  thisMBB:
11007     //   ...
11008     //   fallthrough --> loopMBB
11009     BB->addSuccessor(loop1MBB);
11010 
11011     // loop1MBB:
11012     //   l[bhwd]arx dest, ptr
11013     //   cmp[wd] dest, oldval
11014     //   bne- midMBB
11015     // loop2MBB:
11016     //   st[bhwd]cx. newval, ptr
11017     //   bne- loopMBB
11018     //   b exitBB
11019     // midMBB:
11020     //   st[bhwd]cx. dest, ptr
11021     // exitBB:
11022     BB = loop1MBB;
11023     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11024     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11025         .addReg(oldval)
11026         .addReg(dest);
11027     BuildMI(BB, dl, TII->get(PPC::BCC))
11028         .addImm(PPC::PRED_NE)
11029         .addReg(PPC::CR0)
11030         .addMBB(midMBB);
11031     BB->addSuccessor(loop2MBB);
11032     BB->addSuccessor(midMBB);
11033 
11034     BB = loop2MBB;
11035     BuildMI(BB, dl, TII->get(StoreMnemonic))
11036         .addReg(newval)
11037         .addReg(ptrA)
11038         .addReg(ptrB);
11039     BuildMI(BB, dl, TII->get(PPC::BCC))
11040         .addImm(PPC::PRED_NE)
11041         .addReg(PPC::CR0)
11042         .addMBB(loop1MBB);
11043     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11044     BB->addSuccessor(loop1MBB);
11045     BB->addSuccessor(exitMBB);
11046 
11047     BB = midMBB;
11048     BuildMI(BB, dl, TII->get(StoreMnemonic))
11049         .addReg(dest)
11050         .addReg(ptrA)
11051         .addReg(ptrB);
11052     BB->addSuccessor(exitMBB);
11053 
11054     //  exitMBB:
11055     //   ...
11056     BB = exitMBB;
11057   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11058              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11059     // We must use 64-bit registers for addresses when targeting 64-bit,
11060     // since we're actually doing arithmetic on them.  Other registers
11061     // can be 32-bit.
11062     bool is64bit = Subtarget.isPPC64();
11063     bool isLittleEndian = Subtarget.isLittleEndian();
11064     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11065 
11066     unsigned dest = MI.getOperand(0).getReg();
11067     unsigned ptrA = MI.getOperand(1).getReg();
11068     unsigned ptrB = MI.getOperand(2).getReg();
11069     unsigned oldval = MI.getOperand(3).getReg();
11070     unsigned newval = MI.getOperand(4).getReg();
11071     DebugLoc dl = MI.getDebugLoc();
11072 
11073     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11074     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11075     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11076     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11077     F->insert(It, loop1MBB);
11078     F->insert(It, loop2MBB);
11079     F->insert(It, midMBB);
11080     F->insert(It, exitMBB);
11081     exitMBB->splice(exitMBB->begin(), BB,
11082                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11083     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11084 
11085     MachineRegisterInfo &RegInfo = F->getRegInfo();
11086     const TargetRegisterClass *RC =
11087         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11088     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11089 
11090     Register PtrReg = RegInfo.createVirtualRegister(RC);
11091     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11092     Register ShiftReg =
11093         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11094     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11095     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11096     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11097     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11098     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11099     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11100     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11101     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11102     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11103     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11104     Register Ptr1Reg;
11105     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11106     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11107     //  thisMBB:
11108     //   ...
11109     //   fallthrough --> loopMBB
11110     BB->addSuccessor(loop1MBB);
11111 
11112     // The 4-byte load must be aligned, while a char or short may be
11113     // anywhere in the word.  Hence all this nasty bookkeeping code.
11114     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11115     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11116     //   xori shift, shift1, 24 [16]
11117     //   rlwinm ptr, ptr1, 0, 0, 29
11118     //   slw newval2, newval, shift
11119     //   slw oldval2, oldval,shift
11120     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11121     //   slw mask, mask2, shift
11122     //   and newval3, newval2, mask
11123     //   and oldval3, oldval2, mask
11124     // loop1MBB:
11125     //   lwarx tmpDest, ptr
11126     //   and tmp, tmpDest, mask
11127     //   cmpw tmp, oldval3
11128     //   bne- midMBB
11129     // loop2MBB:
11130     //   andc tmp2, tmpDest, mask
11131     //   or tmp4, tmp2, newval3
11132     //   stwcx. tmp4, ptr
11133     //   bne- loop1MBB
11134     //   b exitBB
11135     // midMBB:
11136     //   stwcx. tmpDest, ptr
11137     // exitBB:
11138     //   srw dest, tmpDest, shift
11139     if (ptrA != ZeroReg) {
11140       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11141       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11142           .addReg(ptrA)
11143           .addReg(ptrB);
11144     } else {
11145       Ptr1Reg = ptrB;
11146     }
11147 
11148     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11149     // mode.
11150     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11151         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11152         .addImm(3)
11153         .addImm(27)
11154         .addImm(is8bit ? 28 : 27);
11155     if (!isLittleEndian)
11156       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11157           .addReg(Shift1Reg)
11158           .addImm(is8bit ? 24 : 16);
11159     if (is64bit)
11160       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11161           .addReg(Ptr1Reg)
11162           .addImm(0)
11163           .addImm(61);
11164     else
11165       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11166           .addReg(Ptr1Reg)
11167           .addImm(0)
11168           .addImm(0)
11169           .addImm(29);
11170     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11171         .addReg(newval)
11172         .addReg(ShiftReg);
11173     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11174         .addReg(oldval)
11175         .addReg(ShiftReg);
11176     if (is8bit)
11177       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11178     else {
11179       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11180       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11181           .addReg(Mask3Reg)
11182           .addImm(65535);
11183     }
11184     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11185         .addReg(Mask2Reg)
11186         .addReg(ShiftReg);
11187     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11188         .addReg(NewVal2Reg)
11189         .addReg(MaskReg);
11190     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11191         .addReg(OldVal2Reg)
11192         .addReg(MaskReg);
11193 
11194     BB = loop1MBB;
11195     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11196         .addReg(ZeroReg)
11197         .addReg(PtrReg);
11198     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11199         .addReg(TmpDestReg)
11200         .addReg(MaskReg);
11201     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11202         .addReg(TmpReg)
11203         .addReg(OldVal3Reg);
11204     BuildMI(BB, dl, TII->get(PPC::BCC))
11205         .addImm(PPC::PRED_NE)
11206         .addReg(PPC::CR0)
11207         .addMBB(midMBB);
11208     BB->addSuccessor(loop2MBB);
11209     BB->addSuccessor(midMBB);
11210 
11211     BB = loop2MBB;
11212     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11213         .addReg(TmpDestReg)
11214         .addReg(MaskReg);
11215     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11216         .addReg(Tmp2Reg)
11217         .addReg(NewVal3Reg);
11218     BuildMI(BB, dl, TII->get(PPC::STWCX))
11219         .addReg(Tmp4Reg)
11220         .addReg(ZeroReg)
11221         .addReg(PtrReg);
11222     BuildMI(BB, dl, TII->get(PPC::BCC))
11223         .addImm(PPC::PRED_NE)
11224         .addReg(PPC::CR0)
11225         .addMBB(loop1MBB);
11226     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11227     BB->addSuccessor(loop1MBB);
11228     BB->addSuccessor(exitMBB);
11229 
11230     BB = midMBB;
11231     BuildMI(BB, dl, TII->get(PPC::STWCX))
11232         .addReg(TmpDestReg)
11233         .addReg(ZeroReg)
11234         .addReg(PtrReg);
11235     BB->addSuccessor(exitMBB);
11236 
11237     //  exitMBB:
11238     //   ...
11239     BB = exitMBB;
11240     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11241         .addReg(TmpReg)
11242         .addReg(ShiftReg);
11243   } else if (MI.getOpcode() == PPC::FADDrtz) {
11244     // This pseudo performs an FADD with rounding mode temporarily forced
11245     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11246     // is not modeled at the SelectionDAG level.
11247     unsigned Dest = MI.getOperand(0).getReg();
11248     unsigned Src1 = MI.getOperand(1).getReg();
11249     unsigned Src2 = MI.getOperand(2).getReg();
11250     DebugLoc dl = MI.getDebugLoc();
11251 
11252     MachineRegisterInfo &RegInfo = F->getRegInfo();
11253     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11254 
11255     // Save FPSCR value.
11256     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11257 
11258     // Set rounding mode to round-to-zero.
11259     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11260     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11261 
11262     // Perform addition.
11263     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11264 
11265     // Restore FPSCR value.
11266     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11267   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11268              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
11269              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11270              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
11271     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11272                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
11273                           ? PPC::ANDIo8
11274                           : PPC::ANDIo;
11275     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11276                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
11277 
11278     MachineRegisterInfo &RegInfo = F->getRegInfo();
11279     unsigned Dest = RegInfo.createVirtualRegister(
11280         Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11281 
11282     DebugLoc dl = MI.getDebugLoc();
11283     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
11284         .addReg(MI.getOperand(1).getReg())
11285         .addImm(1);
11286     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
11287             MI.getOperand(0).getReg())
11288         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
11289   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11290     DebugLoc Dl = MI.getDebugLoc();
11291     MachineRegisterInfo &RegInfo = F->getRegInfo();
11292     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11293     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11294     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11295             MI.getOperand(0).getReg())
11296         .addReg(CRReg);
11297   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11298     DebugLoc Dl = MI.getDebugLoc();
11299     unsigned Imm = MI.getOperand(1).getImm();
11300     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11301     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11302             MI.getOperand(0).getReg())
11303         .addReg(PPC::CR0EQ);
11304   } else if (MI.getOpcode() == PPC::SETRNDi) {
11305     DebugLoc dl = MI.getDebugLoc();
11306     unsigned OldFPSCRReg = MI.getOperand(0).getReg();
11307 
11308     // Save FPSCR value.
11309     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11310 
11311     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11312     // the following settings:
11313     //   00 Round to nearest
11314     //   01 Round to 0
11315     //   10 Round to +inf
11316     //   11 Round to -inf
11317 
11318     // When the operand is immediate, using the two least significant bits of
11319     // the immediate to set the bits 62:63 of FPSCR.
11320     unsigned Mode = MI.getOperand(1).getImm();
11321     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11322       .addImm(31);
11323 
11324     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11325       .addImm(30);
11326   } else if (MI.getOpcode() == PPC::SETRND) {
11327     DebugLoc dl = MI.getDebugLoc();
11328 
11329     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11330     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11331     // If the target doesn't have DirectMove, we should use stack to do the
11332     // conversion, because the target doesn't have the instructions like mtvsrd
11333     // or mfvsrd to do this conversion directly.
11334     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11335       if (Subtarget.hasDirectMove()) {
11336         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11337           .addReg(SrcReg);
11338       } else {
11339         // Use stack to do the register copy.
11340         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11341         MachineRegisterInfo &RegInfo = F->getRegInfo();
11342         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11343         if (RC == &PPC::F8RCRegClass) {
11344           // Copy register from F8RCRegClass to G8RCRegclass.
11345           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11346                  "Unsupported RegClass.");
11347 
11348           StoreOp = PPC::STFD;
11349           LoadOp = PPC::LD;
11350         } else {
11351           // Copy register from G8RCRegClass to F8RCRegclass.
11352           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11353                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11354                  "Unsupported RegClass.");
11355         }
11356 
11357         MachineFrameInfo &MFI = F->getFrameInfo();
11358         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11359 
11360         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11361           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11362           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11363           MFI.getObjectAlignment(FrameIdx));
11364 
11365         // Store the SrcReg into the stack.
11366         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11367           .addReg(SrcReg)
11368           .addImm(0)
11369           .addFrameIndex(FrameIdx)
11370           .addMemOperand(MMOStore);
11371 
11372         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11373           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11374           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11375           MFI.getObjectAlignment(FrameIdx));
11376 
11377         // Load from the stack where SrcReg is stored, and save to DestReg,
11378         // so we have done the RegClass conversion from RegClass::SrcReg to
11379         // RegClass::DestReg.
11380         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11381           .addImm(0)
11382           .addFrameIndex(FrameIdx)
11383           .addMemOperand(MMOLoad);
11384       }
11385     };
11386 
11387     unsigned OldFPSCRReg = MI.getOperand(0).getReg();
11388 
11389     // Save FPSCR value.
11390     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11391 
11392     // When the operand is gprc register, use two least significant bits of the
11393     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11394     //
11395     // copy OldFPSCRTmpReg, OldFPSCRReg
11396     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11397     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11398     // copy NewFPSCRReg, NewFPSCRTmpReg
11399     // mtfsf 255, NewFPSCRReg
11400     MachineOperand SrcOp = MI.getOperand(1);
11401     MachineRegisterInfo &RegInfo = F->getRegInfo();
11402     unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11403 
11404     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11405 
11406     unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11407     unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11408 
11409     // The first operand of INSERT_SUBREG should be a register which has
11410     // subregisters, we only care about its RegClass, so we should use an
11411     // IMPLICIT_DEF register.
11412     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11413     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11414       .addReg(ImDefReg)
11415       .add(SrcOp)
11416       .addImm(1);
11417 
11418     unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11419     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11420       .addReg(OldFPSCRTmpReg)
11421       .addReg(ExtSrcReg)
11422       .addImm(0)
11423       .addImm(62);
11424 
11425     unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11426     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11427 
11428     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11429     // bits of FPSCR.
11430     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11431       .addImm(255)
11432       .addReg(NewFPSCRReg)
11433       .addImm(0)
11434       .addImm(0);
11435   } else {
11436     llvm_unreachable("Unexpected instr type to insert");
11437   }
11438 
11439   MI.eraseFromParent(); // The pseudo instruction is gone now.
11440   return BB;
11441 }
11442 
11443 //===----------------------------------------------------------------------===//
11444 // Target Optimization Hooks
11445 //===----------------------------------------------------------------------===//
11446 
11447 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11448   // For the estimates, convergence is quadratic, so we essentially double the
11449   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11450   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11451   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11452   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11453   if (VT.getScalarType() == MVT::f64)
11454     RefinementSteps++;
11455   return RefinementSteps;
11456 }
11457 
11458 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11459                                            int Enabled, int &RefinementSteps,
11460                                            bool &UseOneConstNR,
11461                                            bool Reciprocal) const {
11462   EVT VT = Operand.getValueType();
11463   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11464       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11465       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11466       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11467       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11468       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11469     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11470       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11471 
11472     // The Newton-Raphson computation with a single constant does not provide
11473     // enough accuracy on some CPUs.
11474     UseOneConstNR = !Subtarget.needsTwoConstNR();
11475     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11476   }
11477   return SDValue();
11478 }
11479 
11480 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11481                                             int Enabled,
11482                                             int &RefinementSteps) const {
11483   EVT VT = Operand.getValueType();
11484   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11485       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11486       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11487       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11488       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11489       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11490     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11491       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11492     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11493   }
11494   return SDValue();
11495 }
11496 
11497 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11498   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11499   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11500   // enabled for division), this functionality is redundant with the default
11501   // combiner logic (once the division -> reciprocal/multiply transformation
11502   // has taken place). As a result, this matters more for older cores than for
11503   // newer ones.
11504 
11505   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11506   // reciprocal if there are two or more FDIVs (for embedded cores with only
11507   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11508   switch (Subtarget.getDarwinDirective()) {
11509   default:
11510     return 3;
11511   case PPC::DIR_440:
11512   case PPC::DIR_A2:
11513   case PPC::DIR_E500:
11514   case PPC::DIR_E500mc:
11515   case PPC::DIR_E5500:
11516     return 2;
11517   }
11518 }
11519 
11520 // isConsecutiveLSLoc needs to work even if all adds have not yet been
11521 // collapsed, and so we need to look through chains of them.
11522 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11523                                      int64_t& Offset, SelectionDAG &DAG) {
11524   if (DAG.isBaseWithConstantOffset(Loc)) {
11525     Base = Loc.getOperand(0);
11526     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11527 
11528     // The base might itself be a base plus an offset, and if so, accumulate
11529     // that as well.
11530     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11531   }
11532 }
11533 
11534 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11535                             unsigned Bytes, int Dist,
11536                             SelectionDAG &DAG) {
11537   if (VT.getSizeInBits() / 8 != Bytes)
11538     return false;
11539 
11540   SDValue BaseLoc = Base->getBasePtr();
11541   if (Loc.getOpcode() == ISD::FrameIndex) {
11542     if (BaseLoc.getOpcode() != ISD::FrameIndex)
11543       return false;
11544     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11545     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
11546     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11547     int FS  = MFI.getObjectSize(FI);
11548     int BFS = MFI.getObjectSize(BFI);
11549     if (FS != BFS || FS != (int)Bytes) return false;
11550     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11551   }
11552 
11553   SDValue Base1 = Loc, Base2 = BaseLoc;
11554   int64_t Offset1 = 0, Offset2 = 0;
11555   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
11556   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
11557   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
11558     return true;
11559 
11560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11561   const GlobalValue *GV1 = nullptr;
11562   const GlobalValue *GV2 = nullptr;
11563   Offset1 = 0;
11564   Offset2 = 0;
11565   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
11566   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
11567   if (isGA1 && isGA2 && GV1 == GV2)
11568     return Offset1 == (Offset2 + Dist*Bytes);
11569   return false;
11570 }
11571 
11572 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
11573 // not enforce equality of the chain operands.
11574 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
11575                             unsigned Bytes, int Dist,
11576                             SelectionDAG &DAG) {
11577   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
11578     EVT VT = LS->getMemoryVT();
11579     SDValue Loc = LS->getBasePtr();
11580     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
11581   }
11582 
11583   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
11584     EVT VT;
11585     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11586     default: return false;
11587     case Intrinsic::ppc_qpx_qvlfd:
11588     case Intrinsic::ppc_qpx_qvlfda:
11589       VT = MVT::v4f64;
11590       break;
11591     case Intrinsic::ppc_qpx_qvlfs:
11592     case Intrinsic::ppc_qpx_qvlfsa:
11593       VT = MVT::v4f32;
11594       break;
11595     case Intrinsic::ppc_qpx_qvlfcd:
11596     case Intrinsic::ppc_qpx_qvlfcda:
11597       VT = MVT::v2f64;
11598       break;
11599     case Intrinsic::ppc_qpx_qvlfcs:
11600     case Intrinsic::ppc_qpx_qvlfcsa:
11601       VT = MVT::v2f32;
11602       break;
11603     case Intrinsic::ppc_qpx_qvlfiwa:
11604     case Intrinsic::ppc_qpx_qvlfiwz:
11605     case Intrinsic::ppc_altivec_lvx:
11606     case Intrinsic::ppc_altivec_lvxl:
11607     case Intrinsic::ppc_vsx_lxvw4x:
11608     case Intrinsic::ppc_vsx_lxvw4x_be:
11609       VT = MVT::v4i32;
11610       break;
11611     case Intrinsic::ppc_vsx_lxvd2x:
11612     case Intrinsic::ppc_vsx_lxvd2x_be:
11613       VT = MVT::v2f64;
11614       break;
11615     case Intrinsic::ppc_altivec_lvebx:
11616       VT = MVT::i8;
11617       break;
11618     case Intrinsic::ppc_altivec_lvehx:
11619       VT = MVT::i16;
11620       break;
11621     case Intrinsic::ppc_altivec_lvewx:
11622       VT = MVT::i32;
11623       break;
11624     }
11625 
11626     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
11627   }
11628 
11629   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
11630     EVT VT;
11631     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11632     default: return false;
11633     case Intrinsic::ppc_qpx_qvstfd:
11634     case Intrinsic::ppc_qpx_qvstfda:
11635       VT = MVT::v4f64;
11636       break;
11637     case Intrinsic::ppc_qpx_qvstfs:
11638     case Intrinsic::ppc_qpx_qvstfsa:
11639       VT = MVT::v4f32;
11640       break;
11641     case Intrinsic::ppc_qpx_qvstfcd:
11642     case Intrinsic::ppc_qpx_qvstfcda:
11643       VT = MVT::v2f64;
11644       break;
11645     case Intrinsic::ppc_qpx_qvstfcs:
11646     case Intrinsic::ppc_qpx_qvstfcsa:
11647       VT = MVT::v2f32;
11648       break;
11649     case Intrinsic::ppc_qpx_qvstfiw:
11650     case Intrinsic::ppc_qpx_qvstfiwa:
11651     case Intrinsic::ppc_altivec_stvx:
11652     case Intrinsic::ppc_altivec_stvxl:
11653     case Intrinsic::ppc_vsx_stxvw4x:
11654       VT = MVT::v4i32;
11655       break;
11656     case Intrinsic::ppc_vsx_stxvd2x:
11657       VT = MVT::v2f64;
11658       break;
11659     case Intrinsic::ppc_vsx_stxvw4x_be:
11660       VT = MVT::v4i32;
11661       break;
11662     case Intrinsic::ppc_vsx_stxvd2x_be:
11663       VT = MVT::v2f64;
11664       break;
11665     case Intrinsic::ppc_altivec_stvebx:
11666       VT = MVT::i8;
11667       break;
11668     case Intrinsic::ppc_altivec_stvehx:
11669       VT = MVT::i16;
11670       break;
11671     case Intrinsic::ppc_altivec_stvewx:
11672       VT = MVT::i32;
11673       break;
11674     }
11675 
11676     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
11677   }
11678 
11679   return false;
11680 }
11681 
11682 // Return true is there is a nearyby consecutive load to the one provided
11683 // (regardless of alignment). We search up and down the chain, looking though
11684 // token factors and other loads (but nothing else). As a result, a true result
11685 // indicates that it is safe to create a new consecutive load adjacent to the
11686 // load provided.
11687 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
11688   SDValue Chain = LD->getChain();
11689   EVT VT = LD->getMemoryVT();
11690 
11691   SmallSet<SDNode *, 16> LoadRoots;
11692   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
11693   SmallSet<SDNode *, 16> Visited;
11694 
11695   // First, search up the chain, branching to follow all token-factor operands.
11696   // If we find a consecutive load, then we're done, otherwise, record all
11697   // nodes just above the top-level loads and token factors.
11698   while (!Queue.empty()) {
11699     SDNode *ChainNext = Queue.pop_back_val();
11700     if (!Visited.insert(ChainNext).second)
11701       continue;
11702 
11703     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
11704       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11705         return true;
11706 
11707       if (!Visited.count(ChainLD->getChain().getNode()))
11708         Queue.push_back(ChainLD->getChain().getNode());
11709     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
11710       for (const SDUse &O : ChainNext->ops())
11711         if (!Visited.count(O.getNode()))
11712           Queue.push_back(O.getNode());
11713     } else
11714       LoadRoots.insert(ChainNext);
11715   }
11716 
11717   // Second, search down the chain, starting from the top-level nodes recorded
11718   // in the first phase. These top-level nodes are the nodes just above all
11719   // loads and token factors. Starting with their uses, recursively look though
11720   // all loads (just the chain uses) and token factors to find a consecutive
11721   // load.
11722   Visited.clear();
11723   Queue.clear();
11724 
11725   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
11726        IE = LoadRoots.end(); I != IE; ++I) {
11727     Queue.push_back(*I);
11728 
11729     while (!Queue.empty()) {
11730       SDNode *LoadRoot = Queue.pop_back_val();
11731       if (!Visited.insert(LoadRoot).second)
11732         continue;
11733 
11734       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
11735         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11736           return true;
11737 
11738       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
11739            UE = LoadRoot->use_end(); UI != UE; ++UI)
11740         if (((isa<MemSDNode>(*UI) &&
11741             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
11742             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
11743           Queue.push_back(*UI);
11744     }
11745   }
11746 
11747   return false;
11748 }
11749 
11750 /// This function is called when we have proved that a SETCC node can be replaced
11751 /// by subtraction (and other supporting instructions) so that the result of
11752 /// comparison is kept in a GPR instead of CR. This function is purely for
11753 /// codegen purposes and has some flags to guide the codegen process.
11754 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
11755                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
11756   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11757 
11758   // Zero extend the operands to the largest legal integer. Originally, they
11759   // must be of a strictly smaller size.
11760   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
11761                          DAG.getConstant(Size, DL, MVT::i32));
11762   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
11763                          DAG.getConstant(Size, DL, MVT::i32));
11764 
11765   // Swap if needed. Depends on the condition code.
11766   if (Swap)
11767     std::swap(Op0, Op1);
11768 
11769   // Subtract extended integers.
11770   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
11771 
11772   // Move the sign bit to the least significant position and zero out the rest.
11773   // Now the least significant bit carries the result of original comparison.
11774   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
11775                              DAG.getConstant(Size - 1, DL, MVT::i32));
11776   auto Final = Shifted;
11777 
11778   // Complement the result if needed. Based on the condition code.
11779   if (Complement)
11780     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
11781                         DAG.getConstant(1, DL, MVT::i64));
11782 
11783   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
11784 }
11785 
11786 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
11787                                                   DAGCombinerInfo &DCI) const {
11788   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11789 
11790   SelectionDAG &DAG = DCI.DAG;
11791   SDLoc DL(N);
11792 
11793   // Size of integers being compared has a critical role in the following
11794   // analysis, so we prefer to do this when all types are legal.
11795   if (!DCI.isAfterLegalizeDAG())
11796     return SDValue();
11797 
11798   // If all users of SETCC extend its value to a legal integer type
11799   // then we replace SETCC with a subtraction
11800   for (SDNode::use_iterator UI = N->use_begin(),
11801        UE = N->use_end(); UI != UE; ++UI) {
11802     if (UI->getOpcode() != ISD::ZERO_EXTEND)
11803       return SDValue();
11804   }
11805 
11806   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11807   auto OpSize = N->getOperand(0).getValueSizeInBits();
11808 
11809   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
11810 
11811   if (OpSize < Size) {
11812     switch (CC) {
11813     default: break;
11814     case ISD::SETULT:
11815       return generateEquivalentSub(N, Size, false, false, DL, DAG);
11816     case ISD::SETULE:
11817       return generateEquivalentSub(N, Size, true, true, DL, DAG);
11818     case ISD::SETUGT:
11819       return generateEquivalentSub(N, Size, false, true, DL, DAG);
11820     case ISD::SETUGE:
11821       return generateEquivalentSub(N, Size, true, false, DL, DAG);
11822     }
11823   }
11824 
11825   return SDValue();
11826 }
11827 
11828 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
11829                                                   DAGCombinerInfo &DCI) const {
11830   SelectionDAG &DAG = DCI.DAG;
11831   SDLoc dl(N);
11832 
11833   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
11834   // If we're tracking CR bits, we need to be careful that we don't have:
11835   //   trunc(binary-ops(zext(x), zext(y)))
11836   // or
11837   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
11838   // such that we're unnecessarily moving things into GPRs when it would be
11839   // better to keep them in CR bits.
11840 
11841   // Note that trunc here can be an actual i1 trunc, or can be the effective
11842   // truncation that comes from a setcc or select_cc.
11843   if (N->getOpcode() == ISD::TRUNCATE &&
11844       N->getValueType(0) != MVT::i1)
11845     return SDValue();
11846 
11847   if (N->getOperand(0).getValueType() != MVT::i32 &&
11848       N->getOperand(0).getValueType() != MVT::i64)
11849     return SDValue();
11850 
11851   if (N->getOpcode() == ISD::SETCC ||
11852       N->getOpcode() == ISD::SELECT_CC) {
11853     // If we're looking at a comparison, then we need to make sure that the
11854     // high bits (all except for the first) don't matter the result.
11855     ISD::CondCode CC =
11856       cast<CondCodeSDNode>(N->getOperand(
11857         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
11858     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
11859 
11860     if (ISD::isSignedIntSetCC(CC)) {
11861       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
11862           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
11863         return SDValue();
11864     } else if (ISD::isUnsignedIntSetCC(CC)) {
11865       if (!DAG.MaskedValueIsZero(N->getOperand(0),
11866                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
11867           !DAG.MaskedValueIsZero(N->getOperand(1),
11868                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
11869         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
11870                                              : SDValue());
11871     } else {
11872       // This is neither a signed nor an unsigned comparison, just make sure
11873       // that the high bits are equal.
11874       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
11875       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
11876 
11877       // We don't really care about what is known about the first bit (if
11878       // anything), so clear it in all masks prior to comparing them.
11879       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
11880       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
11881 
11882       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
11883         return SDValue();
11884     }
11885   }
11886 
11887   // We now know that the higher-order bits are irrelevant, we just need to
11888   // make sure that all of the intermediate operations are bit operations, and
11889   // all inputs are extensions.
11890   if (N->getOperand(0).getOpcode() != ISD::AND &&
11891       N->getOperand(0).getOpcode() != ISD::OR  &&
11892       N->getOperand(0).getOpcode() != ISD::XOR &&
11893       N->getOperand(0).getOpcode() != ISD::SELECT &&
11894       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
11895       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
11896       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
11897       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
11898       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
11899     return SDValue();
11900 
11901   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
11902       N->getOperand(1).getOpcode() != ISD::AND &&
11903       N->getOperand(1).getOpcode() != ISD::OR  &&
11904       N->getOperand(1).getOpcode() != ISD::XOR &&
11905       N->getOperand(1).getOpcode() != ISD::SELECT &&
11906       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
11907       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
11908       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
11909       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
11910       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
11911     return SDValue();
11912 
11913   SmallVector<SDValue, 4> Inputs;
11914   SmallVector<SDValue, 8> BinOps, PromOps;
11915   SmallPtrSet<SDNode *, 16> Visited;
11916 
11917   for (unsigned i = 0; i < 2; ++i) {
11918     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11919           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11920           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11921           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11922         isa<ConstantSDNode>(N->getOperand(i)))
11923       Inputs.push_back(N->getOperand(i));
11924     else
11925       BinOps.push_back(N->getOperand(i));
11926 
11927     if (N->getOpcode() == ISD::TRUNCATE)
11928       break;
11929   }
11930 
11931   // Visit all inputs, collect all binary operations (and, or, xor and
11932   // select) that are all fed by extensions.
11933   while (!BinOps.empty()) {
11934     SDValue BinOp = BinOps.back();
11935     BinOps.pop_back();
11936 
11937     if (!Visited.insert(BinOp.getNode()).second)
11938       continue;
11939 
11940     PromOps.push_back(BinOp);
11941 
11942     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11943       // The condition of the select is not promoted.
11944       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11945         continue;
11946       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11947         continue;
11948 
11949       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11950             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11951             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11952            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11953           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11954         Inputs.push_back(BinOp.getOperand(i));
11955       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11956                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11957                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11958                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11959                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11960                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11961                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11962                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11963                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11964         BinOps.push_back(BinOp.getOperand(i));
11965       } else {
11966         // We have an input that is not an extension or another binary
11967         // operation; we'll abort this transformation.
11968         return SDValue();
11969       }
11970     }
11971   }
11972 
11973   // Make sure that this is a self-contained cluster of operations (which
11974   // is not quite the same thing as saying that everything has only one
11975   // use).
11976   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11977     if (isa<ConstantSDNode>(Inputs[i]))
11978       continue;
11979 
11980     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11981                               UE = Inputs[i].getNode()->use_end();
11982          UI != UE; ++UI) {
11983       SDNode *User = *UI;
11984       if (User != N && !Visited.count(User))
11985         return SDValue();
11986 
11987       // Make sure that we're not going to promote the non-output-value
11988       // operand(s) or SELECT or SELECT_CC.
11989       // FIXME: Although we could sometimes handle this, and it does occur in
11990       // practice that one of the condition inputs to the select is also one of
11991       // the outputs, we currently can't deal with this.
11992       if (User->getOpcode() == ISD::SELECT) {
11993         if (User->getOperand(0) == Inputs[i])
11994           return SDValue();
11995       } else if (User->getOpcode() == ISD::SELECT_CC) {
11996         if (User->getOperand(0) == Inputs[i] ||
11997             User->getOperand(1) == Inputs[i])
11998           return SDValue();
11999       }
12000     }
12001   }
12002 
12003   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12004     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12005                               UE = PromOps[i].getNode()->use_end();
12006          UI != UE; ++UI) {
12007       SDNode *User = *UI;
12008       if (User != N && !Visited.count(User))
12009         return SDValue();
12010 
12011       // Make sure that we're not going to promote the non-output-value
12012       // operand(s) or SELECT or SELECT_CC.
12013       // FIXME: Although we could sometimes handle this, and it does occur in
12014       // practice that one of the condition inputs to the select is also one of
12015       // the outputs, we currently can't deal with this.
12016       if (User->getOpcode() == ISD::SELECT) {
12017         if (User->getOperand(0) == PromOps[i])
12018           return SDValue();
12019       } else if (User->getOpcode() == ISD::SELECT_CC) {
12020         if (User->getOperand(0) == PromOps[i] ||
12021             User->getOperand(1) == PromOps[i])
12022           return SDValue();
12023       }
12024     }
12025   }
12026 
12027   // Replace all inputs with the extension operand.
12028   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12029     // Constants may have users outside the cluster of to-be-promoted nodes,
12030     // and so we need to replace those as we do the promotions.
12031     if (isa<ConstantSDNode>(Inputs[i]))
12032       continue;
12033     else
12034       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12035   }
12036 
12037   std::list<HandleSDNode> PromOpHandles;
12038   for (auto &PromOp : PromOps)
12039     PromOpHandles.emplace_back(PromOp);
12040 
12041   // Replace all operations (these are all the same, but have a different
12042   // (i1) return type). DAG.getNode will validate that the types of
12043   // a binary operator match, so go through the list in reverse so that
12044   // we've likely promoted both operands first. Any intermediate truncations or
12045   // extensions disappear.
12046   while (!PromOpHandles.empty()) {
12047     SDValue PromOp = PromOpHandles.back().getValue();
12048     PromOpHandles.pop_back();
12049 
12050     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12051         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12052         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12053         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12054       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12055           PromOp.getOperand(0).getValueType() != MVT::i1) {
12056         // The operand is not yet ready (see comment below).
12057         PromOpHandles.emplace_front(PromOp);
12058         continue;
12059       }
12060 
12061       SDValue RepValue = PromOp.getOperand(0);
12062       if (isa<ConstantSDNode>(RepValue))
12063         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12064 
12065       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12066       continue;
12067     }
12068 
12069     unsigned C;
12070     switch (PromOp.getOpcode()) {
12071     default:             C = 0; break;
12072     case ISD::SELECT:    C = 1; break;
12073     case ISD::SELECT_CC: C = 2; break;
12074     }
12075 
12076     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12077          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12078         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12079          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12080       // The to-be-promoted operands of this node have not yet been
12081       // promoted (this should be rare because we're going through the
12082       // list backward, but if one of the operands has several users in
12083       // this cluster of to-be-promoted nodes, it is possible).
12084       PromOpHandles.emplace_front(PromOp);
12085       continue;
12086     }
12087 
12088     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12089                                 PromOp.getNode()->op_end());
12090 
12091     // If there are any constant inputs, make sure they're replaced now.
12092     for (unsigned i = 0; i < 2; ++i)
12093       if (isa<ConstantSDNode>(Ops[C+i]))
12094         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12095 
12096     DAG.ReplaceAllUsesOfValueWith(PromOp,
12097       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12098   }
12099 
12100   // Now we're left with the initial truncation itself.
12101   if (N->getOpcode() == ISD::TRUNCATE)
12102     return N->getOperand(0);
12103 
12104   // Otherwise, this is a comparison. The operands to be compared have just
12105   // changed type (to i1), but everything else is the same.
12106   return SDValue(N, 0);
12107 }
12108 
12109 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12110                                                   DAGCombinerInfo &DCI) const {
12111   SelectionDAG &DAG = DCI.DAG;
12112   SDLoc dl(N);
12113 
12114   // If we're tracking CR bits, we need to be careful that we don't have:
12115   //   zext(binary-ops(trunc(x), trunc(y)))
12116   // or
12117   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12118   // such that we're unnecessarily moving things into CR bits that can more
12119   // efficiently stay in GPRs. Note that if we're not certain that the high
12120   // bits are set as required by the final extension, we still may need to do
12121   // some masking to get the proper behavior.
12122 
12123   // This same functionality is important on PPC64 when dealing with
12124   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12125   // the return values of functions. Because it is so similar, it is handled
12126   // here as well.
12127 
12128   if (N->getValueType(0) != MVT::i32 &&
12129       N->getValueType(0) != MVT::i64)
12130     return SDValue();
12131 
12132   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12133         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12134     return SDValue();
12135 
12136   if (N->getOperand(0).getOpcode() != ISD::AND &&
12137       N->getOperand(0).getOpcode() != ISD::OR  &&
12138       N->getOperand(0).getOpcode() != ISD::XOR &&
12139       N->getOperand(0).getOpcode() != ISD::SELECT &&
12140       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12141     return SDValue();
12142 
12143   SmallVector<SDValue, 4> Inputs;
12144   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12145   SmallPtrSet<SDNode *, 16> Visited;
12146 
12147   // Visit all inputs, collect all binary operations (and, or, xor and
12148   // select) that are all fed by truncations.
12149   while (!BinOps.empty()) {
12150     SDValue BinOp = BinOps.back();
12151     BinOps.pop_back();
12152 
12153     if (!Visited.insert(BinOp.getNode()).second)
12154       continue;
12155 
12156     PromOps.push_back(BinOp);
12157 
12158     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12159       // The condition of the select is not promoted.
12160       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12161         continue;
12162       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12163         continue;
12164 
12165       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12166           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12167         Inputs.push_back(BinOp.getOperand(i));
12168       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12169                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12170                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12171                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12172                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12173         BinOps.push_back(BinOp.getOperand(i));
12174       } else {
12175         // We have an input that is not a truncation or another binary
12176         // operation; we'll abort this transformation.
12177         return SDValue();
12178       }
12179     }
12180   }
12181 
12182   // The operands of a select that must be truncated when the select is
12183   // promoted because the operand is actually part of the to-be-promoted set.
12184   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12185 
12186   // Make sure that this is a self-contained cluster of operations (which
12187   // is not quite the same thing as saying that everything has only one
12188   // use).
12189   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12190     if (isa<ConstantSDNode>(Inputs[i]))
12191       continue;
12192 
12193     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12194                               UE = Inputs[i].getNode()->use_end();
12195          UI != UE; ++UI) {
12196       SDNode *User = *UI;
12197       if (User != N && !Visited.count(User))
12198         return SDValue();
12199 
12200       // If we're going to promote the non-output-value operand(s) or SELECT or
12201       // SELECT_CC, record them for truncation.
12202       if (User->getOpcode() == ISD::SELECT) {
12203         if (User->getOperand(0) == Inputs[i])
12204           SelectTruncOp[0].insert(std::make_pair(User,
12205                                     User->getOperand(0).getValueType()));
12206       } else if (User->getOpcode() == ISD::SELECT_CC) {
12207         if (User->getOperand(0) == Inputs[i])
12208           SelectTruncOp[0].insert(std::make_pair(User,
12209                                     User->getOperand(0).getValueType()));
12210         if (User->getOperand(1) == Inputs[i])
12211           SelectTruncOp[1].insert(std::make_pair(User,
12212                                     User->getOperand(1).getValueType()));
12213       }
12214     }
12215   }
12216 
12217   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12218     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12219                               UE = PromOps[i].getNode()->use_end();
12220          UI != UE; ++UI) {
12221       SDNode *User = *UI;
12222       if (User != N && !Visited.count(User))
12223         return SDValue();
12224 
12225       // If we're going to promote the non-output-value operand(s) or SELECT or
12226       // SELECT_CC, record them for truncation.
12227       if (User->getOpcode() == ISD::SELECT) {
12228         if (User->getOperand(0) == PromOps[i])
12229           SelectTruncOp[0].insert(std::make_pair(User,
12230                                     User->getOperand(0).getValueType()));
12231       } else if (User->getOpcode() == ISD::SELECT_CC) {
12232         if (User->getOperand(0) == PromOps[i])
12233           SelectTruncOp[0].insert(std::make_pair(User,
12234                                     User->getOperand(0).getValueType()));
12235         if (User->getOperand(1) == PromOps[i])
12236           SelectTruncOp[1].insert(std::make_pair(User,
12237                                     User->getOperand(1).getValueType()));
12238       }
12239     }
12240   }
12241 
12242   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12243   bool ReallyNeedsExt = false;
12244   if (N->getOpcode() != ISD::ANY_EXTEND) {
12245     // If all of the inputs are not already sign/zero extended, then
12246     // we'll still need to do that at the end.
12247     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12248       if (isa<ConstantSDNode>(Inputs[i]))
12249         continue;
12250 
12251       unsigned OpBits =
12252         Inputs[i].getOperand(0).getValueSizeInBits();
12253       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12254 
12255       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12256            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12257                                   APInt::getHighBitsSet(OpBits,
12258                                                         OpBits-PromBits))) ||
12259           (N->getOpcode() == ISD::SIGN_EXTEND &&
12260            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12261              (OpBits-(PromBits-1)))) {
12262         ReallyNeedsExt = true;
12263         break;
12264       }
12265     }
12266   }
12267 
12268   // Replace all inputs, either with the truncation operand, or a
12269   // truncation or extension to the final output type.
12270   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12271     // Constant inputs need to be replaced with the to-be-promoted nodes that
12272     // use them because they might have users outside of the cluster of
12273     // promoted nodes.
12274     if (isa<ConstantSDNode>(Inputs[i]))
12275       continue;
12276 
12277     SDValue InSrc = Inputs[i].getOperand(0);
12278     if (Inputs[i].getValueType() == N->getValueType(0))
12279       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12280     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12281       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12282         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12283     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12284       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12285         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12286     else
12287       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12288         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12289   }
12290 
12291   std::list<HandleSDNode> PromOpHandles;
12292   for (auto &PromOp : PromOps)
12293     PromOpHandles.emplace_back(PromOp);
12294 
12295   // Replace all operations (these are all the same, but have a different
12296   // (promoted) return type). DAG.getNode will validate that the types of
12297   // a binary operator match, so go through the list in reverse so that
12298   // we've likely promoted both operands first.
12299   while (!PromOpHandles.empty()) {
12300     SDValue PromOp = PromOpHandles.back().getValue();
12301     PromOpHandles.pop_back();
12302 
12303     unsigned C;
12304     switch (PromOp.getOpcode()) {
12305     default:             C = 0; break;
12306     case ISD::SELECT:    C = 1; break;
12307     case ISD::SELECT_CC: C = 2; break;
12308     }
12309 
12310     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12311          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12312         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12313          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12314       // The to-be-promoted operands of this node have not yet been
12315       // promoted (this should be rare because we're going through the
12316       // list backward, but if one of the operands has several users in
12317       // this cluster of to-be-promoted nodes, it is possible).
12318       PromOpHandles.emplace_front(PromOp);
12319       continue;
12320     }
12321 
12322     // For SELECT and SELECT_CC nodes, we do a similar check for any
12323     // to-be-promoted comparison inputs.
12324     if (PromOp.getOpcode() == ISD::SELECT ||
12325         PromOp.getOpcode() == ISD::SELECT_CC) {
12326       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12327            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12328           (SelectTruncOp[1].count(PromOp.getNode()) &&
12329            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12330         PromOpHandles.emplace_front(PromOp);
12331         continue;
12332       }
12333     }
12334 
12335     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12336                                 PromOp.getNode()->op_end());
12337 
12338     // If this node has constant inputs, then they'll need to be promoted here.
12339     for (unsigned i = 0; i < 2; ++i) {
12340       if (!isa<ConstantSDNode>(Ops[C+i]))
12341         continue;
12342       if (Ops[C+i].getValueType() == N->getValueType(0))
12343         continue;
12344 
12345       if (N->getOpcode() == ISD::SIGN_EXTEND)
12346         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12347       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12348         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12349       else
12350         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12351     }
12352 
12353     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12354     // truncate them again to the original value type.
12355     if (PromOp.getOpcode() == ISD::SELECT ||
12356         PromOp.getOpcode() == ISD::SELECT_CC) {
12357       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12358       if (SI0 != SelectTruncOp[0].end())
12359         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12360       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12361       if (SI1 != SelectTruncOp[1].end())
12362         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12363     }
12364 
12365     DAG.ReplaceAllUsesOfValueWith(PromOp,
12366       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12367   }
12368 
12369   // Now we're left with the initial extension itself.
12370   if (!ReallyNeedsExt)
12371     return N->getOperand(0);
12372 
12373   // To zero extend, just mask off everything except for the first bit (in the
12374   // i1 case).
12375   if (N->getOpcode() == ISD::ZERO_EXTEND)
12376     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12377                        DAG.getConstant(APInt::getLowBitsSet(
12378                                          N->getValueSizeInBits(0), PromBits),
12379                                        dl, N->getValueType(0)));
12380 
12381   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12382          "Invalid extension type");
12383   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12384   SDValue ShiftCst =
12385       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12386   return DAG.getNode(
12387       ISD::SRA, dl, N->getValueType(0),
12388       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12389       ShiftCst);
12390 }
12391 
12392 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12393                                         DAGCombinerInfo &DCI) const {
12394   assert(N->getOpcode() == ISD::SETCC &&
12395          "Should be called with a SETCC node");
12396 
12397   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12398   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12399     SDValue LHS = N->getOperand(0);
12400     SDValue RHS = N->getOperand(1);
12401 
12402     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12403     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12404         LHS.hasOneUse())
12405       std::swap(LHS, RHS);
12406 
12407     // x == 0-y --> x+y == 0
12408     // x != 0-y --> x+y != 0
12409     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12410         RHS.hasOneUse()) {
12411       SDLoc DL(N);
12412       SelectionDAG &DAG = DCI.DAG;
12413       EVT VT = N->getValueType(0);
12414       EVT OpVT = LHS.getValueType();
12415       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12416       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12417     }
12418   }
12419 
12420   return DAGCombineTruncBoolExt(N, DCI);
12421 }
12422 
12423 // Is this an extending load from an f32 to an f64?
12424 static bool isFPExtLoad(SDValue Op) {
12425   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12426     return LD->getExtensionType() == ISD::EXTLOAD &&
12427       Op.getValueType() == MVT::f64;
12428   return false;
12429 }
12430 
12431 /// Reduces the number of fp-to-int conversion when building a vector.
12432 ///
12433 /// If this vector is built out of floating to integer conversions,
12434 /// transform it to a vector built out of floating point values followed by a
12435 /// single floating to integer conversion of the vector.
12436 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12437 /// becomes (fptosi (build_vector ($A, $B, ...)))
12438 SDValue PPCTargetLowering::
12439 combineElementTruncationToVectorTruncation(SDNode *N,
12440                                            DAGCombinerInfo &DCI) const {
12441   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12442          "Should be called with a BUILD_VECTOR node");
12443 
12444   SelectionDAG &DAG = DCI.DAG;
12445   SDLoc dl(N);
12446 
12447   SDValue FirstInput = N->getOperand(0);
12448   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12449          "The input operand must be an fp-to-int conversion.");
12450 
12451   // This combine happens after legalization so the fp_to_[su]i nodes are
12452   // already converted to PPCSISD nodes.
12453   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12454   if (FirstConversion == PPCISD::FCTIDZ ||
12455       FirstConversion == PPCISD::FCTIDUZ ||
12456       FirstConversion == PPCISD::FCTIWZ ||
12457       FirstConversion == PPCISD::FCTIWUZ) {
12458     bool IsSplat = true;
12459     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12460       FirstConversion == PPCISD::FCTIWUZ;
12461     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12462     SmallVector<SDValue, 4> Ops;
12463     EVT TargetVT = N->getValueType(0);
12464     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12465       SDValue NextOp = N->getOperand(i);
12466       if (NextOp.getOpcode() != PPCISD::MFVSR)
12467         return SDValue();
12468       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12469       if (NextConversion != FirstConversion)
12470         return SDValue();
12471       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12472       // This is not valid if the input was originally double precision. It is
12473       // also not profitable to do unless this is an extending load in which
12474       // case doing this combine will allow us to combine consecutive loads.
12475       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12476         return SDValue();
12477       if (N->getOperand(i) != FirstInput)
12478         IsSplat = false;
12479     }
12480 
12481     // If this is a splat, we leave it as-is since there will be only a single
12482     // fp-to-int conversion followed by a splat of the integer. This is better
12483     // for 32-bit and smaller ints and neutral for 64-bit ints.
12484     if (IsSplat)
12485       return SDValue();
12486 
12487     // Now that we know we have the right type of node, get its operands
12488     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12489       SDValue In = N->getOperand(i).getOperand(0);
12490       if (Is32Bit) {
12491         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12492         // here, we know that all inputs are extending loads so this is safe).
12493         if (In.isUndef())
12494           Ops.push_back(DAG.getUNDEF(SrcVT));
12495         else {
12496           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12497                                       MVT::f32, In.getOperand(0),
12498                                       DAG.getIntPtrConstant(1, dl));
12499           Ops.push_back(Trunc);
12500         }
12501       } else
12502         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12503     }
12504 
12505     unsigned Opcode;
12506     if (FirstConversion == PPCISD::FCTIDZ ||
12507         FirstConversion == PPCISD::FCTIWZ)
12508       Opcode = ISD::FP_TO_SINT;
12509     else
12510       Opcode = ISD::FP_TO_UINT;
12511 
12512     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12513     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12514     return DAG.getNode(Opcode, dl, TargetVT, BV);
12515   }
12516   return SDValue();
12517 }
12518 
12519 /// Reduce the number of loads when building a vector.
12520 ///
12521 /// Building a vector out of multiple loads can be converted to a load
12522 /// of the vector type if the loads are consecutive. If the loads are
12523 /// consecutive but in descending order, a shuffle is added at the end
12524 /// to reorder the vector.
12525 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12526   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12527          "Should be called with a BUILD_VECTOR node");
12528 
12529   SDLoc dl(N);
12530 
12531   // Return early for non byte-sized type, as they can't be consecutive.
12532   if (!N->getValueType(0).getVectorElementType().isByteSized())
12533     return SDValue();
12534 
12535   bool InputsAreConsecutiveLoads = true;
12536   bool InputsAreReverseConsecutive = true;
12537   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12538   SDValue FirstInput = N->getOperand(0);
12539   bool IsRoundOfExtLoad = false;
12540 
12541   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12542       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12543     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12544     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12545   }
12546   // Not a build vector of (possibly fp_rounded) loads.
12547   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12548       N->getNumOperands() == 1)
12549     return SDValue();
12550 
12551   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12552     // If any inputs are fp_round(extload), they all must be.
12553     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12554       return SDValue();
12555 
12556     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
12557       N->getOperand(i);
12558     if (NextInput.getOpcode() != ISD::LOAD)
12559       return SDValue();
12560 
12561     SDValue PreviousInput =
12562       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
12563     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
12564     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
12565 
12566     // If any inputs are fp_round(extload), they all must be.
12567     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
12568       return SDValue();
12569 
12570     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
12571       InputsAreConsecutiveLoads = false;
12572     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
12573       InputsAreReverseConsecutive = false;
12574 
12575     // Exit early if the loads are neither consecutive nor reverse consecutive.
12576     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
12577       return SDValue();
12578   }
12579 
12580   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
12581          "The loads cannot be both consecutive and reverse consecutive.");
12582 
12583   SDValue FirstLoadOp =
12584     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
12585   SDValue LastLoadOp =
12586     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
12587                        N->getOperand(N->getNumOperands()-1);
12588 
12589   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
12590   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
12591   if (InputsAreConsecutiveLoads) {
12592     assert(LD1 && "Input needs to be a LoadSDNode.");
12593     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
12594                        LD1->getBasePtr(), LD1->getPointerInfo(),
12595                        LD1->getAlignment());
12596   }
12597   if (InputsAreReverseConsecutive) {
12598     assert(LDL && "Input needs to be a LoadSDNode.");
12599     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
12600                                LDL->getBasePtr(), LDL->getPointerInfo(),
12601                                LDL->getAlignment());
12602     SmallVector<int, 16> Ops;
12603     for (int i = N->getNumOperands() - 1; i >= 0; i--)
12604       Ops.push_back(i);
12605 
12606     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
12607                                 DAG.getUNDEF(N->getValueType(0)), Ops);
12608   }
12609   return SDValue();
12610 }
12611 
12612 // This function adds the required vector_shuffle needed to get
12613 // the elements of the vector extract in the correct position
12614 // as specified by the CorrectElems encoding.
12615 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
12616                                       SDValue Input, uint64_t Elems,
12617                                       uint64_t CorrectElems) {
12618   SDLoc dl(N);
12619 
12620   unsigned NumElems = Input.getValueType().getVectorNumElements();
12621   SmallVector<int, 16> ShuffleMask(NumElems, -1);
12622 
12623   // Knowing the element indices being extracted from the original
12624   // vector and the order in which they're being inserted, just put
12625   // them at element indices required for the instruction.
12626   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12627     if (DAG.getDataLayout().isLittleEndian())
12628       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
12629     else
12630       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
12631     CorrectElems = CorrectElems >> 8;
12632     Elems = Elems >> 8;
12633   }
12634 
12635   SDValue Shuffle =
12636       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
12637                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
12638 
12639   EVT Ty = N->getValueType(0);
12640   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
12641   return BV;
12642 }
12643 
12644 // Look for build vector patterns where input operands come from sign
12645 // extended vector_extract elements of specific indices. If the correct indices
12646 // aren't used, add a vector shuffle to fix up the indices and create a new
12647 // PPCISD:SExtVElems node which selects the vector sign extend instructions
12648 // during instruction selection.
12649 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
12650   // This array encodes the indices that the vector sign extend instructions
12651   // extract from when extending from one type to another for both BE and LE.
12652   // The right nibble of each byte corresponds to the LE incides.
12653   // and the left nibble of each byte corresponds to the BE incides.
12654   // For example: 0x3074B8FC  byte->word
12655   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
12656   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
12657   // For example: 0x000070F8  byte->double word
12658   // For LE: the allowed indices are: 0x0,0x8
12659   // For BE: the allowed indices are: 0x7,0xF
12660   uint64_t TargetElems[] = {
12661       0x3074B8FC, // b->w
12662       0x000070F8, // b->d
12663       0x10325476, // h->w
12664       0x00003074, // h->d
12665       0x00001032, // w->d
12666   };
12667 
12668   uint64_t Elems = 0;
12669   int Index;
12670   SDValue Input;
12671 
12672   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
12673     if (!Op)
12674       return false;
12675     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
12676         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
12677       return false;
12678 
12679     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
12680     // of the right width.
12681     SDValue Extract = Op.getOperand(0);
12682     if (Extract.getOpcode() == ISD::ANY_EXTEND)
12683       Extract = Extract.getOperand(0);
12684     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12685       return false;
12686 
12687     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
12688     if (!ExtOp)
12689       return false;
12690 
12691     Index = ExtOp->getZExtValue();
12692     if (Input && Input != Extract.getOperand(0))
12693       return false;
12694 
12695     if (!Input)
12696       Input = Extract.getOperand(0);
12697 
12698     Elems = Elems << 8;
12699     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
12700     Elems |= Index;
12701 
12702     return true;
12703   };
12704 
12705   // If the build vector operands aren't sign extended vector extracts,
12706   // of the same input vector, then return.
12707   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12708     if (!isSExtOfVecExtract(N->getOperand(i))) {
12709       return SDValue();
12710     }
12711   }
12712 
12713   // If the vector extract indicies are not correct, add the appropriate
12714   // vector_shuffle.
12715   int TgtElemArrayIdx;
12716   int InputSize = Input.getValueType().getScalarSizeInBits();
12717   int OutputSize = N->getValueType(0).getScalarSizeInBits();
12718   if (InputSize + OutputSize == 40)
12719     TgtElemArrayIdx = 0;
12720   else if (InputSize + OutputSize == 72)
12721     TgtElemArrayIdx = 1;
12722   else if (InputSize + OutputSize == 48)
12723     TgtElemArrayIdx = 2;
12724   else if (InputSize + OutputSize == 80)
12725     TgtElemArrayIdx = 3;
12726   else if (InputSize + OutputSize == 96)
12727     TgtElemArrayIdx = 4;
12728   else
12729     return SDValue();
12730 
12731   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
12732   CorrectElems = DAG.getDataLayout().isLittleEndian()
12733                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
12734                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
12735   if (Elems != CorrectElems) {
12736     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
12737   }
12738 
12739   // Regular lowering will catch cases where a shuffle is not needed.
12740   return SDValue();
12741 }
12742 
12743 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
12744                                                  DAGCombinerInfo &DCI) const {
12745   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12746          "Should be called with a BUILD_VECTOR node");
12747 
12748   SelectionDAG &DAG = DCI.DAG;
12749   SDLoc dl(N);
12750 
12751   if (!Subtarget.hasVSX())
12752     return SDValue();
12753 
12754   // The target independent DAG combiner will leave a build_vector of
12755   // float-to-int conversions intact. We can generate MUCH better code for
12756   // a float-to-int conversion of a vector of floats.
12757   SDValue FirstInput = N->getOperand(0);
12758   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
12759     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
12760     if (Reduced)
12761       return Reduced;
12762   }
12763 
12764   // If we're building a vector out of consecutive loads, just load that
12765   // vector type.
12766   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
12767   if (Reduced)
12768     return Reduced;
12769 
12770   // If we're building a vector out of extended elements from another vector
12771   // we have P9 vector integer extend instructions. The code assumes legal
12772   // input types (i.e. it can't handle things like v4i16) so do not run before
12773   // legalization.
12774   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
12775     Reduced = combineBVOfVecSExt(N, DAG);
12776     if (Reduced)
12777       return Reduced;
12778   }
12779 
12780 
12781   if (N->getValueType(0) != MVT::v2f64)
12782     return SDValue();
12783 
12784   // Looking for:
12785   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
12786   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
12787       FirstInput.getOpcode() != ISD::UINT_TO_FP)
12788     return SDValue();
12789   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
12790       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
12791     return SDValue();
12792   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
12793     return SDValue();
12794 
12795   SDValue Ext1 = FirstInput.getOperand(0);
12796   SDValue Ext2 = N->getOperand(1).getOperand(0);
12797   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12798      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12799     return SDValue();
12800 
12801   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
12802   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
12803   if (!Ext1Op || !Ext2Op)
12804     return SDValue();
12805   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
12806       Ext1.getOperand(0) != Ext2.getOperand(0))
12807     return SDValue();
12808 
12809   int FirstElem = Ext1Op->getZExtValue();
12810   int SecondElem = Ext2Op->getZExtValue();
12811   int SubvecIdx;
12812   if (FirstElem == 0 && SecondElem == 1)
12813     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
12814   else if (FirstElem == 2 && SecondElem == 3)
12815     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
12816   else
12817     return SDValue();
12818 
12819   SDValue SrcVec = Ext1.getOperand(0);
12820   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
12821     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
12822   return DAG.getNode(NodeType, dl, MVT::v2f64,
12823                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
12824 }
12825 
12826 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
12827                                               DAGCombinerInfo &DCI) const {
12828   assert((N->getOpcode() == ISD::SINT_TO_FP ||
12829           N->getOpcode() == ISD::UINT_TO_FP) &&
12830          "Need an int -> FP conversion node here");
12831 
12832   if (useSoftFloat() || !Subtarget.has64BitSupport())
12833     return SDValue();
12834 
12835   SelectionDAG &DAG = DCI.DAG;
12836   SDLoc dl(N);
12837   SDValue Op(N, 0);
12838 
12839   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
12840   // from the hardware.
12841   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
12842     return SDValue();
12843   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
12844       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
12845     return SDValue();
12846 
12847   SDValue FirstOperand(Op.getOperand(0));
12848   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
12849     (FirstOperand.getValueType() == MVT::i8 ||
12850      FirstOperand.getValueType() == MVT::i16);
12851   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
12852     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
12853     bool DstDouble = Op.getValueType() == MVT::f64;
12854     unsigned ConvOp = Signed ?
12855       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
12856       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
12857     SDValue WidthConst =
12858       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
12859                             dl, false);
12860     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
12861     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
12862     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
12863                                          DAG.getVTList(MVT::f64, MVT::Other),
12864                                          Ops, MVT::i8, LDN->getMemOperand());
12865 
12866     // For signed conversion, we need to sign-extend the value in the VSR
12867     if (Signed) {
12868       SDValue ExtOps[] = { Ld, WidthConst };
12869       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
12870       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
12871     } else
12872       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
12873   }
12874 
12875 
12876   // For i32 intermediate values, unfortunately, the conversion functions
12877   // leave the upper 32 bits of the value are undefined. Within the set of
12878   // scalar instructions, we have no method for zero- or sign-extending the
12879   // value. Thus, we cannot handle i32 intermediate values here.
12880   if (Op.getOperand(0).getValueType() == MVT::i32)
12881     return SDValue();
12882 
12883   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
12884          "UINT_TO_FP is supported only with FPCVT");
12885 
12886   // If we have FCFIDS, then use it when converting to single-precision.
12887   // Otherwise, convert to double-precision and then round.
12888   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12889                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
12890                                                             : PPCISD::FCFIDS)
12891                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
12892                                                             : PPCISD::FCFID);
12893   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12894                   ? MVT::f32
12895                   : MVT::f64;
12896 
12897   // If we're converting from a float, to an int, and back to a float again,
12898   // then we don't need the store/load pair at all.
12899   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
12900        Subtarget.hasFPCVT()) ||
12901       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
12902     SDValue Src = Op.getOperand(0).getOperand(0);
12903     if (Src.getValueType() == MVT::f32) {
12904       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
12905       DCI.AddToWorklist(Src.getNode());
12906     } else if (Src.getValueType() != MVT::f64) {
12907       // Make sure that we don't pick up a ppc_fp128 source value.
12908       return SDValue();
12909     }
12910 
12911     unsigned FCTOp =
12912       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
12913                                                         PPCISD::FCTIDUZ;
12914 
12915     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
12916     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
12917 
12918     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
12919       FP = DAG.getNode(ISD::FP_ROUND, dl,
12920                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
12921       DCI.AddToWorklist(FP.getNode());
12922     }
12923 
12924     return FP;
12925   }
12926 
12927   return SDValue();
12928 }
12929 
12930 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
12931 // builtins) into loads with swaps.
12932 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
12933                                               DAGCombinerInfo &DCI) const {
12934   SelectionDAG &DAG = DCI.DAG;
12935   SDLoc dl(N);
12936   SDValue Chain;
12937   SDValue Base;
12938   MachineMemOperand *MMO;
12939 
12940   switch (N->getOpcode()) {
12941   default:
12942     llvm_unreachable("Unexpected opcode for little endian VSX load");
12943   case ISD::LOAD: {
12944     LoadSDNode *LD = cast<LoadSDNode>(N);
12945     Chain = LD->getChain();
12946     Base = LD->getBasePtr();
12947     MMO = LD->getMemOperand();
12948     // If the MMO suggests this isn't a load of a full vector, leave
12949     // things alone.  For a built-in, we have to make the change for
12950     // correctness, so if there is a size problem that will be a bug.
12951     if (MMO->getSize() < 16)
12952       return SDValue();
12953     break;
12954   }
12955   case ISD::INTRINSIC_W_CHAIN: {
12956     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12957     Chain = Intrin->getChain();
12958     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
12959     // us what we want. Get operand 2 instead.
12960     Base = Intrin->getOperand(2);
12961     MMO = Intrin->getMemOperand();
12962     break;
12963   }
12964   }
12965 
12966   MVT VecTy = N->getValueType(0).getSimpleVT();
12967 
12968   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
12969   // aligned and the type is a vector with elements up to 4 bytes
12970   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12971       && VecTy.getScalarSizeInBits() <= 32 ) {
12972     return SDValue();
12973   }
12974 
12975   SDValue LoadOps[] = { Chain, Base };
12976   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
12977                                          DAG.getVTList(MVT::v2f64, MVT::Other),
12978                                          LoadOps, MVT::v2f64, MMO);
12979 
12980   DCI.AddToWorklist(Load.getNode());
12981   Chain = Load.getValue(1);
12982   SDValue Swap = DAG.getNode(
12983       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
12984   DCI.AddToWorklist(Swap.getNode());
12985 
12986   // Add a bitcast if the resulting load type doesn't match v2f64.
12987   if (VecTy != MVT::v2f64) {
12988     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12989     DCI.AddToWorklist(N.getNode());
12990     // Package {bitcast value, swap's chain} to match Load's shape.
12991     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12992                        N, Swap.getValue(1));
12993   }
12994 
12995   return Swap;
12996 }
12997 
12998 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12999 // builtins) into stores with swaps.
13000 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13001                                                DAGCombinerInfo &DCI) const {
13002   SelectionDAG &DAG = DCI.DAG;
13003   SDLoc dl(N);
13004   SDValue Chain;
13005   SDValue Base;
13006   unsigned SrcOpnd;
13007   MachineMemOperand *MMO;
13008 
13009   switch (N->getOpcode()) {
13010   default:
13011     llvm_unreachable("Unexpected opcode for little endian VSX store");
13012   case ISD::STORE: {
13013     StoreSDNode *ST = cast<StoreSDNode>(N);
13014     Chain = ST->getChain();
13015     Base = ST->getBasePtr();
13016     MMO = ST->getMemOperand();
13017     SrcOpnd = 1;
13018     // If the MMO suggests this isn't a store of a full vector, leave
13019     // things alone.  For a built-in, we have to make the change for
13020     // correctness, so if there is a size problem that will be a bug.
13021     if (MMO->getSize() < 16)
13022       return SDValue();
13023     break;
13024   }
13025   case ISD::INTRINSIC_VOID: {
13026     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13027     Chain = Intrin->getChain();
13028     // Intrin->getBasePtr() oddly does not get what we want.
13029     Base = Intrin->getOperand(3);
13030     MMO = Intrin->getMemOperand();
13031     SrcOpnd = 2;
13032     break;
13033   }
13034   }
13035 
13036   SDValue Src = N->getOperand(SrcOpnd);
13037   MVT VecTy = Src.getValueType().getSimpleVT();
13038 
13039   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13040   // aligned and the type is a vector with elements up to 4 bytes
13041   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13042       && VecTy.getScalarSizeInBits() <= 32 ) {
13043     return SDValue();
13044   }
13045 
13046   // All stores are done as v2f64 and possible bit cast.
13047   if (VecTy != MVT::v2f64) {
13048     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13049     DCI.AddToWorklist(Src.getNode());
13050   }
13051 
13052   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13053                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13054   DCI.AddToWorklist(Swap.getNode());
13055   Chain = Swap.getValue(1);
13056   SDValue StoreOps[] = { Chain, Swap, Base };
13057   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13058                                           DAG.getVTList(MVT::Other),
13059                                           StoreOps, VecTy, MMO);
13060   DCI.AddToWorklist(Store.getNode());
13061   return Store;
13062 }
13063 
13064 // Handle DAG combine for STORE (FP_TO_INT F).
13065 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13066                                                DAGCombinerInfo &DCI) const {
13067 
13068   SelectionDAG &DAG = DCI.DAG;
13069   SDLoc dl(N);
13070   unsigned Opcode = N->getOperand(1).getOpcode();
13071 
13072   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13073          && "Not a FP_TO_INT Instruction!");
13074 
13075   SDValue Val = N->getOperand(1).getOperand(0);
13076   EVT Op1VT = N->getOperand(1).getValueType();
13077   EVT ResVT = Val.getValueType();
13078 
13079   // Floating point types smaller than 32 bits are not legal on Power.
13080   if (ResVT.getScalarSizeInBits() < 32)
13081     return SDValue();
13082 
13083   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13084   bool ValidTypeForStoreFltAsInt =
13085         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13086          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13087 
13088   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13089       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13090     return SDValue();
13091 
13092   // Extend f32 values to f64
13093   if (ResVT.getScalarSizeInBits() == 32) {
13094     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13095     DCI.AddToWorklist(Val.getNode());
13096   }
13097 
13098   // Set signed or unsigned conversion opcode.
13099   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13100                           PPCISD::FP_TO_SINT_IN_VSR :
13101                           PPCISD::FP_TO_UINT_IN_VSR;
13102 
13103   Val = DAG.getNode(ConvOpcode,
13104                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13105   DCI.AddToWorklist(Val.getNode());
13106 
13107   // Set number of bytes being converted.
13108   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13109   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13110                     DAG.getIntPtrConstant(ByteSize, dl, false),
13111                     DAG.getValueType(Op1VT) };
13112 
13113   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13114           DAG.getVTList(MVT::Other), Ops,
13115           cast<StoreSDNode>(N)->getMemoryVT(),
13116           cast<StoreSDNode>(N)->getMemOperand());
13117 
13118   DCI.AddToWorklist(Val.getNode());
13119   return Val;
13120 }
13121 
13122 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13123                                                 LSBaseSDNode *LSBase,
13124                                                 DAGCombinerInfo &DCI) const {
13125   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13126         "Not a reverse memop pattern!");
13127 
13128   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13129     auto Mask = SVN->getMask();
13130     int i = 0;
13131     auto I = Mask.rbegin();
13132     auto E = Mask.rend();
13133 
13134     for (; I != E; ++I) {
13135       if (*I != i)
13136         return false;
13137       i++;
13138     }
13139     return true;
13140   };
13141 
13142   SelectionDAG &DAG = DCI.DAG;
13143   EVT VT = SVN->getValueType(0);
13144 
13145   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13146     return SDValue();
13147 
13148   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13149   // See comment in PPCVSXSwapRemoval.cpp.
13150   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13151   if (!Subtarget.hasP9Vector())
13152     return SDValue();
13153 
13154   if(!IsElementReverse(SVN))
13155     return SDValue();
13156 
13157   if (LSBase->getOpcode() == ISD::LOAD) {
13158     SDLoc dl(SVN);
13159     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13160     return DAG.getMemIntrinsicNode(
13161         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13162         LSBase->getMemoryVT(), LSBase->getMemOperand());
13163   }
13164 
13165   if (LSBase->getOpcode() == ISD::STORE) {
13166     SDLoc dl(LSBase);
13167     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13168                           LSBase->getBasePtr()};
13169     return DAG.getMemIntrinsicNode(
13170         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13171         LSBase->getMemoryVT(), LSBase->getMemOperand());
13172   }
13173 
13174   llvm_unreachable("Expected a load or store node here");
13175 }
13176 
13177 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13178                                              DAGCombinerInfo &DCI) const {
13179   SelectionDAG &DAG = DCI.DAG;
13180   SDLoc dl(N);
13181   switch (N->getOpcode()) {
13182   default: break;
13183   case ISD::ADD:
13184     return combineADD(N, DCI);
13185   case ISD::SHL:
13186     return combineSHL(N, DCI);
13187   case ISD::SRA:
13188     return combineSRA(N, DCI);
13189   case ISD::SRL:
13190     return combineSRL(N, DCI);
13191   case ISD::MUL:
13192     return combineMUL(N, DCI);
13193   case PPCISD::SHL:
13194     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13195         return N->getOperand(0);
13196     break;
13197   case PPCISD::SRL:
13198     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13199         return N->getOperand(0);
13200     break;
13201   case PPCISD::SRA:
13202     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13203       if (C->isNullValue() ||   //  0 >>s V -> 0.
13204           C->isAllOnesValue())    // -1 >>s V -> -1.
13205         return N->getOperand(0);
13206     }
13207     break;
13208   case ISD::SIGN_EXTEND:
13209   case ISD::ZERO_EXTEND:
13210   case ISD::ANY_EXTEND:
13211     return DAGCombineExtBoolTrunc(N, DCI);
13212   case ISD::TRUNCATE:
13213     return combineTRUNCATE(N, DCI);
13214   case ISD::SETCC:
13215     if (SDValue CSCC = combineSetCC(N, DCI))
13216       return CSCC;
13217     LLVM_FALLTHROUGH;
13218   case ISD::SELECT_CC:
13219     return DAGCombineTruncBoolExt(N, DCI);
13220   case ISD::SINT_TO_FP:
13221   case ISD::UINT_TO_FP:
13222     return combineFPToIntToFP(N, DCI);
13223   case ISD::VECTOR_SHUFFLE:
13224     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13225       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13226       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13227     }
13228     break;
13229   case ISD::STORE: {
13230 
13231     EVT Op1VT = N->getOperand(1).getValueType();
13232     unsigned Opcode = N->getOperand(1).getOpcode();
13233 
13234     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13235       SDValue Val= combineStoreFPToInt(N, DCI);
13236       if (Val)
13237         return Val;
13238     }
13239 
13240     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13241       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13242       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13243       if (Val)
13244         return Val;
13245     }
13246 
13247     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13248     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13249         N->getOperand(1).getNode()->hasOneUse() &&
13250         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13251          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13252 
13253       // STBRX can only handle simple types and it makes no sense to store less
13254       // two bytes in byte-reversed order.
13255       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13256       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13257         break;
13258 
13259       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13260       // Do an any-extend to 32-bits if this is a half-word input.
13261       if (BSwapOp.getValueType() == MVT::i16)
13262         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13263 
13264       // If the type of BSWAP operand is wider than stored memory width
13265       // it need to be shifted to the right side before STBRX.
13266       if (Op1VT.bitsGT(mVT)) {
13267         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13268         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13269                               DAG.getConstant(Shift, dl, MVT::i32));
13270         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13271         if (Op1VT == MVT::i64)
13272           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13273       }
13274 
13275       SDValue Ops[] = {
13276         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13277       };
13278       return
13279         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13280                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13281                                 cast<StoreSDNode>(N)->getMemOperand());
13282     }
13283 
13284     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13285     // So it can increase the chance of CSE constant construction.
13286     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13287         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13288       // Need to sign-extended to 64-bits to handle negative values.
13289       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13290       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13291                                     MemVT.getSizeInBits());
13292       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13293 
13294       // DAG.getTruncStore() can't be used here because it doesn't accept
13295       // the general (base + offset) addressing mode.
13296       // So we use UpdateNodeOperands and setTruncatingStore instead.
13297       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13298                              N->getOperand(3));
13299       cast<StoreSDNode>(N)->setTruncatingStore(true);
13300       return SDValue(N, 0);
13301     }
13302 
13303     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13304     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13305     if (Op1VT.isSimple()) {
13306       MVT StoreVT = Op1VT.getSimpleVT();
13307       if (Subtarget.needsSwapsForVSXMemOps() &&
13308           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13309            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13310         return expandVSXStoreForLE(N, DCI);
13311     }
13312     break;
13313   }
13314   case ISD::LOAD: {
13315     LoadSDNode *LD = cast<LoadSDNode>(N);
13316     EVT VT = LD->getValueType(0);
13317 
13318     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13319     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13320     if (VT.isSimple()) {
13321       MVT LoadVT = VT.getSimpleVT();
13322       if (Subtarget.needsSwapsForVSXMemOps() &&
13323           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13324            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13325         return expandVSXLoadForLE(N, DCI);
13326     }
13327 
13328     // We sometimes end up with a 64-bit integer load, from which we extract
13329     // two single-precision floating-point numbers. This happens with
13330     // std::complex<float>, and other similar structures, because of the way we
13331     // canonicalize structure copies. However, if we lack direct moves,
13332     // then the final bitcasts from the extracted integer values to the
13333     // floating-point numbers turn into store/load pairs. Even with direct moves,
13334     // just loading the two floating-point numbers is likely better.
13335     auto ReplaceTwoFloatLoad = [&]() {
13336       if (VT != MVT::i64)
13337         return false;
13338 
13339       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13340           LD->isVolatile())
13341         return false;
13342 
13343       //  We're looking for a sequence like this:
13344       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13345       //      t16: i64 = srl t13, Constant:i32<32>
13346       //    t17: i32 = truncate t16
13347       //  t18: f32 = bitcast t17
13348       //    t19: i32 = truncate t13
13349       //  t20: f32 = bitcast t19
13350 
13351       if (!LD->hasNUsesOfValue(2, 0))
13352         return false;
13353 
13354       auto UI = LD->use_begin();
13355       while (UI.getUse().getResNo() != 0) ++UI;
13356       SDNode *Trunc = *UI++;
13357       while (UI.getUse().getResNo() != 0) ++UI;
13358       SDNode *RightShift = *UI;
13359       if (Trunc->getOpcode() != ISD::TRUNCATE)
13360         std::swap(Trunc, RightShift);
13361 
13362       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13363           Trunc->getValueType(0) != MVT::i32 ||
13364           !Trunc->hasOneUse())
13365         return false;
13366       if (RightShift->getOpcode() != ISD::SRL ||
13367           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13368           RightShift->getConstantOperandVal(1) != 32 ||
13369           !RightShift->hasOneUse())
13370         return false;
13371 
13372       SDNode *Trunc2 = *RightShift->use_begin();
13373       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13374           Trunc2->getValueType(0) != MVT::i32 ||
13375           !Trunc2->hasOneUse())
13376         return false;
13377 
13378       SDNode *Bitcast = *Trunc->use_begin();
13379       SDNode *Bitcast2 = *Trunc2->use_begin();
13380 
13381       if (Bitcast->getOpcode() != ISD::BITCAST ||
13382           Bitcast->getValueType(0) != MVT::f32)
13383         return false;
13384       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13385           Bitcast2->getValueType(0) != MVT::f32)
13386         return false;
13387 
13388       if (Subtarget.isLittleEndian())
13389         std::swap(Bitcast, Bitcast2);
13390 
13391       // Bitcast has the second float (in memory-layout order) and Bitcast2
13392       // has the first one.
13393 
13394       SDValue BasePtr = LD->getBasePtr();
13395       if (LD->isIndexed()) {
13396         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13397                "Non-pre-inc AM on PPC?");
13398         BasePtr =
13399           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13400                       LD->getOffset());
13401       }
13402 
13403       auto MMOFlags =
13404           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13405       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13406                                       LD->getPointerInfo(), LD->getAlignment(),
13407                                       MMOFlags, LD->getAAInfo());
13408       SDValue AddPtr =
13409         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13410                     BasePtr, DAG.getIntPtrConstant(4, dl));
13411       SDValue FloatLoad2 = DAG.getLoad(
13412           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13413           LD->getPointerInfo().getWithOffset(4),
13414           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13415 
13416       if (LD->isIndexed()) {
13417         // Note that DAGCombine should re-form any pre-increment load(s) from
13418         // what is produced here if that makes sense.
13419         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13420       }
13421 
13422       DCI.CombineTo(Bitcast2, FloatLoad);
13423       DCI.CombineTo(Bitcast, FloatLoad2);
13424 
13425       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13426                                     SDValue(FloatLoad2.getNode(), 1));
13427       return true;
13428     };
13429 
13430     if (ReplaceTwoFloatLoad())
13431       return SDValue(N, 0);
13432 
13433     EVT MemVT = LD->getMemoryVT();
13434     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13435     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13436     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13437     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13438     if (LD->isUnindexed() && VT.isVector() &&
13439         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13440           // P8 and later hardware should just use LOAD.
13441           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13442                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13443          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13444           LD->getAlignment() >= ScalarABIAlignment)) &&
13445         LD->getAlignment() < ABIAlignment) {
13446       // This is a type-legal unaligned Altivec or QPX load.
13447       SDValue Chain = LD->getChain();
13448       SDValue Ptr = LD->getBasePtr();
13449       bool isLittleEndian = Subtarget.isLittleEndian();
13450 
13451       // This implements the loading of unaligned vectors as described in
13452       // the venerable Apple Velocity Engine overview. Specifically:
13453       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13454       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13455       //
13456       // The general idea is to expand a sequence of one or more unaligned
13457       // loads into an alignment-based permutation-control instruction (lvsl
13458       // or lvsr), a series of regular vector loads (which always truncate
13459       // their input address to an aligned address), and a series of
13460       // permutations.  The results of these permutations are the requested
13461       // loaded values.  The trick is that the last "extra" load is not taken
13462       // from the address you might suspect (sizeof(vector) bytes after the
13463       // last requested load), but rather sizeof(vector) - 1 bytes after the
13464       // last requested vector. The point of this is to avoid a page fault if
13465       // the base address happened to be aligned. This works because if the
13466       // base address is aligned, then adding less than a full vector length
13467       // will cause the last vector in the sequence to be (re)loaded.
13468       // Otherwise, the next vector will be fetched as you might suspect was
13469       // necessary.
13470 
13471       // We might be able to reuse the permutation generation from
13472       // a different base address offset from this one by an aligned amount.
13473       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13474       // optimization later.
13475       Intrinsic::ID Intr, IntrLD, IntrPerm;
13476       MVT PermCntlTy, PermTy, LDTy;
13477       if (Subtarget.hasAltivec()) {
13478         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13479                                  Intrinsic::ppc_altivec_lvsl;
13480         IntrLD = Intrinsic::ppc_altivec_lvx;
13481         IntrPerm = Intrinsic::ppc_altivec_vperm;
13482         PermCntlTy = MVT::v16i8;
13483         PermTy = MVT::v4i32;
13484         LDTy = MVT::v4i32;
13485       } else {
13486         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13487                                        Intrinsic::ppc_qpx_qvlpcls;
13488         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13489                                        Intrinsic::ppc_qpx_qvlfs;
13490         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13491         PermCntlTy = MVT::v4f64;
13492         PermTy = MVT::v4f64;
13493         LDTy = MemVT.getSimpleVT();
13494       }
13495 
13496       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13497 
13498       // Create the new MMO for the new base load. It is like the original MMO,
13499       // but represents an area in memory almost twice the vector size centered
13500       // on the original address. If the address is unaligned, we might start
13501       // reading up to (sizeof(vector)-1) bytes below the address of the
13502       // original unaligned load.
13503       MachineFunction &MF = DAG.getMachineFunction();
13504       MachineMemOperand *BaseMMO =
13505         MF.getMachineMemOperand(LD->getMemOperand(),
13506                                 -(long)MemVT.getStoreSize()+1,
13507                                 2*MemVT.getStoreSize()-1);
13508 
13509       // Create the new base load.
13510       SDValue LDXIntID =
13511           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13512       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13513       SDValue BaseLoad =
13514         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13515                                 DAG.getVTList(PermTy, MVT::Other),
13516                                 BaseLoadOps, LDTy, BaseMMO);
13517 
13518       // Note that the value of IncOffset (which is provided to the next
13519       // load's pointer info offset value, and thus used to calculate the
13520       // alignment), and the value of IncValue (which is actually used to
13521       // increment the pointer value) are different! This is because we
13522       // require the next load to appear to be aligned, even though it
13523       // is actually offset from the base pointer by a lesser amount.
13524       int IncOffset = VT.getSizeInBits() / 8;
13525       int IncValue = IncOffset;
13526 
13527       // Walk (both up and down) the chain looking for another load at the real
13528       // (aligned) offset (the alignment of the other load does not matter in
13529       // this case). If found, then do not use the offset reduction trick, as
13530       // that will prevent the loads from being later combined (as they would
13531       // otherwise be duplicates).
13532       if (!findConsecutiveLoad(LD, DAG))
13533         --IncValue;
13534 
13535       SDValue Increment =
13536           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13537       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13538 
13539       MachineMemOperand *ExtraMMO =
13540         MF.getMachineMemOperand(LD->getMemOperand(),
13541                                 1, 2*MemVT.getStoreSize()-1);
13542       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13543       SDValue ExtraLoad =
13544         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13545                                 DAG.getVTList(PermTy, MVT::Other),
13546                                 ExtraLoadOps, LDTy, ExtraMMO);
13547 
13548       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13549         BaseLoad.getValue(1), ExtraLoad.getValue(1));
13550 
13551       // Because vperm has a big-endian bias, we must reverse the order
13552       // of the input vectors and complement the permute control vector
13553       // when generating little endian code.  We have already handled the
13554       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13555       // and ExtraLoad here.
13556       SDValue Perm;
13557       if (isLittleEndian)
13558         Perm = BuildIntrinsicOp(IntrPerm,
13559                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
13560       else
13561         Perm = BuildIntrinsicOp(IntrPerm,
13562                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
13563 
13564       if (VT != PermTy)
13565         Perm = Subtarget.hasAltivec() ?
13566                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
13567                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
13568                                DAG.getTargetConstant(1, dl, MVT::i64));
13569                                // second argument is 1 because this rounding
13570                                // is always exact.
13571 
13572       // The output of the permutation is our loaded result, the TokenFactor is
13573       // our new chain.
13574       DCI.CombineTo(N, Perm, TF);
13575       return SDValue(N, 0);
13576     }
13577     }
13578     break;
13579     case ISD::INTRINSIC_WO_CHAIN: {
13580       bool isLittleEndian = Subtarget.isLittleEndian();
13581       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13582       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
13583                                            : Intrinsic::ppc_altivec_lvsl);
13584       if ((IID == Intr ||
13585            IID == Intrinsic::ppc_qpx_qvlpcld  ||
13586            IID == Intrinsic::ppc_qpx_qvlpcls) &&
13587         N->getOperand(1)->getOpcode() == ISD::ADD) {
13588         SDValue Add = N->getOperand(1);
13589 
13590         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
13591                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
13592 
13593         if (DAG.MaskedValueIsZero(Add->getOperand(1),
13594                                   APInt::getAllOnesValue(Bits /* alignment */)
13595                                       .zext(Add.getScalarValueSizeInBits()))) {
13596           SDNode *BasePtr = Add->getOperand(0).getNode();
13597           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13598                                     UE = BasePtr->use_end();
13599                UI != UE; ++UI) {
13600             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13601                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
13602               // We've found another LVSL/LVSR, and this address is an aligned
13603               // multiple of that one. The results will be the same, so use the
13604               // one we've just found instead.
13605 
13606               return SDValue(*UI, 0);
13607             }
13608           }
13609         }
13610 
13611         if (isa<ConstantSDNode>(Add->getOperand(1))) {
13612           SDNode *BasePtr = Add->getOperand(0).getNode();
13613           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13614                UE = BasePtr->use_end(); UI != UE; ++UI) {
13615             if (UI->getOpcode() == ISD::ADD &&
13616                 isa<ConstantSDNode>(UI->getOperand(1)) &&
13617                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
13618                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
13619                 (1ULL << Bits) == 0) {
13620               SDNode *OtherAdd = *UI;
13621               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
13622                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
13623                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13624                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
13625                   return SDValue(*VI, 0);
13626                 }
13627               }
13628             }
13629           }
13630         }
13631       }
13632 
13633       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
13634       // Expose the vabsduw/h/b opportunity for down stream
13635       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
13636           (IID == Intrinsic::ppc_altivec_vmaxsw ||
13637            IID == Intrinsic::ppc_altivec_vmaxsh ||
13638            IID == Intrinsic::ppc_altivec_vmaxsb)) {
13639         SDValue V1 = N->getOperand(1);
13640         SDValue V2 = N->getOperand(2);
13641         if ((V1.getSimpleValueType() == MVT::v4i32 ||
13642              V1.getSimpleValueType() == MVT::v8i16 ||
13643              V1.getSimpleValueType() == MVT::v16i8) &&
13644             V1.getSimpleValueType() == V2.getSimpleValueType()) {
13645           // (0-a, a)
13646           if (V1.getOpcode() == ISD::SUB &&
13647               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
13648               V1.getOperand(1) == V2) {
13649             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
13650           }
13651           // (a, 0-a)
13652           if (V2.getOpcode() == ISD::SUB &&
13653               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
13654               V2.getOperand(1) == V1) {
13655             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13656           }
13657           // (x-y, y-x)
13658           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
13659               V1.getOperand(0) == V2.getOperand(1) &&
13660               V1.getOperand(1) == V2.getOperand(0)) {
13661             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13662           }
13663         }
13664       }
13665     }
13666 
13667     break;
13668   case ISD::INTRINSIC_W_CHAIN:
13669     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13670     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13671     if (Subtarget.needsSwapsForVSXMemOps()) {
13672       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13673       default:
13674         break;
13675       case Intrinsic::ppc_vsx_lxvw4x:
13676       case Intrinsic::ppc_vsx_lxvd2x:
13677         return expandVSXLoadForLE(N, DCI);
13678       }
13679     }
13680     break;
13681   case ISD::INTRINSIC_VOID:
13682     // For little endian, VSX stores require generating xxswapd/stxvd2x.
13683     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13684     if (Subtarget.needsSwapsForVSXMemOps()) {
13685       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13686       default:
13687         break;
13688       case Intrinsic::ppc_vsx_stxvw4x:
13689       case Intrinsic::ppc_vsx_stxvd2x:
13690         return expandVSXStoreForLE(N, DCI);
13691       }
13692     }
13693     break;
13694   case ISD::BSWAP:
13695     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
13696     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
13697         N->getOperand(0).hasOneUse() &&
13698         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
13699          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
13700           N->getValueType(0) == MVT::i64))) {
13701       SDValue Load = N->getOperand(0);
13702       LoadSDNode *LD = cast<LoadSDNode>(Load);
13703       // Create the byte-swapping load.
13704       SDValue Ops[] = {
13705         LD->getChain(),    // Chain
13706         LD->getBasePtr(),  // Ptr
13707         DAG.getValueType(N->getValueType(0)) // VT
13708       };
13709       SDValue BSLoad =
13710         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
13711                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
13712                                               MVT::i64 : MVT::i32, MVT::Other),
13713                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
13714 
13715       // If this is an i16 load, insert the truncate.
13716       SDValue ResVal = BSLoad;
13717       if (N->getValueType(0) == MVT::i16)
13718         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
13719 
13720       // First, combine the bswap away.  This makes the value produced by the
13721       // load dead.
13722       DCI.CombineTo(N, ResVal);
13723 
13724       // Next, combine the load away, we give it a bogus result value but a real
13725       // chain result.  The result value is dead because the bswap is dead.
13726       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
13727 
13728       // Return N so it doesn't get rechecked!
13729       return SDValue(N, 0);
13730     }
13731     break;
13732   case PPCISD::VCMP:
13733     // If a VCMPo node already exists with exactly the same operands as this
13734     // node, use its result instead of this node (VCMPo computes both a CR6 and
13735     // a normal output).
13736     //
13737     if (!N->getOperand(0).hasOneUse() &&
13738         !N->getOperand(1).hasOneUse() &&
13739         !N->getOperand(2).hasOneUse()) {
13740 
13741       // Scan all of the users of the LHS, looking for VCMPo's that match.
13742       SDNode *VCMPoNode = nullptr;
13743 
13744       SDNode *LHSN = N->getOperand(0).getNode();
13745       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
13746            UI != E; ++UI)
13747         if (UI->getOpcode() == PPCISD::VCMPo &&
13748             UI->getOperand(1) == N->getOperand(1) &&
13749             UI->getOperand(2) == N->getOperand(2) &&
13750             UI->getOperand(0) == N->getOperand(0)) {
13751           VCMPoNode = *UI;
13752           break;
13753         }
13754 
13755       // If there is no VCMPo node, or if the flag value has a single use, don't
13756       // transform this.
13757       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
13758         break;
13759 
13760       // Look at the (necessarily single) use of the flag value.  If it has a
13761       // chain, this transformation is more complex.  Note that multiple things
13762       // could use the value result, which we should ignore.
13763       SDNode *FlagUser = nullptr;
13764       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
13765            FlagUser == nullptr; ++UI) {
13766         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
13767         SDNode *User = *UI;
13768         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
13769           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
13770             FlagUser = User;
13771             break;
13772           }
13773         }
13774       }
13775 
13776       // If the user is a MFOCRF instruction, we know this is safe.
13777       // Otherwise we give up for right now.
13778       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
13779         return SDValue(VCMPoNode, 0);
13780     }
13781     break;
13782   case ISD::BRCOND: {
13783     SDValue Cond = N->getOperand(1);
13784     SDValue Target = N->getOperand(2);
13785 
13786     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13787         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
13788           Intrinsic::loop_decrement) {
13789 
13790       // We now need to make the intrinsic dead (it cannot be instruction
13791       // selected).
13792       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
13793       assert(Cond.getNode()->hasOneUse() &&
13794              "Counter decrement has more than one use");
13795 
13796       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
13797                          N->getOperand(0), Target);
13798     }
13799   }
13800   break;
13801   case ISD::BR_CC: {
13802     // If this is a branch on an altivec predicate comparison, lower this so
13803     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
13804     // lowering is done pre-legalize, because the legalizer lowers the predicate
13805     // compare down to code that is difficult to reassemble.
13806     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13807     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
13808 
13809     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
13810     // value. If so, pass-through the AND to get to the intrinsic.
13811     if (LHS.getOpcode() == ISD::AND &&
13812         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13813         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
13814           Intrinsic::loop_decrement &&
13815         isa<ConstantSDNode>(LHS.getOperand(1)) &&
13816         !isNullConstant(LHS.getOperand(1)))
13817       LHS = LHS.getOperand(0);
13818 
13819     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13820         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
13821           Intrinsic::loop_decrement &&
13822         isa<ConstantSDNode>(RHS)) {
13823       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
13824              "Counter decrement comparison is not EQ or NE");
13825 
13826       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13827       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
13828                     (CC == ISD::SETNE && !Val);
13829 
13830       // We now need to make the intrinsic dead (it cannot be instruction
13831       // selected).
13832       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
13833       assert(LHS.getNode()->hasOneUse() &&
13834              "Counter decrement has more than one use");
13835 
13836       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
13837                          N->getOperand(0), N->getOperand(4));
13838     }
13839 
13840     int CompareOpc;
13841     bool isDot;
13842 
13843     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13844         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
13845         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
13846       assert(isDot && "Can't compare against a vector result!");
13847 
13848       // If this is a comparison against something other than 0/1, then we know
13849       // that the condition is never/always true.
13850       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13851       if (Val != 0 && Val != 1) {
13852         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
13853           return N->getOperand(0);
13854         // Always !=, turn it into an unconditional branch.
13855         return DAG.getNode(ISD::BR, dl, MVT::Other,
13856                            N->getOperand(0), N->getOperand(4));
13857       }
13858 
13859       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
13860 
13861       // Create the PPCISD altivec 'dot' comparison node.
13862       SDValue Ops[] = {
13863         LHS.getOperand(2),  // LHS of compare
13864         LHS.getOperand(3),  // RHS of compare
13865         DAG.getConstant(CompareOpc, dl, MVT::i32)
13866       };
13867       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
13868       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
13869 
13870       // Unpack the result based on how the target uses it.
13871       PPC::Predicate CompOpc;
13872       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
13873       default:  // Can't happen, don't crash on invalid number though.
13874       case 0:   // Branch on the value of the EQ bit of CR6.
13875         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
13876         break;
13877       case 1:   // Branch on the inverted value of the EQ bit of CR6.
13878         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
13879         break;
13880       case 2:   // Branch on the value of the LT bit of CR6.
13881         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
13882         break;
13883       case 3:   // Branch on the inverted value of the LT bit of CR6.
13884         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
13885         break;
13886       }
13887 
13888       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
13889                          DAG.getConstant(CompOpc, dl, MVT::i32),
13890                          DAG.getRegister(PPC::CR6, MVT::i32),
13891                          N->getOperand(4), CompNode.getValue(1));
13892     }
13893     break;
13894   }
13895   case ISD::BUILD_VECTOR:
13896     return DAGCombineBuildVector(N, DCI);
13897   case ISD::ABS:
13898     return combineABS(N, DCI);
13899   case ISD::VSELECT:
13900     return combineVSelect(N, DCI);
13901   }
13902 
13903   return SDValue();
13904 }
13905 
13906 SDValue
13907 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
13908                                  SelectionDAG &DAG,
13909                                  SmallVectorImpl<SDNode *> &Created) const {
13910   // fold (sdiv X, pow2)
13911   EVT VT = N->getValueType(0);
13912   if (VT == MVT::i64 && !Subtarget.isPPC64())
13913     return SDValue();
13914   if ((VT != MVT::i32 && VT != MVT::i64) ||
13915       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
13916     return SDValue();
13917 
13918   SDLoc DL(N);
13919   SDValue N0 = N->getOperand(0);
13920 
13921   bool IsNegPow2 = (-Divisor).isPowerOf2();
13922   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
13923   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
13924 
13925   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
13926   Created.push_back(Op.getNode());
13927 
13928   if (IsNegPow2) {
13929     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
13930     Created.push_back(Op.getNode());
13931   }
13932 
13933   return Op;
13934 }
13935 
13936 //===----------------------------------------------------------------------===//
13937 // Inline Assembly Support
13938 //===----------------------------------------------------------------------===//
13939 
13940 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13941                                                       KnownBits &Known,
13942                                                       const APInt &DemandedElts,
13943                                                       const SelectionDAG &DAG,
13944                                                       unsigned Depth) const {
13945   Known.resetAll();
13946   switch (Op.getOpcode()) {
13947   default: break;
13948   case PPCISD::LBRX: {
13949     // lhbrx is known to have the top bits cleared out.
13950     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
13951       Known.Zero = 0xFFFF0000;
13952     break;
13953   }
13954   case ISD::INTRINSIC_WO_CHAIN: {
13955     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
13956     default: break;
13957     case Intrinsic::ppc_altivec_vcmpbfp_p:
13958     case Intrinsic::ppc_altivec_vcmpeqfp_p:
13959     case Intrinsic::ppc_altivec_vcmpequb_p:
13960     case Intrinsic::ppc_altivec_vcmpequh_p:
13961     case Intrinsic::ppc_altivec_vcmpequw_p:
13962     case Intrinsic::ppc_altivec_vcmpequd_p:
13963     case Intrinsic::ppc_altivec_vcmpgefp_p:
13964     case Intrinsic::ppc_altivec_vcmpgtfp_p:
13965     case Intrinsic::ppc_altivec_vcmpgtsb_p:
13966     case Intrinsic::ppc_altivec_vcmpgtsh_p:
13967     case Intrinsic::ppc_altivec_vcmpgtsw_p:
13968     case Intrinsic::ppc_altivec_vcmpgtsd_p:
13969     case Intrinsic::ppc_altivec_vcmpgtub_p:
13970     case Intrinsic::ppc_altivec_vcmpgtuh_p:
13971     case Intrinsic::ppc_altivec_vcmpgtuw_p:
13972     case Intrinsic::ppc_altivec_vcmpgtud_p:
13973       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
13974       break;
13975     }
13976   }
13977   }
13978 }
13979 
13980 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
13981   switch (Subtarget.getDarwinDirective()) {
13982   default: break;
13983   case PPC::DIR_970:
13984   case PPC::DIR_PWR4:
13985   case PPC::DIR_PWR5:
13986   case PPC::DIR_PWR5X:
13987   case PPC::DIR_PWR6:
13988   case PPC::DIR_PWR6X:
13989   case PPC::DIR_PWR7:
13990   case PPC::DIR_PWR8:
13991   case PPC::DIR_PWR9: {
13992     if (!ML)
13993       break;
13994 
13995     if (!DisableInnermostLoopAlign32) {
13996       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
13997       // so that we can decrease cache misses and branch-prediction misses.
13998       // Actual alignment of the loop will depend on the hotness check and other
13999       // logic in alignBlocks.
14000       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14001         return 5;
14002     }
14003 
14004     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14005 
14006     // For small loops (between 5 and 8 instructions), align to a 32-byte
14007     // boundary so that the entire loop fits in one instruction-cache line.
14008     uint64_t LoopSize = 0;
14009     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14010       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14011         LoopSize += TII->getInstSizeInBytes(*J);
14012         if (LoopSize > 32)
14013           break;
14014       }
14015 
14016     if (LoopSize > 16 && LoopSize <= 32)
14017       return 5;
14018 
14019     break;
14020   }
14021   }
14022 
14023   return TargetLowering::getPrefLoopAlignment(ML);
14024 }
14025 
14026 /// getConstraintType - Given a constraint, return the type of
14027 /// constraint it is for this target.
14028 PPCTargetLowering::ConstraintType
14029 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14030   if (Constraint.size() == 1) {
14031     switch (Constraint[0]) {
14032     default: break;
14033     case 'b':
14034     case 'r':
14035     case 'f':
14036     case 'd':
14037     case 'v':
14038     case 'y':
14039       return C_RegisterClass;
14040     case 'Z':
14041       // FIXME: While Z does indicate a memory constraint, it specifically
14042       // indicates an r+r address (used in conjunction with the 'y' modifier
14043       // in the replacement string). Currently, we're forcing the base
14044       // register to be r0 in the asm printer (which is interpreted as zero)
14045       // and forming the complete address in the second register. This is
14046       // suboptimal.
14047       return C_Memory;
14048     }
14049   } else if (Constraint == "wc") { // individual CR bits.
14050     return C_RegisterClass;
14051   } else if (Constraint == "wa" || Constraint == "wd" ||
14052              Constraint == "wf" || Constraint == "ws" ||
14053              Constraint == "wi" || Constraint == "ww") {
14054     return C_RegisterClass; // VSX registers.
14055   }
14056   return TargetLowering::getConstraintType(Constraint);
14057 }
14058 
14059 /// Examine constraint type and operand type and determine a weight value.
14060 /// This object must already have been set up with the operand type
14061 /// and the current alternative constraint selected.
14062 TargetLowering::ConstraintWeight
14063 PPCTargetLowering::getSingleConstraintMatchWeight(
14064     AsmOperandInfo &info, const char *constraint) const {
14065   ConstraintWeight weight = CW_Invalid;
14066   Value *CallOperandVal = info.CallOperandVal;
14067     // If we don't have a value, we can't do a match,
14068     // but allow it at the lowest weight.
14069   if (!CallOperandVal)
14070     return CW_Default;
14071   Type *type = CallOperandVal->getType();
14072 
14073   // Look at the constraint type.
14074   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14075     return CW_Register; // an individual CR bit.
14076   else if ((StringRef(constraint) == "wa" ||
14077             StringRef(constraint) == "wd" ||
14078             StringRef(constraint) == "wf") &&
14079            type->isVectorTy())
14080     return CW_Register;
14081   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14082     return CW_Register; // just hold 64-bit integers data.
14083   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14084     return CW_Register;
14085   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14086     return CW_Register;
14087 
14088   switch (*constraint) {
14089   default:
14090     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14091     break;
14092   case 'b':
14093     if (type->isIntegerTy())
14094       weight = CW_Register;
14095     break;
14096   case 'f':
14097     if (type->isFloatTy())
14098       weight = CW_Register;
14099     break;
14100   case 'd':
14101     if (type->isDoubleTy())
14102       weight = CW_Register;
14103     break;
14104   case 'v':
14105     if (type->isVectorTy())
14106       weight = CW_Register;
14107     break;
14108   case 'y':
14109     weight = CW_Register;
14110     break;
14111   case 'Z':
14112     weight = CW_Memory;
14113     break;
14114   }
14115   return weight;
14116 }
14117 
14118 std::pair<unsigned, const TargetRegisterClass *>
14119 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14120                                                 StringRef Constraint,
14121                                                 MVT VT) const {
14122   if (Constraint.size() == 1) {
14123     // GCC RS6000 Constraint Letters
14124     switch (Constraint[0]) {
14125     case 'b':   // R1-R31
14126       if (VT == MVT::i64 && Subtarget.isPPC64())
14127         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14128       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14129     case 'r':   // R0-R31
14130       if (VT == MVT::i64 && Subtarget.isPPC64())
14131         return std::make_pair(0U, &PPC::G8RCRegClass);
14132       return std::make_pair(0U, &PPC::GPRCRegClass);
14133     // 'd' and 'f' constraints are both defined to be "the floating point
14134     // registers", where one is for 32-bit and the other for 64-bit. We don't
14135     // really care overly much here so just give them all the same reg classes.
14136     case 'd':
14137     case 'f':
14138       if (Subtarget.hasSPE()) {
14139         if (VT == MVT::f32 || VT == MVT::i32)
14140           return std::make_pair(0U, &PPC::SPE4RCRegClass);
14141         if (VT == MVT::f64 || VT == MVT::i64)
14142           return std::make_pair(0U, &PPC::SPERCRegClass);
14143       } else {
14144         if (VT == MVT::f32 || VT == MVT::i32)
14145           return std::make_pair(0U, &PPC::F4RCRegClass);
14146         if (VT == MVT::f64 || VT == MVT::i64)
14147           return std::make_pair(0U, &PPC::F8RCRegClass);
14148         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14149           return std::make_pair(0U, &PPC::QFRCRegClass);
14150         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14151           return std::make_pair(0U, &PPC::QSRCRegClass);
14152       }
14153       break;
14154     case 'v':
14155       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14156         return std::make_pair(0U, &PPC::QFRCRegClass);
14157       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14158         return std::make_pair(0U, &PPC::QSRCRegClass);
14159       if (Subtarget.hasAltivec())
14160         return std::make_pair(0U, &PPC::VRRCRegClass);
14161       break;
14162     case 'y':   // crrc
14163       return std::make_pair(0U, &PPC::CRRCRegClass);
14164     }
14165   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14166     // An individual CR bit.
14167     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14168   } else if ((Constraint == "wa" || Constraint == "wd" ||
14169              Constraint == "wf" || Constraint == "wi") &&
14170              Subtarget.hasVSX()) {
14171     return std::make_pair(0U, &PPC::VSRCRegClass);
14172   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14173     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14174       return std::make_pair(0U, &PPC::VSSRCRegClass);
14175     else
14176       return std::make_pair(0U, &PPC::VSFRCRegClass);
14177   }
14178 
14179   std::pair<unsigned, const TargetRegisterClass *> R =
14180       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14181 
14182   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14183   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14184   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14185   // register.
14186   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14187   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14188   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14189       PPC::GPRCRegClass.contains(R.first))
14190     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14191                             PPC::sub_32, &PPC::G8RCRegClass),
14192                           &PPC::G8RCRegClass);
14193 
14194   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14195   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14196     R.first = PPC::CR0;
14197     R.second = &PPC::CRRCRegClass;
14198   }
14199 
14200   return R;
14201 }
14202 
14203 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14204 /// vector.  If it is invalid, don't add anything to Ops.
14205 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14206                                                      std::string &Constraint,
14207                                                      std::vector<SDValue>&Ops,
14208                                                      SelectionDAG &DAG) const {
14209   SDValue Result;
14210 
14211   // Only support length 1 constraints.
14212   if (Constraint.length() > 1) return;
14213 
14214   char Letter = Constraint[0];
14215   switch (Letter) {
14216   default: break;
14217   case 'I':
14218   case 'J':
14219   case 'K':
14220   case 'L':
14221   case 'M':
14222   case 'N':
14223   case 'O':
14224   case 'P': {
14225     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14226     if (!CST) return; // Must be an immediate to match.
14227     SDLoc dl(Op);
14228     int64_t Value = CST->getSExtValue();
14229     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14230                          // numbers are printed as such.
14231     switch (Letter) {
14232     default: llvm_unreachable("Unknown constraint letter!");
14233     case 'I':  // "I" is a signed 16-bit constant.
14234       if (isInt<16>(Value))
14235         Result = DAG.getTargetConstant(Value, dl, TCVT);
14236       break;
14237     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14238       if (isShiftedUInt<16, 16>(Value))
14239         Result = DAG.getTargetConstant(Value, dl, TCVT);
14240       break;
14241     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14242       if (isShiftedInt<16, 16>(Value))
14243         Result = DAG.getTargetConstant(Value, dl, TCVT);
14244       break;
14245     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14246       if (isUInt<16>(Value))
14247         Result = DAG.getTargetConstant(Value, dl, TCVT);
14248       break;
14249     case 'M':  // "M" is a constant that is greater than 31.
14250       if (Value > 31)
14251         Result = DAG.getTargetConstant(Value, dl, TCVT);
14252       break;
14253     case 'N':  // "N" is a positive constant that is an exact power of two.
14254       if (Value > 0 && isPowerOf2_64(Value))
14255         Result = DAG.getTargetConstant(Value, dl, TCVT);
14256       break;
14257     case 'O':  // "O" is the constant zero.
14258       if (Value == 0)
14259         Result = DAG.getTargetConstant(Value, dl, TCVT);
14260       break;
14261     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14262       if (isInt<16>(-Value))
14263         Result = DAG.getTargetConstant(Value, dl, TCVT);
14264       break;
14265     }
14266     break;
14267   }
14268   }
14269 
14270   if (Result.getNode()) {
14271     Ops.push_back(Result);
14272     return;
14273   }
14274 
14275   // Handle standard constraint letters.
14276   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14277 }
14278 
14279 // isLegalAddressingMode - Return true if the addressing mode represented
14280 // by AM is legal for this target, for a load/store of the specified type.
14281 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14282                                               const AddrMode &AM, Type *Ty,
14283                                               unsigned AS, Instruction *I) const {
14284   // PPC does not allow r+i addressing modes for vectors!
14285   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14286     return false;
14287 
14288   // PPC allows a sign-extended 16-bit immediate field.
14289   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14290     return false;
14291 
14292   // No global is ever allowed as a base.
14293   if (AM.BaseGV)
14294     return false;
14295 
14296   // PPC only support r+r,
14297   switch (AM.Scale) {
14298   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14299     break;
14300   case 1:
14301     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14302       return false;
14303     // Otherwise we have r+r or r+i.
14304     break;
14305   case 2:
14306     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14307       return false;
14308     // Allow 2*r as r+r.
14309     break;
14310   default:
14311     // No other scales are supported.
14312     return false;
14313   }
14314 
14315   return true;
14316 }
14317 
14318 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14319                                            SelectionDAG &DAG) const {
14320   MachineFunction &MF = DAG.getMachineFunction();
14321   MachineFrameInfo &MFI = MF.getFrameInfo();
14322   MFI.setReturnAddressIsTaken(true);
14323 
14324   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14325     return SDValue();
14326 
14327   SDLoc dl(Op);
14328   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14329 
14330   // Make sure the function does not optimize away the store of the RA to
14331   // the stack.
14332   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14333   FuncInfo->setLRStoreRequired();
14334   bool isPPC64 = Subtarget.isPPC64();
14335   auto PtrVT = getPointerTy(MF.getDataLayout());
14336 
14337   if (Depth > 0) {
14338     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14339     SDValue Offset =
14340         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14341                         isPPC64 ? MVT::i64 : MVT::i32);
14342     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14343                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14344                        MachinePointerInfo());
14345   }
14346 
14347   // Just load the return address off the stack.
14348   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14349   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14350                      MachinePointerInfo());
14351 }
14352 
14353 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14354                                           SelectionDAG &DAG) const {
14355   SDLoc dl(Op);
14356   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14357 
14358   MachineFunction &MF = DAG.getMachineFunction();
14359   MachineFrameInfo &MFI = MF.getFrameInfo();
14360   MFI.setFrameAddressIsTaken(true);
14361 
14362   EVT PtrVT = getPointerTy(MF.getDataLayout());
14363   bool isPPC64 = PtrVT == MVT::i64;
14364 
14365   // Naked functions never have a frame pointer, and so we use r1. For all
14366   // other functions, this decision must be delayed until during PEI.
14367   unsigned FrameReg;
14368   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14369     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14370   else
14371     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14372 
14373   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14374                                          PtrVT);
14375   while (Depth--)
14376     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14377                             FrameAddr, MachinePointerInfo());
14378   return FrameAddr;
14379 }
14380 
14381 // FIXME? Maybe this could be a TableGen attribute on some registers and
14382 // this table could be generated automatically from RegInfo.
14383 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
14384                                               SelectionDAG &DAG) const {
14385   bool isPPC64 = Subtarget.isPPC64();
14386   bool isDarwinABI = Subtarget.isDarwinABI();
14387 
14388   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
14389       (!isPPC64 && VT != MVT::i32))
14390     report_fatal_error("Invalid register global variable type");
14391 
14392   bool is64Bit = isPPC64 && VT == MVT::i64;
14393   unsigned Reg = StringSwitch<unsigned>(RegName)
14394                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14395                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
14396                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
14397                                   (is64Bit ? PPC::X13 : PPC::R13))
14398                    .Default(0);
14399 
14400   if (Reg)
14401     return Reg;
14402   report_fatal_error("Invalid register name global variable");
14403 }
14404 
14405 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14406   // 32-bit SVR4 ABI access everything as got-indirect.
14407   if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
14408     return true;
14409 
14410   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14411   // If it is small or large code model, module locals are accessed
14412   // indirectly by loading their address from .toc/.got. The difference
14413   // is that for large code model we have ADDIStocHA8 + LDtocL and for
14414   // small code model we simply have LDtoc.
14415   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14416     return true;
14417 
14418   // JumpTable and BlockAddress are accessed as got-indirect.
14419   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14420     return true;
14421 
14422   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
14423     const GlobalValue *GV = G->getGlobal();
14424     unsigned char GVFlags = Subtarget.classifyGlobalReference(GV);
14425     // The NLP flag indicates that a global access has to use an
14426     // extra indirection.
14427     if (GVFlags & PPCII::MO_NLP_FLAG)
14428       return true;
14429   }
14430 
14431   return false;
14432 }
14433 
14434 bool
14435 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14436   // The PowerPC target isn't yet aware of offsets.
14437   return false;
14438 }
14439 
14440 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14441                                            const CallInst &I,
14442                                            MachineFunction &MF,
14443                                            unsigned Intrinsic) const {
14444   switch (Intrinsic) {
14445   case Intrinsic::ppc_qpx_qvlfd:
14446   case Intrinsic::ppc_qpx_qvlfs:
14447   case Intrinsic::ppc_qpx_qvlfcd:
14448   case Intrinsic::ppc_qpx_qvlfcs:
14449   case Intrinsic::ppc_qpx_qvlfiwa:
14450   case Intrinsic::ppc_qpx_qvlfiwz:
14451   case Intrinsic::ppc_altivec_lvx:
14452   case Intrinsic::ppc_altivec_lvxl:
14453   case Intrinsic::ppc_altivec_lvebx:
14454   case Intrinsic::ppc_altivec_lvehx:
14455   case Intrinsic::ppc_altivec_lvewx:
14456   case Intrinsic::ppc_vsx_lxvd2x:
14457   case Intrinsic::ppc_vsx_lxvw4x: {
14458     EVT VT;
14459     switch (Intrinsic) {
14460     case Intrinsic::ppc_altivec_lvebx:
14461       VT = MVT::i8;
14462       break;
14463     case Intrinsic::ppc_altivec_lvehx:
14464       VT = MVT::i16;
14465       break;
14466     case Intrinsic::ppc_altivec_lvewx:
14467       VT = MVT::i32;
14468       break;
14469     case Intrinsic::ppc_vsx_lxvd2x:
14470       VT = MVT::v2f64;
14471       break;
14472     case Intrinsic::ppc_qpx_qvlfd:
14473       VT = MVT::v4f64;
14474       break;
14475     case Intrinsic::ppc_qpx_qvlfs:
14476       VT = MVT::v4f32;
14477       break;
14478     case Intrinsic::ppc_qpx_qvlfcd:
14479       VT = MVT::v2f64;
14480       break;
14481     case Intrinsic::ppc_qpx_qvlfcs:
14482       VT = MVT::v2f32;
14483       break;
14484     default:
14485       VT = MVT::v4i32;
14486       break;
14487     }
14488 
14489     Info.opc = ISD::INTRINSIC_W_CHAIN;
14490     Info.memVT = VT;
14491     Info.ptrVal = I.getArgOperand(0);
14492     Info.offset = -VT.getStoreSize()+1;
14493     Info.size = 2*VT.getStoreSize()-1;
14494     Info.align = Align(1);
14495     Info.flags = MachineMemOperand::MOLoad;
14496     return true;
14497   }
14498   case Intrinsic::ppc_qpx_qvlfda:
14499   case Intrinsic::ppc_qpx_qvlfsa:
14500   case Intrinsic::ppc_qpx_qvlfcda:
14501   case Intrinsic::ppc_qpx_qvlfcsa:
14502   case Intrinsic::ppc_qpx_qvlfiwaa:
14503   case Intrinsic::ppc_qpx_qvlfiwza: {
14504     EVT VT;
14505     switch (Intrinsic) {
14506     case Intrinsic::ppc_qpx_qvlfda:
14507       VT = MVT::v4f64;
14508       break;
14509     case Intrinsic::ppc_qpx_qvlfsa:
14510       VT = MVT::v4f32;
14511       break;
14512     case Intrinsic::ppc_qpx_qvlfcda:
14513       VT = MVT::v2f64;
14514       break;
14515     case Intrinsic::ppc_qpx_qvlfcsa:
14516       VT = MVT::v2f32;
14517       break;
14518     default:
14519       VT = MVT::v4i32;
14520       break;
14521     }
14522 
14523     Info.opc = ISD::INTRINSIC_W_CHAIN;
14524     Info.memVT = VT;
14525     Info.ptrVal = I.getArgOperand(0);
14526     Info.offset = 0;
14527     Info.size = VT.getStoreSize();
14528     Info.align = Align(1);
14529     Info.flags = MachineMemOperand::MOLoad;
14530     return true;
14531   }
14532   case Intrinsic::ppc_qpx_qvstfd:
14533   case Intrinsic::ppc_qpx_qvstfs:
14534   case Intrinsic::ppc_qpx_qvstfcd:
14535   case Intrinsic::ppc_qpx_qvstfcs:
14536   case Intrinsic::ppc_qpx_qvstfiw:
14537   case Intrinsic::ppc_altivec_stvx:
14538   case Intrinsic::ppc_altivec_stvxl:
14539   case Intrinsic::ppc_altivec_stvebx:
14540   case Intrinsic::ppc_altivec_stvehx:
14541   case Intrinsic::ppc_altivec_stvewx:
14542   case Intrinsic::ppc_vsx_stxvd2x:
14543   case Intrinsic::ppc_vsx_stxvw4x: {
14544     EVT VT;
14545     switch (Intrinsic) {
14546     case Intrinsic::ppc_altivec_stvebx:
14547       VT = MVT::i8;
14548       break;
14549     case Intrinsic::ppc_altivec_stvehx:
14550       VT = MVT::i16;
14551       break;
14552     case Intrinsic::ppc_altivec_stvewx:
14553       VT = MVT::i32;
14554       break;
14555     case Intrinsic::ppc_vsx_stxvd2x:
14556       VT = MVT::v2f64;
14557       break;
14558     case Intrinsic::ppc_qpx_qvstfd:
14559       VT = MVT::v4f64;
14560       break;
14561     case Intrinsic::ppc_qpx_qvstfs:
14562       VT = MVT::v4f32;
14563       break;
14564     case Intrinsic::ppc_qpx_qvstfcd:
14565       VT = MVT::v2f64;
14566       break;
14567     case Intrinsic::ppc_qpx_qvstfcs:
14568       VT = MVT::v2f32;
14569       break;
14570     default:
14571       VT = MVT::v4i32;
14572       break;
14573     }
14574 
14575     Info.opc = ISD::INTRINSIC_VOID;
14576     Info.memVT = VT;
14577     Info.ptrVal = I.getArgOperand(1);
14578     Info.offset = -VT.getStoreSize()+1;
14579     Info.size = 2*VT.getStoreSize()-1;
14580     Info.align = Align(1);
14581     Info.flags = MachineMemOperand::MOStore;
14582     return true;
14583   }
14584   case Intrinsic::ppc_qpx_qvstfda:
14585   case Intrinsic::ppc_qpx_qvstfsa:
14586   case Intrinsic::ppc_qpx_qvstfcda:
14587   case Intrinsic::ppc_qpx_qvstfcsa:
14588   case Intrinsic::ppc_qpx_qvstfiwa: {
14589     EVT VT;
14590     switch (Intrinsic) {
14591     case Intrinsic::ppc_qpx_qvstfda:
14592       VT = MVT::v4f64;
14593       break;
14594     case Intrinsic::ppc_qpx_qvstfsa:
14595       VT = MVT::v4f32;
14596       break;
14597     case Intrinsic::ppc_qpx_qvstfcda:
14598       VT = MVT::v2f64;
14599       break;
14600     case Intrinsic::ppc_qpx_qvstfcsa:
14601       VT = MVT::v2f32;
14602       break;
14603     default:
14604       VT = MVT::v4i32;
14605       break;
14606     }
14607 
14608     Info.opc = ISD::INTRINSIC_VOID;
14609     Info.memVT = VT;
14610     Info.ptrVal = I.getArgOperand(1);
14611     Info.offset = 0;
14612     Info.size = VT.getStoreSize();
14613     Info.align = Align(1);
14614     Info.flags = MachineMemOperand::MOStore;
14615     return true;
14616   }
14617   default:
14618     break;
14619   }
14620 
14621   return false;
14622 }
14623 
14624 /// getOptimalMemOpType - Returns the target specific optimal type for load
14625 /// and store operations as a result of memset, memcpy, and memmove
14626 /// lowering. If DstAlign is zero that means it's safe to destination
14627 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
14628 /// means there isn't a need to check it against alignment requirement,
14629 /// probably because the source does not need to be loaded. If 'IsMemset' is
14630 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
14631 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
14632 /// source is constant so it does not need to be loaded.
14633 /// It returns EVT::Other if the type should be determined using generic
14634 /// target-independent logic.
14635 EVT PPCTargetLowering::getOptimalMemOpType(
14636     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14637     bool ZeroMemset, bool MemcpyStrSrc,
14638     const AttributeList &FuncAttributes) const {
14639   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
14640     // When expanding a memset, require at least two QPX instructions to cover
14641     // the cost of loading the value to be stored from the constant pool.
14642     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
14643        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
14644         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14645       return MVT::v4f64;
14646     }
14647 
14648     // We should use Altivec/VSX loads and stores when available. For unaligned
14649     // addresses, unaligned VSX loads are only fast starting with the P8.
14650     if (Subtarget.hasAltivec() && Size >= 16 &&
14651         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
14652          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
14653       return MVT::v4i32;
14654   }
14655 
14656   if (Subtarget.isPPC64()) {
14657     return MVT::i64;
14658   }
14659 
14660   return MVT::i32;
14661 }
14662 
14663 /// Returns true if it is beneficial to convert a load of a constant
14664 /// to just the constant itself.
14665 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14666                                                           Type *Ty) const {
14667   assert(Ty->isIntegerTy());
14668 
14669   unsigned BitSize = Ty->getPrimitiveSizeInBits();
14670   return !(BitSize == 0 || BitSize > 64);
14671 }
14672 
14673 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14674   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14675     return false;
14676   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14677   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14678   return NumBits1 == 64 && NumBits2 == 32;
14679 }
14680 
14681 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14682   if (!VT1.isInteger() || !VT2.isInteger())
14683     return false;
14684   unsigned NumBits1 = VT1.getSizeInBits();
14685   unsigned NumBits2 = VT2.getSizeInBits();
14686   return NumBits1 == 64 && NumBits2 == 32;
14687 }
14688 
14689 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14690   // Generally speaking, zexts are not free, but they are free when they can be
14691   // folded with other operations.
14692   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
14693     EVT MemVT = LD->getMemoryVT();
14694     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
14695          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
14696         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
14697          LD->getExtensionType() == ISD::ZEXTLOAD))
14698       return true;
14699   }
14700 
14701   // FIXME: Add other cases...
14702   //  - 32-bit shifts with a zext to i64
14703   //  - zext after ctlz, bswap, etc.
14704   //  - zext after and by a constant mask
14705 
14706   return TargetLowering::isZExtFree(Val, VT2);
14707 }
14708 
14709 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
14710   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
14711          "invalid fpext types");
14712   // Extending to float128 is not free.
14713   if (DestVT == MVT::f128)
14714     return false;
14715   return true;
14716 }
14717 
14718 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14719   return isInt<16>(Imm) || isUInt<16>(Imm);
14720 }
14721 
14722 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14723   return isInt<16>(Imm) || isUInt<16>(Imm);
14724 }
14725 
14726 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
14727                                                        unsigned,
14728                                                        unsigned,
14729                                                        MachineMemOperand::Flags,
14730                                                        bool *Fast) const {
14731   if (DisablePPCUnaligned)
14732     return false;
14733 
14734   // PowerPC supports unaligned memory access for simple non-vector types.
14735   // Although accessing unaligned addresses is not as efficient as accessing
14736   // aligned addresses, it is generally more efficient than manual expansion,
14737   // and generally only traps for software emulation when crossing page
14738   // boundaries.
14739 
14740   if (!VT.isSimple())
14741     return false;
14742 
14743   if (VT.getSimpleVT().isVector()) {
14744     if (Subtarget.hasVSX()) {
14745       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
14746           VT != MVT::v4f32 && VT != MVT::v4i32)
14747         return false;
14748     } else {
14749       return false;
14750     }
14751   }
14752 
14753   if (VT == MVT::ppcf128)
14754     return false;
14755 
14756   if (Fast)
14757     *Fast = true;
14758 
14759   return true;
14760 }
14761 
14762 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14763   VT = VT.getScalarType();
14764 
14765   if (!VT.isSimple())
14766     return false;
14767 
14768   switch (VT.getSimpleVT().SimpleTy) {
14769   case MVT::f32:
14770   case MVT::f64:
14771     return true;
14772   case MVT::f128:
14773     return (EnableQuadPrecision && Subtarget.hasP9Vector());
14774   default:
14775     break;
14776   }
14777 
14778   return false;
14779 }
14780 
14781 const MCPhysReg *
14782 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
14783   // LR is a callee-save register, but we must treat it as clobbered by any call
14784   // site. Hence we include LR in the scratch registers, which are in turn added
14785   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
14786   // to CTR, which is used by any indirect call.
14787   static const MCPhysReg ScratchRegs[] = {
14788     PPC::X12, PPC::LR8, PPC::CTR8, 0
14789   };
14790 
14791   return ScratchRegs;
14792 }
14793 
14794 unsigned PPCTargetLowering::getExceptionPointerRegister(
14795     const Constant *PersonalityFn) const {
14796   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
14797 }
14798 
14799 unsigned PPCTargetLowering::getExceptionSelectorRegister(
14800     const Constant *PersonalityFn) const {
14801   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
14802 }
14803 
14804 bool
14805 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
14806                      EVT VT , unsigned DefinedValues) const {
14807   if (VT == MVT::v2i64)
14808     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
14809 
14810   if (Subtarget.hasVSX() || Subtarget.hasQPX())
14811     return true;
14812 
14813   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
14814 }
14815 
14816 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
14817   if (DisableILPPref || Subtarget.enableMachineScheduler())
14818     return TargetLowering::getSchedulingPreference(N);
14819 
14820   return Sched::ILP;
14821 }
14822 
14823 // Create a fast isel object.
14824 FastISel *
14825 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
14826                                   const TargetLibraryInfo *LibInfo) const {
14827   return PPC::createFastISel(FuncInfo, LibInfo);
14828 }
14829 
14830 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14831   if (Subtarget.isDarwinABI()) return;
14832   if (!Subtarget.isPPC64()) return;
14833 
14834   // Update IsSplitCSR in PPCFunctionInfo
14835   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
14836   PFI->setIsSplitCSR(true);
14837 }
14838 
14839 void PPCTargetLowering::insertCopiesSplitCSR(
14840   MachineBasicBlock *Entry,
14841   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14842   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
14843   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14844   if (!IStart)
14845     return;
14846 
14847   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14848   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14849   MachineBasicBlock::iterator MBBI = Entry->begin();
14850   for (const MCPhysReg *I = IStart; *I; ++I) {
14851     const TargetRegisterClass *RC = nullptr;
14852     if (PPC::G8RCRegClass.contains(*I))
14853       RC = &PPC::G8RCRegClass;
14854     else if (PPC::F8RCRegClass.contains(*I))
14855       RC = &PPC::F8RCRegClass;
14856     else if (PPC::CRRCRegClass.contains(*I))
14857       RC = &PPC::CRRCRegClass;
14858     else if (PPC::VRRCRegClass.contains(*I))
14859       RC = &PPC::VRRCRegClass;
14860     else
14861       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14862 
14863     unsigned NewVR = MRI->createVirtualRegister(RC);
14864     // Create copy from CSR to a virtual register.
14865     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14866     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14867     // nounwind. If we want to generalize this later, we may need to emit
14868     // CFI pseudo-instructions.
14869     assert(Entry->getParent()->getFunction().hasFnAttribute(
14870              Attribute::NoUnwind) &&
14871            "Function should be nounwind in insertCopiesSplitCSR!");
14872     Entry->addLiveIn(*I);
14873     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14874       .addReg(*I);
14875 
14876     // Insert the copy-back instructions right before the terminator.
14877     for (auto *Exit : Exits)
14878       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14879               TII->get(TargetOpcode::COPY), *I)
14880         .addReg(NewVR);
14881   }
14882 }
14883 
14884 // Override to enable LOAD_STACK_GUARD lowering on Linux.
14885 bool PPCTargetLowering::useLoadStackGuardNode() const {
14886   if (!Subtarget.isTargetLinux())
14887     return TargetLowering::useLoadStackGuardNode();
14888   return true;
14889 }
14890 
14891 // Override to disable global variable loading on Linux.
14892 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
14893   if (!Subtarget.isTargetLinux())
14894     return TargetLowering::insertSSPDeclarations(M);
14895 }
14896 
14897 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
14898                                      bool ForCodeSize) const {
14899   if (!VT.isSimple() || !Subtarget.hasVSX())
14900     return false;
14901 
14902   switch(VT.getSimpleVT().SimpleTy) {
14903   default:
14904     // For FP types that are currently not supported by PPC backend, return
14905     // false. Examples: f16, f80.
14906     return false;
14907   case MVT::f32:
14908   case MVT::f64:
14909   case MVT::ppcf128:
14910     return Imm.isPosZero();
14911   }
14912 }
14913 
14914 // For vector shift operation op, fold
14915 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
14916 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
14917                                   SelectionDAG &DAG) {
14918   SDValue N0 = N->getOperand(0);
14919   SDValue N1 = N->getOperand(1);
14920   EVT VT = N0.getValueType();
14921   unsigned OpSizeInBits = VT.getScalarSizeInBits();
14922   unsigned Opcode = N->getOpcode();
14923   unsigned TargetOpcode;
14924 
14925   switch (Opcode) {
14926   default:
14927     llvm_unreachable("Unexpected shift operation");
14928   case ISD::SHL:
14929     TargetOpcode = PPCISD::SHL;
14930     break;
14931   case ISD::SRL:
14932     TargetOpcode = PPCISD::SRL;
14933     break;
14934   case ISD::SRA:
14935     TargetOpcode = PPCISD::SRA;
14936     break;
14937   }
14938 
14939   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
14940       N1->getOpcode() == ISD::AND)
14941     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
14942       if (Mask->getZExtValue() == OpSizeInBits - 1)
14943         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
14944 
14945   return SDValue();
14946 }
14947 
14948 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
14949   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14950     return Value;
14951 
14952   SDValue N0 = N->getOperand(0);
14953   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
14954   if (!Subtarget.isISA3_0() ||
14955       N0.getOpcode() != ISD::SIGN_EXTEND ||
14956       N0.getOperand(0).getValueType() != MVT::i32 ||
14957       CN1 == nullptr || N->getValueType(0) != MVT::i64)
14958     return SDValue();
14959 
14960   // We can't save an operation here if the value is already extended, and
14961   // the existing shift is easier to combine.
14962   SDValue ExtsSrc = N0.getOperand(0);
14963   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
14964       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
14965     return SDValue();
14966 
14967   SDLoc DL(N0);
14968   SDValue ShiftBy = SDValue(CN1, 0);
14969   // We want the shift amount to be i32 on the extswli, but the shift could
14970   // have an i64.
14971   if (ShiftBy.getValueType() == MVT::i64)
14972     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
14973 
14974   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
14975                          ShiftBy);
14976 }
14977 
14978 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
14979   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14980     return Value;
14981 
14982   return SDValue();
14983 }
14984 
14985 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
14986   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14987     return Value;
14988 
14989   return SDValue();
14990 }
14991 
14992 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
14993 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
14994 // When C is zero, the equation (addi Z, -C) can be simplified to Z
14995 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
14996 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
14997                                  const PPCSubtarget &Subtarget) {
14998   if (!Subtarget.isPPC64())
14999     return SDValue();
15000 
15001   SDValue LHS = N->getOperand(0);
15002   SDValue RHS = N->getOperand(1);
15003 
15004   auto isZextOfCompareWithConstant = [](SDValue Op) {
15005     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15006         Op.getValueType() != MVT::i64)
15007       return false;
15008 
15009     SDValue Cmp = Op.getOperand(0);
15010     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15011         Cmp.getOperand(0).getValueType() != MVT::i64)
15012       return false;
15013 
15014     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15015       int64_t NegConstant = 0 - Constant->getSExtValue();
15016       // Due to the limitations of the addi instruction,
15017       // -C is required to be [-32768, 32767].
15018       return isInt<16>(NegConstant);
15019     }
15020 
15021     return false;
15022   };
15023 
15024   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15025   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15026 
15027   // If there is a pattern, canonicalize a zext operand to the RHS.
15028   if (LHSHasPattern && !RHSHasPattern)
15029     std::swap(LHS, RHS);
15030   else if (!LHSHasPattern && !RHSHasPattern)
15031     return SDValue();
15032 
15033   SDLoc DL(N);
15034   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15035   SDValue Cmp = RHS.getOperand(0);
15036   SDValue Z = Cmp.getOperand(0);
15037   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15038 
15039   assert(Constant && "Constant Should not be a null pointer.");
15040   int64_t NegConstant = 0 - Constant->getSExtValue();
15041 
15042   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15043   default: break;
15044   case ISD::SETNE: {
15045     //                                 when C == 0
15046     //                             --> addze X, (addic Z, -1).carry
15047     //                            /
15048     // add X, (zext(setne Z, C))--
15049     //                            \    when -32768 <= -C <= 32767 && C != 0
15050     //                             --> addze X, (addic (addi Z, -C), -1).carry
15051     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15052                               DAG.getConstant(NegConstant, DL, MVT::i64));
15053     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15054     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15055                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15056     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15057                        SDValue(Addc.getNode(), 1));
15058     }
15059   case ISD::SETEQ: {
15060     //                                 when C == 0
15061     //                             --> addze X, (subfic Z, 0).carry
15062     //                            /
15063     // add X, (zext(sete  Z, C))--
15064     //                            \    when -32768 <= -C <= 32767 && C != 0
15065     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15066     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15067                               DAG.getConstant(NegConstant, DL, MVT::i64));
15068     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15069     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15070                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15071     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15072                        SDValue(Subc.getNode(), 1));
15073     }
15074   }
15075 
15076   return SDValue();
15077 }
15078 
15079 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15080   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15081     return Value;
15082 
15083   return SDValue();
15084 }
15085 
15086 // Detect TRUNCATE operations on bitcasts of float128 values.
15087 // What we are looking for here is the situtation where we extract a subset
15088 // of bits from a 128 bit float.
15089 // This can be of two forms:
15090 // 1) BITCAST of f128 feeding TRUNCATE
15091 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15092 // The reason this is required is because we do not have a legal i128 type
15093 // and so we want to prevent having to store the f128 and then reload part
15094 // of it.
15095 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15096                                            DAGCombinerInfo &DCI) const {
15097   // If we are using CRBits then try that first.
15098   if (Subtarget.useCRBits()) {
15099     // Check if CRBits did anything and return that if it did.
15100     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15101       return CRTruncValue;
15102   }
15103 
15104   SDLoc dl(N);
15105   SDValue Op0 = N->getOperand(0);
15106 
15107   // Looking for a truncate of i128 to i64.
15108   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15109     return SDValue();
15110 
15111   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15112 
15113   // SRL feeding TRUNCATE.
15114   if (Op0.getOpcode() == ISD::SRL) {
15115     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15116     // The right shift has to be by 64 bits.
15117     if (!ConstNode || ConstNode->getZExtValue() != 64)
15118       return SDValue();
15119 
15120     // Switch the element number to extract.
15121     EltToExtract = EltToExtract ? 0 : 1;
15122     // Update Op0 past the SRL.
15123     Op0 = Op0.getOperand(0);
15124   }
15125 
15126   // BITCAST feeding a TRUNCATE possibly via SRL.
15127   if (Op0.getOpcode() == ISD::BITCAST &&
15128       Op0.getValueType() == MVT::i128 &&
15129       Op0.getOperand(0).getValueType() == MVT::f128) {
15130     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15131     return DCI.DAG.getNode(
15132         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15133         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15134   }
15135   return SDValue();
15136 }
15137 
15138 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15139   SelectionDAG &DAG = DCI.DAG;
15140 
15141   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15142   if (!ConstOpOrElement)
15143     return SDValue();
15144 
15145   // An imul is usually smaller than the alternative sequence for legal type.
15146   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15147       isOperationLegal(ISD::MUL, N->getValueType(0)))
15148     return SDValue();
15149 
15150   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15151     switch (this->Subtarget.getDarwinDirective()) {
15152     default:
15153       // TODO: enhance the condition for subtarget before pwr8
15154       return false;
15155     case PPC::DIR_PWR8:
15156       //  type        mul     add    shl
15157       // scalar        4       1      1
15158       // vector        7       2      2
15159       return true;
15160     case PPC::DIR_PWR9:
15161       //  type        mul     add    shl
15162       // scalar        5       2      2
15163       // vector        7       2      2
15164 
15165       // The cycle RATIO of related operations are showed as a table above.
15166       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15167       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15168       // are 4, it is always profitable; but for 3 instrs patterns
15169       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15170       // So we should only do it for vector type.
15171       return IsAddOne && IsNeg ? VT.isVector() : true;
15172     }
15173   };
15174 
15175   EVT VT = N->getValueType(0);
15176   SDLoc DL(N);
15177 
15178   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15179   bool IsNeg = MulAmt.isNegative();
15180   APInt MulAmtAbs = MulAmt.abs();
15181 
15182   if ((MulAmtAbs - 1).isPowerOf2()) {
15183     // (mul x, 2^N + 1) => (add (shl x, N), x)
15184     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15185 
15186     if (!IsProfitable(IsNeg, true, VT))
15187       return SDValue();
15188 
15189     SDValue Op0 = N->getOperand(0);
15190     SDValue Op1 =
15191         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15192                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15193     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15194 
15195     if (!IsNeg)
15196       return Res;
15197 
15198     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15199   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15200     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15201     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15202 
15203     if (!IsProfitable(IsNeg, false, VT))
15204       return SDValue();
15205 
15206     SDValue Op0 = N->getOperand(0);
15207     SDValue Op1 =
15208         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15209                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15210 
15211     if (!IsNeg)
15212       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15213     else
15214       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15215 
15216   } else {
15217     return SDValue();
15218   }
15219 }
15220 
15221 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15222   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15223   if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64())
15224     return false;
15225 
15226   // If not a tail call then no need to proceed.
15227   if (!CI->isTailCall())
15228     return false;
15229 
15230   // If tail calls are disabled for the caller then we are done.
15231   const Function *Caller = CI->getParent()->getParent();
15232   auto Attr = Caller->getFnAttribute("disable-tail-calls");
15233   if (Attr.getValueAsString() == "true")
15234     return false;
15235 
15236   // If sibling calls have been disabled and tail-calls aren't guaranteed
15237   // there is no reason to duplicate.
15238   auto &TM = getTargetMachine();
15239   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15240     return false;
15241 
15242   // Can't tail call a function called indirectly, or if it has variadic args.
15243   const Function *Callee = CI->getCalledFunction();
15244   if (!Callee || Callee->isVarArg())
15245     return false;
15246 
15247   // Make sure the callee and caller calling conventions are eligible for tco.
15248   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15249                                            CI->getCallingConv()))
15250       return false;
15251 
15252   // If the function is local then we have a good chance at tail-calling it
15253   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15254 }
15255 
15256 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15257   if (!Subtarget.hasVSX())
15258     return false;
15259   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15260     return true;
15261   return VT == MVT::f32 || VT == MVT::f64 ||
15262     VT == MVT::v4f32 || VT == MVT::v2f64;
15263 }
15264 
15265 bool PPCTargetLowering::
15266 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15267   const Value *Mask = AndI.getOperand(1);
15268   // If the mask is suitable for andi. or andis. we should sink the and.
15269   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15270     // Can't handle constants wider than 64-bits.
15271     if (CI->getBitWidth() > 64)
15272       return false;
15273     int64_t ConstVal = CI->getZExtValue();
15274     return isUInt<16>(ConstVal) ||
15275       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15276   }
15277 
15278   // For non-constant masks, we can always use the record-form and.
15279   return true;
15280 }
15281 
15282 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15283 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15284 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15285 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15286 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15287 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15288   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15289   assert(Subtarget.hasP9Altivec() &&
15290          "Only combine this when P9 altivec supported!");
15291   EVT VT = N->getValueType(0);
15292   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15293     return SDValue();
15294 
15295   SelectionDAG &DAG = DCI.DAG;
15296   SDLoc dl(N);
15297   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15298     // Even for signed integers, if it's known to be positive (as signed
15299     // integer) due to zero-extended inputs.
15300     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15301     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15302     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15303          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15304         (SubOpcd1 == ISD::ZERO_EXTEND ||
15305          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15306       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15307                          N->getOperand(0)->getOperand(0),
15308                          N->getOperand(0)->getOperand(1),
15309                          DAG.getTargetConstant(0, dl, MVT::i32));
15310     }
15311 
15312     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15313     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15314         N->getOperand(0).hasOneUse()) {
15315       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15316                          N->getOperand(0)->getOperand(0),
15317                          N->getOperand(0)->getOperand(1),
15318                          DAG.getTargetConstant(1, dl, MVT::i32));
15319     }
15320   }
15321 
15322   return SDValue();
15323 }
15324 
15325 // For type v4i32/v8ii16/v16i8, transform
15326 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15327 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15328 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15329 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15330 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15331                                           DAGCombinerInfo &DCI) const {
15332   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15333   assert(Subtarget.hasP9Altivec() &&
15334          "Only combine this when P9 altivec supported!");
15335 
15336   SelectionDAG &DAG = DCI.DAG;
15337   SDLoc dl(N);
15338   SDValue Cond = N->getOperand(0);
15339   SDValue TrueOpnd = N->getOperand(1);
15340   SDValue FalseOpnd = N->getOperand(2);
15341   EVT VT = N->getOperand(1).getValueType();
15342 
15343   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15344       FalseOpnd.getOpcode() != ISD::SUB)
15345     return SDValue();
15346 
15347   // ABSD only available for type v4i32/v8i16/v16i8
15348   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15349     return SDValue();
15350 
15351   // At least to save one more dependent computation
15352   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15353     return SDValue();
15354 
15355   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15356 
15357   // Can only handle unsigned comparison here
15358   switch (CC) {
15359   default:
15360     return SDValue();
15361   case ISD::SETUGT:
15362   case ISD::SETUGE:
15363     break;
15364   case ISD::SETULT:
15365   case ISD::SETULE:
15366     std::swap(TrueOpnd, FalseOpnd);
15367     break;
15368   }
15369 
15370   SDValue CmpOpnd1 = Cond.getOperand(0);
15371   SDValue CmpOpnd2 = Cond.getOperand(1);
15372 
15373   // SETCC CmpOpnd1 CmpOpnd2 cond
15374   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15375   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15376   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15377       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15378       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15379       FalseOpnd.getOperand(1) == CmpOpnd1) {
15380     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15381                        CmpOpnd1, CmpOpnd2,
15382                        DAG.getTargetConstant(0, dl, MVT::i32));
15383   }
15384 
15385   return SDValue();
15386 }
15387