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 
1122   if (Subtarget.useCRBits()) {
1123     setTargetDAGCombine(ISD::TRUNCATE);
1124     setTargetDAGCombine(ISD::SETCC);
1125     setTargetDAGCombine(ISD::SELECT_CC);
1126   }
1127 
1128   // Use reciprocal estimates.
1129   if (TM.Options.UnsafeFPMath) {
1130     setTargetDAGCombine(ISD::FDIV);
1131     setTargetDAGCombine(ISD::FSQRT);
1132   }
1133 
1134   if (Subtarget.hasP9Altivec()) {
1135     setTargetDAGCombine(ISD::ABS);
1136     setTargetDAGCombine(ISD::VSELECT);
1137   }
1138 
1139   // Darwin long double math library functions have $LDBL128 appended.
1140   if (Subtarget.isDarwin()) {
1141     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1142     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1143     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1144     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1145     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1146     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1147     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1148     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1149     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1150     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1151   }
1152 
1153   if (EnableQuadPrecision) {
1154     setLibcallName(RTLIB::LOG_F128, "logf128");
1155     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1156     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1157     setLibcallName(RTLIB::EXP_F128, "expf128");
1158     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1159     setLibcallName(RTLIB::SIN_F128, "sinf128");
1160     setLibcallName(RTLIB::COS_F128, "cosf128");
1161     setLibcallName(RTLIB::POW_F128, "powf128");
1162     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1163     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1164     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1165     setLibcallName(RTLIB::REM_F128, "fmodf128");
1166   }
1167 
1168   // With 32 condition bits, we don't need to sink (and duplicate) compares
1169   // aggressively in CodeGenPrep.
1170   if (Subtarget.useCRBits()) {
1171     setHasMultipleConditionRegisters();
1172     setJumpIsExpensive();
1173   }
1174 
1175   setMinFunctionAlignment(2);
1176   if (Subtarget.isDarwin())
1177     setPrefFunctionAlignment(4);
1178 
1179   switch (Subtarget.getDarwinDirective()) {
1180   default: break;
1181   case PPC::DIR_970:
1182   case PPC::DIR_A2:
1183   case PPC::DIR_E500:
1184   case PPC::DIR_E500mc:
1185   case PPC::DIR_E5500:
1186   case PPC::DIR_PWR4:
1187   case PPC::DIR_PWR5:
1188   case PPC::DIR_PWR5X:
1189   case PPC::DIR_PWR6:
1190   case PPC::DIR_PWR6X:
1191   case PPC::DIR_PWR7:
1192   case PPC::DIR_PWR8:
1193   case PPC::DIR_PWR9:
1194     setPrefFunctionAlignment(4);
1195     setPrefLoopAlignment(4);
1196     break;
1197   }
1198 
1199   if (Subtarget.enableMachineScheduler())
1200     setSchedulingPreference(Sched::Source);
1201   else
1202     setSchedulingPreference(Sched::Hybrid);
1203 
1204   computeRegisterProperties(STI.getRegisterInfo());
1205 
1206   // The Freescale cores do better with aggressive inlining of memcpy and
1207   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1208   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1209       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1210     MaxStoresPerMemset = 32;
1211     MaxStoresPerMemsetOptSize = 16;
1212     MaxStoresPerMemcpy = 32;
1213     MaxStoresPerMemcpyOptSize = 8;
1214     MaxStoresPerMemmove = 32;
1215     MaxStoresPerMemmoveOptSize = 8;
1216   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1217     // The A2 also benefits from (very) aggressive inlining of memcpy and
1218     // friends. The overhead of a the function call, even when warm, can be
1219     // over one hundred cycles.
1220     MaxStoresPerMemset = 128;
1221     MaxStoresPerMemcpy = 128;
1222     MaxStoresPerMemmove = 128;
1223     MaxLoadsPerMemcmp = 128;
1224   } else {
1225     MaxLoadsPerMemcmp = 8;
1226     MaxLoadsPerMemcmpOptSize = 4;
1227   }
1228 }
1229 
1230 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1231 /// the desired ByVal argument alignment.
1232 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1233                              unsigned MaxMaxAlign) {
1234   if (MaxAlign == MaxMaxAlign)
1235     return;
1236   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1237     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1238       MaxAlign = 32;
1239     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1240       MaxAlign = 16;
1241   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1242     unsigned EltAlign = 0;
1243     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1244     if (EltAlign > MaxAlign)
1245       MaxAlign = EltAlign;
1246   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1247     for (auto *EltTy : STy->elements()) {
1248       unsigned EltAlign = 0;
1249       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1250       if (EltAlign > MaxAlign)
1251         MaxAlign = EltAlign;
1252       if (MaxAlign == MaxMaxAlign)
1253         break;
1254     }
1255   }
1256 }
1257 
1258 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1259 /// function arguments in the caller parameter area.
1260 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1261                                                   const DataLayout &DL) const {
1262   // Darwin passes everything on 4 byte boundary.
1263   if (Subtarget.isDarwin())
1264     return 4;
1265 
1266   // 16byte and wider vectors are passed on 16byte boundary.
1267   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1268   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1269   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1270     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1271   return Align;
1272 }
1273 
1274 bool PPCTargetLowering::useSoftFloat() const {
1275   return Subtarget.useSoftFloat();
1276 }
1277 
1278 bool PPCTargetLowering::hasSPE() const {
1279   return Subtarget.hasSPE();
1280 }
1281 
1282 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1283   return VT.isScalarInteger();
1284 }
1285 
1286 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1287   switch ((PPCISD::NodeType)Opcode) {
1288   case PPCISD::FIRST_NUMBER:    break;
1289   case PPCISD::FSEL:            return "PPCISD::FSEL";
1290   case PPCISD::FCFID:           return "PPCISD::FCFID";
1291   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1292   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1293   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1294   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1295   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1296   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1297   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1298   case PPCISD::FP_TO_UINT_IN_VSR:
1299                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1300   case PPCISD::FP_TO_SINT_IN_VSR:
1301                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1302   case PPCISD::FRE:             return "PPCISD::FRE";
1303   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1304   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1305   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1306   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1307   case PPCISD::VPERM:           return "PPCISD::VPERM";
1308   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1309   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1310   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1311   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1312   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1313   case PPCISD::CMPB:            return "PPCISD::CMPB";
1314   case PPCISD::Hi:              return "PPCISD::Hi";
1315   case PPCISD::Lo:              return "PPCISD::Lo";
1316   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1317   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1318   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1319   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1320   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1321   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1322   case PPCISD::SRL:             return "PPCISD::SRL";
1323   case PPCISD::SRA:             return "PPCISD::SRA";
1324   case PPCISD::SHL:             return "PPCISD::SHL";
1325   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1326   case PPCISD::CALL:            return "PPCISD::CALL";
1327   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1328   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1329   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1330   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1331   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1332   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1333   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1334   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1335   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1336   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1337   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1338   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1339   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1340   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1341   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1342   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1343   case PPCISD::VCMP:            return "PPCISD::VCMP";
1344   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1345   case PPCISD::LBRX:            return "PPCISD::LBRX";
1346   case PPCISD::STBRX:           return "PPCISD::STBRX";
1347   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1348   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1349   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1350   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1351   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1352   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1353   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1354   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1355   case PPCISD::ST_VSR_SCAL_INT:
1356                                 return "PPCISD::ST_VSR_SCAL_INT";
1357   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1358   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1359   case PPCISD::BDZ:             return "PPCISD::BDZ";
1360   case PPCISD::MFFS:            return "PPCISD::MFFS";
1361   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1362   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1363   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1364   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1365   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1366   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1367   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1368   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1369   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1370   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1371   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1372   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1373   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1374   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1375   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1376   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1377   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1378   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1379   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1380   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1381   case PPCISD::SC:              return "PPCISD::SC";
1382   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1383   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1384   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1385   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1386   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1387   case PPCISD::VABSD:           return "PPCISD::VABSD";
1388   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1389   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1390   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1391   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1392   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1393   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1394   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1395   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1396   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1397   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1398   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1399   case PPCISD::FP_EXTEND_LH:    return "PPCISD::FP_EXTEND_LH";
1400   }
1401   return nullptr;
1402 }
1403 
1404 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1405                                           EVT VT) const {
1406   if (!VT.isVector())
1407     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1408 
1409   if (Subtarget.hasQPX())
1410     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1411 
1412   return VT.changeVectorElementTypeToInteger();
1413 }
1414 
1415 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1416   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1417   return true;
1418 }
1419 
1420 //===----------------------------------------------------------------------===//
1421 // Node matching predicates, for use by the tblgen matching code.
1422 //===----------------------------------------------------------------------===//
1423 
1424 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1425 static bool isFloatingPointZero(SDValue Op) {
1426   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1427     return CFP->getValueAPF().isZero();
1428   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1429     // Maybe this has already been legalized into the constant pool?
1430     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1431       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1432         return CFP->getValueAPF().isZero();
1433   }
1434   return false;
1435 }
1436 
1437 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1438 /// true if Op is undef or if it matches the specified value.
1439 static bool isConstantOrUndef(int Op, int Val) {
1440   return Op < 0 || Op == Val;
1441 }
1442 
1443 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1444 /// VPKUHUM instruction.
1445 /// The ShuffleKind distinguishes between big-endian operations with
1446 /// two different inputs (0), either-endian operations with two identical
1447 /// inputs (1), and little-endian operations with two different inputs (2).
1448 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1449 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1450                                SelectionDAG &DAG) {
1451   bool IsLE = DAG.getDataLayout().isLittleEndian();
1452   if (ShuffleKind == 0) {
1453     if (IsLE)
1454       return false;
1455     for (unsigned i = 0; i != 16; ++i)
1456       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1457         return false;
1458   } else if (ShuffleKind == 2) {
1459     if (!IsLE)
1460       return false;
1461     for (unsigned i = 0; i != 16; ++i)
1462       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1463         return false;
1464   } else if (ShuffleKind == 1) {
1465     unsigned j = IsLE ? 0 : 1;
1466     for (unsigned i = 0; i != 8; ++i)
1467       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1468           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1469         return false;
1470   }
1471   return true;
1472 }
1473 
1474 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1475 /// VPKUWUM instruction.
1476 /// The ShuffleKind distinguishes between big-endian operations with
1477 /// two different inputs (0), either-endian operations with two identical
1478 /// inputs (1), and little-endian operations with two different inputs (2).
1479 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1480 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1481                                SelectionDAG &DAG) {
1482   bool IsLE = DAG.getDataLayout().isLittleEndian();
1483   if (ShuffleKind == 0) {
1484     if (IsLE)
1485       return false;
1486     for (unsigned i = 0; i != 16; i += 2)
1487       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1488           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1489         return false;
1490   } else if (ShuffleKind == 2) {
1491     if (!IsLE)
1492       return false;
1493     for (unsigned i = 0; i != 16; i += 2)
1494       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1495           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1496         return false;
1497   } else if (ShuffleKind == 1) {
1498     unsigned j = IsLE ? 0 : 2;
1499     for (unsigned i = 0; i != 8; i += 2)
1500       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1501           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1502           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1503           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1504         return false;
1505   }
1506   return true;
1507 }
1508 
1509 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1510 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1511 /// current subtarget.
1512 ///
1513 /// The ShuffleKind distinguishes between big-endian operations with
1514 /// two different inputs (0), either-endian operations with two identical
1515 /// inputs (1), and little-endian operations with two different inputs (2).
1516 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1517 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1518                                SelectionDAG &DAG) {
1519   const PPCSubtarget& Subtarget =
1520     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1521   if (!Subtarget.hasP8Vector())
1522     return false;
1523 
1524   bool IsLE = DAG.getDataLayout().isLittleEndian();
1525   if (ShuffleKind == 0) {
1526     if (IsLE)
1527       return false;
1528     for (unsigned i = 0; i != 16; i += 4)
1529       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1530           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1531           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1532           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1533         return false;
1534   } else if (ShuffleKind == 2) {
1535     if (!IsLE)
1536       return false;
1537     for (unsigned i = 0; i != 16; i += 4)
1538       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1539           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1540           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1541           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1542         return false;
1543   } else if (ShuffleKind == 1) {
1544     unsigned j = IsLE ? 0 : 4;
1545     for (unsigned i = 0; i != 8; i += 4)
1546       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1547           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1548           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1549           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1550           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1551           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1552           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1553           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1554         return false;
1555   }
1556   return true;
1557 }
1558 
1559 /// isVMerge - Common function, used to match vmrg* shuffles.
1560 ///
1561 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1562                      unsigned LHSStart, unsigned RHSStart) {
1563   if (N->getValueType(0) != MVT::v16i8)
1564     return false;
1565   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1566          "Unsupported merge size!");
1567 
1568   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1569     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1570       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1571                              LHSStart+j+i*UnitSize) ||
1572           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1573                              RHSStart+j+i*UnitSize))
1574         return false;
1575     }
1576   return true;
1577 }
1578 
1579 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1580 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1581 /// The ShuffleKind distinguishes between big-endian merges with two
1582 /// different inputs (0), either-endian merges with two identical inputs (1),
1583 /// and little-endian merges with two different inputs (2).  For the latter,
1584 /// the input operands are swapped (see PPCInstrAltivec.td).
1585 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1586                              unsigned ShuffleKind, SelectionDAG &DAG) {
1587   if (DAG.getDataLayout().isLittleEndian()) {
1588     if (ShuffleKind == 1) // unary
1589       return isVMerge(N, UnitSize, 0, 0);
1590     else if (ShuffleKind == 2) // swapped
1591       return isVMerge(N, UnitSize, 0, 16);
1592     else
1593       return false;
1594   } else {
1595     if (ShuffleKind == 1) // unary
1596       return isVMerge(N, UnitSize, 8, 8);
1597     else if (ShuffleKind == 0) // normal
1598       return isVMerge(N, UnitSize, 8, 24);
1599     else
1600       return false;
1601   }
1602 }
1603 
1604 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1605 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1606 /// The ShuffleKind distinguishes between big-endian merges with two
1607 /// different inputs (0), either-endian merges with two identical inputs (1),
1608 /// and little-endian merges with two different inputs (2).  For the latter,
1609 /// the input operands are swapped (see PPCInstrAltivec.td).
1610 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1611                              unsigned ShuffleKind, SelectionDAG &DAG) {
1612   if (DAG.getDataLayout().isLittleEndian()) {
1613     if (ShuffleKind == 1) // unary
1614       return isVMerge(N, UnitSize, 8, 8);
1615     else if (ShuffleKind == 2) // swapped
1616       return isVMerge(N, UnitSize, 8, 24);
1617     else
1618       return false;
1619   } else {
1620     if (ShuffleKind == 1) // unary
1621       return isVMerge(N, UnitSize, 0, 0);
1622     else if (ShuffleKind == 0) // normal
1623       return isVMerge(N, UnitSize, 0, 16);
1624     else
1625       return false;
1626   }
1627 }
1628 
1629 /**
1630  * Common function used to match vmrgew and vmrgow shuffles
1631  *
1632  * The indexOffset determines whether to look for even or odd words in
1633  * the shuffle mask. This is based on the of the endianness of the target
1634  * machine.
1635  *   - Little Endian:
1636  *     - Use offset of 0 to check for odd elements
1637  *     - Use offset of 4 to check for even elements
1638  *   - Big Endian:
1639  *     - Use offset of 0 to check for even elements
1640  *     - Use offset of 4 to check for odd elements
1641  * A detailed description of the vector element ordering for little endian and
1642  * big endian can be found at
1643  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1644  * Targeting your applications - what little endian and big endian IBM XL C/C++
1645  * compiler differences mean to you
1646  *
1647  * The mask to the shuffle vector instruction specifies the indices of the
1648  * elements from the two input vectors to place in the result. The elements are
1649  * numbered in array-access order, starting with the first vector. These vectors
1650  * are always of type v16i8, thus each vector will contain 16 elements of size
1651  * 8. More info on the shuffle vector can be found in the
1652  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1653  * Language Reference.
1654  *
1655  * The RHSStartValue indicates whether the same input vectors are used (unary)
1656  * or two different input vectors are used, based on the following:
1657  *   - If the instruction uses the same vector for both inputs, the range of the
1658  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1659  *     be 0.
1660  *   - If the instruction has two different vectors then the range of the
1661  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1662  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1663  *     to 31 specify elements in the second vector).
1664  *
1665  * \param[in] N The shuffle vector SD Node to analyze
1666  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1667  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1668  * vector to the shuffle_vector instruction
1669  * \return true iff this shuffle vector represents an even or odd word merge
1670  */
1671 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1672                      unsigned RHSStartValue) {
1673   if (N->getValueType(0) != MVT::v16i8)
1674     return false;
1675 
1676   for (unsigned i = 0; i < 2; ++i)
1677     for (unsigned j = 0; j < 4; ++j)
1678       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1679                              i*RHSStartValue+j+IndexOffset) ||
1680           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1681                              i*RHSStartValue+j+IndexOffset+8))
1682         return false;
1683   return true;
1684 }
1685 
1686 /**
1687  * Determine if the specified shuffle mask is suitable for the vmrgew or
1688  * vmrgow instructions.
1689  *
1690  * \param[in] N The shuffle vector SD Node to analyze
1691  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1692  * \param[in] ShuffleKind Identify the type of merge:
1693  *   - 0 = big-endian merge with two different inputs;
1694  *   - 1 = either-endian merge with two identical inputs;
1695  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1696  *     little-endian merges).
1697  * \param[in] DAG The current SelectionDAG
1698  * \return true iff this shuffle mask
1699  */
1700 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1701                               unsigned ShuffleKind, SelectionDAG &DAG) {
1702   if (DAG.getDataLayout().isLittleEndian()) {
1703     unsigned indexOffset = CheckEven ? 4 : 0;
1704     if (ShuffleKind == 1) // Unary
1705       return isVMerge(N, indexOffset, 0);
1706     else if (ShuffleKind == 2) // swapped
1707       return isVMerge(N, indexOffset, 16);
1708     else
1709       return false;
1710   }
1711   else {
1712     unsigned indexOffset = CheckEven ? 0 : 4;
1713     if (ShuffleKind == 1) // Unary
1714       return isVMerge(N, indexOffset, 0);
1715     else if (ShuffleKind == 0) // Normal
1716       return isVMerge(N, indexOffset, 16);
1717     else
1718       return false;
1719   }
1720   return false;
1721 }
1722 
1723 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1724 /// amount, otherwise return -1.
1725 /// The ShuffleKind distinguishes between big-endian operations with two
1726 /// different inputs (0), either-endian operations with two identical inputs
1727 /// (1), and little-endian operations with two different inputs (2).  For the
1728 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1729 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1730                              SelectionDAG &DAG) {
1731   if (N->getValueType(0) != MVT::v16i8)
1732     return -1;
1733 
1734   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1735 
1736   // Find the first non-undef value in the shuffle mask.
1737   unsigned i;
1738   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1739     /*search*/;
1740 
1741   if (i == 16) return -1;  // all undef.
1742 
1743   // Otherwise, check to see if the rest of the elements are consecutively
1744   // numbered from this value.
1745   unsigned ShiftAmt = SVOp->getMaskElt(i);
1746   if (ShiftAmt < i) return -1;
1747 
1748   ShiftAmt -= i;
1749   bool isLE = DAG.getDataLayout().isLittleEndian();
1750 
1751   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1752     // Check the rest of the elements to see if they are consecutive.
1753     for (++i; i != 16; ++i)
1754       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1755         return -1;
1756   } else if (ShuffleKind == 1) {
1757     // Check the rest of the elements to see if they are consecutive.
1758     for (++i; i != 16; ++i)
1759       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1760         return -1;
1761   } else
1762     return -1;
1763 
1764   if (isLE)
1765     ShiftAmt = 16 - ShiftAmt;
1766 
1767   return ShiftAmt;
1768 }
1769 
1770 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1771 /// specifies a splat of a single element that is suitable for input to
1772 /// VSPLTB/VSPLTH/VSPLTW.
1773 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1774   assert(N->getValueType(0) == MVT::v16i8 &&
1775          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1776 
1777   // The consecutive indices need to specify an element, not part of two
1778   // different elements.  So abandon ship early if this isn't the case.
1779   if (N->getMaskElt(0) % EltSize != 0)
1780     return false;
1781 
1782   // This is a splat operation if each element of the permute is the same, and
1783   // if the value doesn't reference the second vector.
1784   unsigned ElementBase = N->getMaskElt(0);
1785 
1786   // FIXME: Handle UNDEF elements too!
1787   if (ElementBase >= 16)
1788     return false;
1789 
1790   // Check that the indices are consecutive, in the case of a multi-byte element
1791   // splatted with a v16i8 mask.
1792   for (unsigned i = 1; i != EltSize; ++i)
1793     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1794       return false;
1795 
1796   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1797     if (N->getMaskElt(i) < 0) continue;
1798     for (unsigned j = 0; j != EltSize; ++j)
1799       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1800         return false;
1801   }
1802   return true;
1803 }
1804 
1805 /// Check that the mask is shuffling N byte elements. Within each N byte
1806 /// element of the mask, the indices could be either in increasing or
1807 /// decreasing order as long as they are consecutive.
1808 /// \param[in] N the shuffle vector SD Node to analyze
1809 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1810 /// Word/DoubleWord/QuadWord).
1811 /// \param[in] StepLen the delta indices number among the N byte element, if
1812 /// the mask is in increasing/decreasing order then it is 1/-1.
1813 /// \return true iff the mask is shuffling N byte elements.
1814 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1815                                    int StepLen) {
1816   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1817          "Unexpected element width.");
1818   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1819 
1820   unsigned NumOfElem = 16 / Width;
1821   unsigned MaskVal[16]; //  Width is never greater than 16
1822   for (unsigned i = 0; i < NumOfElem; ++i) {
1823     MaskVal[0] = N->getMaskElt(i * Width);
1824     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1825       return false;
1826     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1827       return false;
1828     }
1829 
1830     for (unsigned int j = 1; j < Width; ++j) {
1831       MaskVal[j] = N->getMaskElt(i * Width + j);
1832       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1833         return false;
1834       }
1835     }
1836   }
1837 
1838   return true;
1839 }
1840 
1841 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1842                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1843   if (!isNByteElemShuffleMask(N, 4, 1))
1844     return false;
1845 
1846   // Now we look at mask elements 0,4,8,12
1847   unsigned M0 = N->getMaskElt(0) / 4;
1848   unsigned M1 = N->getMaskElt(4) / 4;
1849   unsigned M2 = N->getMaskElt(8) / 4;
1850   unsigned M3 = N->getMaskElt(12) / 4;
1851   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1852   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1853 
1854   // Below, let H and L be arbitrary elements of the shuffle mask
1855   // where H is in the range [4,7] and L is in the range [0,3].
1856   // H, 1, 2, 3 or L, 5, 6, 7
1857   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1858       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1859     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1860     InsertAtByte = IsLE ? 12 : 0;
1861     Swap = M0 < 4;
1862     return true;
1863   }
1864   // 0, H, 2, 3 or 4, L, 6, 7
1865   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1866       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1867     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1868     InsertAtByte = IsLE ? 8 : 4;
1869     Swap = M1 < 4;
1870     return true;
1871   }
1872   // 0, 1, H, 3 or 4, 5, L, 7
1873   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1874       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1875     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1876     InsertAtByte = IsLE ? 4 : 8;
1877     Swap = M2 < 4;
1878     return true;
1879   }
1880   // 0, 1, 2, H or 4, 5, 6, L
1881   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1882       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1883     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1884     InsertAtByte = IsLE ? 0 : 12;
1885     Swap = M3 < 4;
1886     return true;
1887   }
1888 
1889   // If both vector operands for the shuffle are the same vector, the mask will
1890   // contain only elements from the first one and the second one will be undef.
1891   if (N->getOperand(1).isUndef()) {
1892     ShiftElts = 0;
1893     Swap = true;
1894     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1895     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1896       InsertAtByte = IsLE ? 12 : 0;
1897       return true;
1898     }
1899     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1900       InsertAtByte = IsLE ? 8 : 4;
1901       return true;
1902     }
1903     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1904       InsertAtByte = IsLE ? 4 : 8;
1905       return true;
1906     }
1907     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1908       InsertAtByte = IsLE ? 0 : 12;
1909       return true;
1910     }
1911   }
1912 
1913   return false;
1914 }
1915 
1916 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1917                                bool &Swap, bool IsLE) {
1918   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1919   // Ensure each byte index of the word is consecutive.
1920   if (!isNByteElemShuffleMask(N, 4, 1))
1921     return false;
1922 
1923   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1924   unsigned M0 = N->getMaskElt(0) / 4;
1925   unsigned M1 = N->getMaskElt(4) / 4;
1926   unsigned M2 = N->getMaskElt(8) / 4;
1927   unsigned M3 = N->getMaskElt(12) / 4;
1928 
1929   // If both vector operands for the shuffle are the same vector, the mask will
1930   // contain only elements from the first one and the second one will be undef.
1931   if (N->getOperand(1).isUndef()) {
1932     assert(M0 < 4 && "Indexing into an undef vector?");
1933     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1934       return false;
1935 
1936     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1937     Swap = false;
1938     return true;
1939   }
1940 
1941   // Ensure each word index of the ShuffleVector Mask is consecutive.
1942   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1943     return false;
1944 
1945   if (IsLE) {
1946     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1947       // Input vectors don't need to be swapped if the leading element
1948       // of the result is one of the 3 left elements of the second vector
1949       // (or if there is no shift to be done at all).
1950       Swap = false;
1951       ShiftElts = (8 - M0) % 8;
1952     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1953       // Input vectors need to be swapped if the leading element
1954       // of the result is one of the 3 left elements of the first vector
1955       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1956       Swap = true;
1957       ShiftElts = (4 - M0) % 4;
1958     }
1959 
1960     return true;
1961   } else {                                          // BE
1962     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1963       // Input vectors don't need to be swapped if the leading element
1964       // of the result is one of the 4 elements of the first vector.
1965       Swap = false;
1966       ShiftElts = M0;
1967     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1968       // Input vectors need to be swapped if the leading element
1969       // of the result is one of the 4 elements of the right vector.
1970       Swap = true;
1971       ShiftElts = M0 - 4;
1972     }
1973 
1974     return true;
1975   }
1976 }
1977 
1978 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1979   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1980 
1981   if (!isNByteElemShuffleMask(N, Width, -1))
1982     return false;
1983 
1984   for (int i = 0; i < 16; i += Width)
1985     if (N->getMaskElt(i) != i + Width - 1)
1986       return false;
1987 
1988   return true;
1989 }
1990 
1991 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1992   return isXXBRShuffleMaskHelper(N, 2);
1993 }
1994 
1995 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
1996   return isXXBRShuffleMaskHelper(N, 4);
1997 }
1998 
1999 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2000   return isXXBRShuffleMaskHelper(N, 8);
2001 }
2002 
2003 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2004   return isXXBRShuffleMaskHelper(N, 16);
2005 }
2006 
2007 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2008 /// if the inputs to the instruction should be swapped and set \p DM to the
2009 /// value for the immediate.
2010 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2011 /// AND element 0 of the result comes from the first input (LE) or second input
2012 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2013 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2014 /// mask.
2015 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2016                                bool &Swap, bool IsLE) {
2017   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2018 
2019   // Ensure each byte index of the double word is consecutive.
2020   if (!isNByteElemShuffleMask(N, 8, 1))
2021     return false;
2022 
2023   unsigned M0 = N->getMaskElt(0) / 8;
2024   unsigned M1 = N->getMaskElt(8) / 8;
2025   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2026 
2027   // If both vector operands for the shuffle are the same vector, the mask will
2028   // contain only elements from the first one and the second one will be undef.
2029   if (N->getOperand(1).isUndef()) {
2030     if ((M0 | M1) < 2) {
2031       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2032       Swap = false;
2033       return true;
2034     } else
2035       return false;
2036   }
2037 
2038   if (IsLE) {
2039     if (M0 > 1 && M1 < 2) {
2040       Swap = false;
2041     } else if (M0 < 2 && M1 > 1) {
2042       M0 = (M0 + 2) % 4;
2043       M1 = (M1 + 2) % 4;
2044       Swap = true;
2045     } else
2046       return false;
2047 
2048     // Note: if control flow comes here that means Swap is already set above
2049     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2050     return true;
2051   } else { // BE
2052     if (M0 < 2 && M1 > 1) {
2053       Swap = false;
2054     } else if (M0 > 1 && M1 < 2) {
2055       M0 = (M0 + 2) % 4;
2056       M1 = (M1 + 2) % 4;
2057       Swap = true;
2058     } else
2059       return false;
2060 
2061     // Note: if control flow comes here that means Swap is already set above
2062     DM = (M0 << 1) + (M1 & 1);
2063     return true;
2064   }
2065 }
2066 
2067 
2068 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
2069 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
2070 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
2071                                 SelectionDAG &DAG) {
2072   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2073   assert(isSplatShuffleMask(SVOp, EltSize));
2074   if (DAG.getDataLayout().isLittleEndian())
2075     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2076   else
2077     return SVOp->getMaskElt(0) / EltSize;
2078 }
2079 
2080 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2081 /// by using a vspltis[bhw] instruction of the specified element size, return
2082 /// the constant being splatted.  The ByteSize field indicates the number of
2083 /// bytes of each element [124] -> [bhw].
2084 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2085   SDValue OpVal(nullptr, 0);
2086 
2087   // If ByteSize of the splat is bigger than the element size of the
2088   // build_vector, then we have a case where we are checking for a splat where
2089   // multiple elements of the buildvector are folded together into a single
2090   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2091   unsigned EltSize = 16/N->getNumOperands();
2092   if (EltSize < ByteSize) {
2093     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2094     SDValue UniquedVals[4];
2095     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2096 
2097     // See if all of the elements in the buildvector agree across.
2098     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2099       if (N->getOperand(i).isUndef()) continue;
2100       // If the element isn't a constant, bail fully out.
2101       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2102 
2103       if (!UniquedVals[i&(Multiple-1)].getNode())
2104         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2105       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2106         return SDValue();  // no match.
2107     }
2108 
2109     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2110     // either constant or undef values that are identical for each chunk.  See
2111     // if these chunks can form into a larger vspltis*.
2112 
2113     // Check to see if all of the leading entries are either 0 or -1.  If
2114     // neither, then this won't fit into the immediate field.
2115     bool LeadingZero = true;
2116     bool LeadingOnes = true;
2117     for (unsigned i = 0; i != Multiple-1; ++i) {
2118       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2119 
2120       LeadingZero &= isNullConstant(UniquedVals[i]);
2121       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2122     }
2123     // Finally, check the least significant entry.
2124     if (LeadingZero) {
2125       if (!UniquedVals[Multiple-1].getNode())
2126         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2127       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2128       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2129         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2130     }
2131     if (LeadingOnes) {
2132       if (!UniquedVals[Multiple-1].getNode())
2133         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2134       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2135       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2136         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2137     }
2138 
2139     return SDValue();
2140   }
2141 
2142   // Check to see if this buildvec has a single non-undef value in its elements.
2143   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2144     if (N->getOperand(i).isUndef()) continue;
2145     if (!OpVal.getNode())
2146       OpVal = N->getOperand(i);
2147     else if (OpVal != N->getOperand(i))
2148       return SDValue();
2149   }
2150 
2151   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2152 
2153   unsigned ValSizeInBytes = EltSize;
2154   uint64_t Value = 0;
2155   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2156     Value = CN->getZExtValue();
2157   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2158     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2159     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2160   }
2161 
2162   // If the splat value is larger than the element value, then we can never do
2163   // this splat.  The only case that we could fit the replicated bits into our
2164   // immediate field for would be zero, and we prefer to use vxor for it.
2165   if (ValSizeInBytes < ByteSize) return SDValue();
2166 
2167   // If the element value is larger than the splat value, check if it consists
2168   // of a repeated bit pattern of size ByteSize.
2169   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2170     return SDValue();
2171 
2172   // Properly sign extend the value.
2173   int MaskVal = SignExtend32(Value, ByteSize * 8);
2174 
2175   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2176   if (MaskVal == 0) return SDValue();
2177 
2178   // Finally, if this value fits in a 5 bit sext field, return it
2179   if (SignExtend32<5>(MaskVal) == MaskVal)
2180     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2181   return SDValue();
2182 }
2183 
2184 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2185 /// amount, otherwise return -1.
2186 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2187   EVT VT = N->getValueType(0);
2188   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2189     return -1;
2190 
2191   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2192 
2193   // Find the first non-undef value in the shuffle mask.
2194   unsigned i;
2195   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2196     /*search*/;
2197 
2198   if (i == 4) return -1;  // all undef.
2199 
2200   // Otherwise, check to see if the rest of the elements are consecutively
2201   // numbered from this value.
2202   unsigned ShiftAmt = SVOp->getMaskElt(i);
2203   if (ShiftAmt < i) return -1;
2204   ShiftAmt -= i;
2205 
2206   // Check the rest of the elements to see if they are consecutive.
2207   for (++i; i != 4; ++i)
2208     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2209       return -1;
2210 
2211   return ShiftAmt;
2212 }
2213 
2214 //===----------------------------------------------------------------------===//
2215 //  Addressing Mode Selection
2216 //===----------------------------------------------------------------------===//
2217 
2218 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2219 /// or 64-bit immediate, and if the value can be accurately represented as a
2220 /// sign extension from a 16-bit value.  If so, this returns true and the
2221 /// immediate.
2222 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2223   if (!isa<ConstantSDNode>(N))
2224     return false;
2225 
2226   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2227   if (N->getValueType(0) == MVT::i32)
2228     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2229   else
2230     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2231 }
2232 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2233   return isIntS16Immediate(Op.getNode(), Imm);
2234 }
2235 
2236 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2237 /// can be represented as an indexed [r+r] operation.  Returns false if it
2238 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2239 /// non-zero and N can be represented by a base register plus a signed 16-bit
2240 /// displacement, make a more precise judgement by checking (displacement % \p
2241 /// EncodingAlignment).
2242 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2243                                             SDValue &Index, SelectionDAG &DAG,
2244                                             unsigned EncodingAlignment) const {
2245   int16_t imm = 0;
2246   if (N.getOpcode() == ISD::ADD) {
2247     if (isIntS16Immediate(N.getOperand(1), imm) &&
2248         (!EncodingAlignment || !(imm % EncodingAlignment)))
2249       return false; // r+i
2250     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2251       return false;    // r+i
2252 
2253     Base = N.getOperand(0);
2254     Index = N.getOperand(1);
2255     return true;
2256   } else if (N.getOpcode() == ISD::OR) {
2257     if (isIntS16Immediate(N.getOperand(1), imm) &&
2258         (!EncodingAlignment || !(imm % EncodingAlignment)))
2259       return false; // r+i can fold it if we can.
2260 
2261     // If this is an or of disjoint bitfields, we can codegen this as an add
2262     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2263     // disjoint.
2264     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2265 
2266     if (LHSKnown.Zero.getBoolValue()) {
2267       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2268       // If all of the bits are known zero on the LHS or RHS, the add won't
2269       // carry.
2270       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2271         Base = N.getOperand(0);
2272         Index = N.getOperand(1);
2273         return true;
2274       }
2275     }
2276   }
2277 
2278   return false;
2279 }
2280 
2281 // If we happen to be doing an i64 load or store into a stack slot that has
2282 // less than a 4-byte alignment, then the frame-index elimination may need to
2283 // use an indexed load or store instruction (because the offset may not be a
2284 // multiple of 4). The extra register needed to hold the offset comes from the
2285 // register scavenger, and it is possible that the scavenger will need to use
2286 // an emergency spill slot. As a result, we need to make sure that a spill slot
2287 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2288 // stack slot.
2289 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2290   // FIXME: This does not handle the LWA case.
2291   if (VT != MVT::i64)
2292     return;
2293 
2294   // NOTE: We'll exclude negative FIs here, which come from argument
2295   // lowering, because there are no known test cases triggering this problem
2296   // using packed structures (or similar). We can remove this exclusion if
2297   // we find such a test case. The reason why this is so test-case driven is
2298   // because this entire 'fixup' is only to prevent crashes (from the
2299   // register scavenger) on not-really-valid inputs. For example, if we have:
2300   //   %a = alloca i1
2301   //   %b = bitcast i1* %a to i64*
2302   //   store i64* a, i64 b
2303   // then the store should really be marked as 'align 1', but is not. If it
2304   // were marked as 'align 1' then the indexed form would have been
2305   // instruction-selected initially, and the problem this 'fixup' is preventing
2306   // won't happen regardless.
2307   if (FrameIdx < 0)
2308     return;
2309 
2310   MachineFunction &MF = DAG.getMachineFunction();
2311   MachineFrameInfo &MFI = MF.getFrameInfo();
2312 
2313   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2314   if (Align >= 4)
2315     return;
2316 
2317   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2318   FuncInfo->setHasNonRISpills();
2319 }
2320 
2321 /// Returns true if the address N can be represented by a base register plus
2322 /// a signed 16-bit displacement [r+imm], and if it is not better
2323 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2324 /// displacements that are multiples of that value.
2325 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2326                                             SDValue &Base,
2327                                             SelectionDAG &DAG,
2328                                             unsigned EncodingAlignment) const {
2329   // FIXME dl should come from parent load or store, not from address
2330   SDLoc dl(N);
2331   // If this can be more profitably realized as r+r, fail.
2332   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2333     return false;
2334 
2335   if (N.getOpcode() == ISD::ADD) {
2336     int16_t imm = 0;
2337     if (isIntS16Immediate(N.getOperand(1), imm) &&
2338         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2339       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2340       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2341         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2342         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2343       } else {
2344         Base = N.getOperand(0);
2345       }
2346       return true; // [r+i]
2347     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2348       // Match LOAD (ADD (X, Lo(G))).
2349       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2350              && "Cannot handle constant offsets yet!");
2351       Disp = N.getOperand(1).getOperand(0);  // The global address.
2352       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2353              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2354              Disp.getOpcode() == ISD::TargetConstantPool ||
2355              Disp.getOpcode() == ISD::TargetJumpTable);
2356       Base = N.getOperand(0);
2357       return true;  // [&g+r]
2358     }
2359   } else if (N.getOpcode() == ISD::OR) {
2360     int16_t imm = 0;
2361     if (isIntS16Immediate(N.getOperand(1), imm) &&
2362         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2363       // If this is an or of disjoint bitfields, we can codegen this as an add
2364       // (for better address arithmetic) if the LHS and RHS of the OR are
2365       // provably disjoint.
2366       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2367 
2368       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2369         // If all of the bits are known zero on the LHS or RHS, the add won't
2370         // carry.
2371         if (FrameIndexSDNode *FI =
2372               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2373           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2374           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2375         } else {
2376           Base = N.getOperand(0);
2377         }
2378         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2379         return true;
2380       }
2381     }
2382   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2383     // Loading from a constant address.
2384 
2385     // If this address fits entirely in a 16-bit sext immediate field, codegen
2386     // this as "d, 0"
2387     int16_t Imm;
2388     if (isIntS16Immediate(CN, Imm) &&
2389         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2390       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2391       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2392                              CN->getValueType(0));
2393       return true;
2394     }
2395 
2396     // Handle 32-bit sext immediates with LIS + addr mode.
2397     if ((CN->getValueType(0) == MVT::i32 ||
2398          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2399         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2400       int Addr = (int)CN->getZExtValue();
2401 
2402       // Otherwise, break this down into an LIS + disp.
2403       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2404 
2405       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2406                                    MVT::i32);
2407       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2408       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2409       return true;
2410     }
2411   }
2412 
2413   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2414   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2415     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2416     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2417   } else
2418     Base = N;
2419   return true;      // [r+0]
2420 }
2421 
2422 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2423 /// represented as an indexed [r+r] operation.
2424 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2425                                                 SDValue &Index,
2426                                                 SelectionDAG &DAG) const {
2427   // Check to see if we can easily represent this as an [r+r] address.  This
2428   // will fail if it thinks that the address is more profitably represented as
2429   // reg+imm, e.g. where imm = 0.
2430   if (SelectAddressRegReg(N, Base, Index, DAG))
2431     return true;
2432 
2433   // If the address is the result of an add, we will utilize the fact that the
2434   // address calculation includes an implicit add.  However, we can reduce
2435   // register pressure if we do not materialize a constant just for use as the
2436   // index register.  We only get rid of the add if it is not an add of a
2437   // value and a 16-bit signed constant and both have a single use.
2438   int16_t imm = 0;
2439   if (N.getOpcode() == ISD::ADD &&
2440       (!isIntS16Immediate(N.getOperand(1), imm) ||
2441        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2442     Base = N.getOperand(0);
2443     Index = N.getOperand(1);
2444     return true;
2445   }
2446 
2447   // Otherwise, do it the hard way, using R0 as the base register.
2448   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2449                          N.getValueType());
2450   Index = N;
2451   return true;
2452 }
2453 
2454 /// Returns true if we should use a direct load into vector instruction
2455 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2456 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2457 
2458   // If there are any other uses other than scalar to vector, then we should
2459   // keep it as a scalar load -> direct move pattern to prevent multiple
2460   // loads.
2461   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2462   if (!LD)
2463     return false;
2464 
2465   EVT MemVT = LD->getMemoryVT();
2466   if (!MemVT.isSimple())
2467     return false;
2468   switch(MemVT.getSimpleVT().SimpleTy) {
2469   case MVT::i64:
2470     break;
2471   case MVT::i32:
2472     if (!ST.hasP8Vector())
2473       return false;
2474     break;
2475   case MVT::i16:
2476   case MVT::i8:
2477     if (!ST.hasP9Vector())
2478       return false;
2479     break;
2480   default:
2481     return false;
2482   }
2483 
2484   SDValue LoadedVal(N, 0);
2485   if (!LoadedVal.hasOneUse())
2486     return false;
2487 
2488   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2489        UI != UE; ++UI)
2490     if (UI.getUse().get().getResNo() == 0 &&
2491         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2492       return false;
2493 
2494   return true;
2495 }
2496 
2497 /// getPreIndexedAddressParts - returns true by value, base pointer and
2498 /// offset pointer and addressing mode by reference if the node's address
2499 /// can be legally represented as pre-indexed load / store address.
2500 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2501                                                   SDValue &Offset,
2502                                                   ISD::MemIndexedMode &AM,
2503                                                   SelectionDAG &DAG) const {
2504   if (DisablePPCPreinc) return false;
2505 
2506   bool isLoad = true;
2507   SDValue Ptr;
2508   EVT VT;
2509   unsigned Alignment;
2510   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2511     Ptr = LD->getBasePtr();
2512     VT = LD->getMemoryVT();
2513     Alignment = LD->getAlignment();
2514   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2515     Ptr = ST->getBasePtr();
2516     VT  = ST->getMemoryVT();
2517     Alignment = ST->getAlignment();
2518     isLoad = false;
2519   } else
2520     return false;
2521 
2522   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2523   // instructions because we can fold these into a more efficient instruction
2524   // instead, (such as LXSD).
2525   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2526     return false;
2527   }
2528 
2529   // PowerPC doesn't have preinc load/store instructions for vectors (except
2530   // for QPX, which does have preinc r+r forms).
2531   if (VT.isVector()) {
2532     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2533       return false;
2534     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2535       AM = ISD::PRE_INC;
2536       return true;
2537     }
2538   }
2539 
2540   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2541     // Common code will reject creating a pre-inc form if the base pointer
2542     // is a frame index, or if N is a store and the base pointer is either
2543     // the same as or a predecessor of the value being stored.  Check for
2544     // those situations here, and try with swapped Base/Offset instead.
2545     bool Swap = false;
2546 
2547     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2548       Swap = true;
2549     else if (!isLoad) {
2550       SDValue Val = cast<StoreSDNode>(N)->getValue();
2551       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2552         Swap = true;
2553     }
2554 
2555     if (Swap)
2556       std::swap(Base, Offset);
2557 
2558     AM = ISD::PRE_INC;
2559     return true;
2560   }
2561 
2562   // LDU/STU can only handle immediates that are a multiple of 4.
2563   if (VT != MVT::i64) {
2564     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2565       return false;
2566   } else {
2567     // LDU/STU need an address with at least 4-byte alignment.
2568     if (Alignment < 4)
2569       return false;
2570 
2571     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2572       return false;
2573   }
2574 
2575   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2576     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2577     // sext i32 to i64 when addr mode is r+i.
2578     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2579         LD->getExtensionType() == ISD::SEXTLOAD &&
2580         isa<ConstantSDNode>(Offset))
2581       return false;
2582   }
2583 
2584   AM = ISD::PRE_INC;
2585   return true;
2586 }
2587 
2588 //===----------------------------------------------------------------------===//
2589 //  LowerOperation implementation
2590 //===----------------------------------------------------------------------===//
2591 
2592 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2593 /// and LoOpFlags to the target MO flags.
2594 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2595                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2596                                const GlobalValue *GV = nullptr) {
2597   HiOpFlags = PPCII::MO_HA;
2598   LoOpFlags = PPCII::MO_LO;
2599 
2600   // Don't use the pic base if not in PIC relocation model.
2601   if (IsPIC) {
2602     HiOpFlags |= PPCII::MO_PIC_FLAG;
2603     LoOpFlags |= PPCII::MO_PIC_FLAG;
2604   }
2605 
2606   // If this is a reference to a global value that requires a non-lazy-ptr, make
2607   // sure that instruction lowering adds it.
2608   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2609     HiOpFlags |= PPCII::MO_NLP_FLAG;
2610     LoOpFlags |= PPCII::MO_NLP_FLAG;
2611 
2612     if (GV->hasHiddenVisibility()) {
2613       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2614       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2615     }
2616   }
2617 }
2618 
2619 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2620                              SelectionDAG &DAG) {
2621   SDLoc DL(HiPart);
2622   EVT PtrVT = HiPart.getValueType();
2623   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2624 
2625   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2626   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2627 
2628   // With PIC, the first instruction is actually "GR+hi(&G)".
2629   if (isPIC)
2630     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2631                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2632 
2633   // Generate non-pic code that has direct accesses to the constant pool.
2634   // The address of the global is just (hi(&g)+lo(&g)).
2635   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2636 }
2637 
2638 static void setUsesTOCBasePtr(MachineFunction &MF) {
2639   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2640   FuncInfo->setUsesTOCBasePtr();
2641 }
2642 
2643 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2644   setUsesTOCBasePtr(DAG.getMachineFunction());
2645 }
2646 
2647 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2648                            SDValue GA) {
2649   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2650   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2651                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2652 
2653   SDValue Ops[] = { GA, Reg };
2654   return DAG.getMemIntrinsicNode(
2655       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2656       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2657       MachineMemOperand::MOLoad);
2658 }
2659 
2660 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2661                                              SelectionDAG &DAG) const {
2662   EVT PtrVT = Op.getValueType();
2663   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2664   const Constant *C = CP->getConstVal();
2665 
2666   // 64-bit SVR4 ABI code is always position-independent.
2667   // The actual address of the GlobalValue is stored in the TOC.
2668   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2669     setUsesTOCBasePtr(DAG);
2670     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2671     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2672   }
2673 
2674   unsigned MOHiFlag, MOLoFlag;
2675   bool IsPIC = isPositionIndependent();
2676   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2677 
2678   if (IsPIC && Subtarget.isSVR4ABI()) {
2679     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2680                                            PPCII::MO_PIC_FLAG);
2681     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2682   }
2683 
2684   SDValue CPIHi =
2685     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2686   SDValue CPILo =
2687     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2688   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2689 }
2690 
2691 // For 64-bit PowerPC, prefer the more compact relative encodings.
2692 // This trades 32 bits per jump table entry for one or two instructions
2693 // on the jump site.
2694 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2695   if (isJumpTableRelative())
2696     return MachineJumpTableInfo::EK_LabelDifference32;
2697 
2698   return TargetLowering::getJumpTableEncoding();
2699 }
2700 
2701 bool PPCTargetLowering::isJumpTableRelative() const {
2702   if (Subtarget.isPPC64())
2703     return true;
2704   return TargetLowering::isJumpTableRelative();
2705 }
2706 
2707 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2708                                                     SelectionDAG &DAG) const {
2709   if (!Subtarget.isPPC64())
2710     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2711 
2712   switch (getTargetMachine().getCodeModel()) {
2713   case CodeModel::Small:
2714   case CodeModel::Medium:
2715     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2716   default:
2717     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2718                        getPointerTy(DAG.getDataLayout()));
2719   }
2720 }
2721 
2722 const MCExpr *
2723 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2724                                                 unsigned JTI,
2725                                                 MCContext &Ctx) const {
2726   if (!Subtarget.isPPC64())
2727     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2728 
2729   switch (getTargetMachine().getCodeModel()) {
2730   case CodeModel::Small:
2731   case CodeModel::Medium:
2732     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2733   default:
2734     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2735   }
2736 }
2737 
2738 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2739   EVT PtrVT = Op.getValueType();
2740   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2741 
2742   // 64-bit SVR4 ABI code is always position-independent.
2743   // The actual address of the GlobalValue is stored in the TOC.
2744   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2745     setUsesTOCBasePtr(DAG);
2746     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2747     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2748   }
2749 
2750   unsigned MOHiFlag, MOLoFlag;
2751   bool IsPIC = isPositionIndependent();
2752   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2753 
2754   if (IsPIC && Subtarget.isSVR4ABI()) {
2755     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2756                                         PPCII::MO_PIC_FLAG);
2757     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2758   }
2759 
2760   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2761   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2762   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2763 }
2764 
2765 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2766                                              SelectionDAG &DAG) const {
2767   EVT PtrVT = Op.getValueType();
2768   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2769   const BlockAddress *BA = BASDN->getBlockAddress();
2770 
2771   // 64-bit SVR4 ABI code is always position-independent.
2772   // The actual BlockAddress is stored in the TOC.
2773   if (Subtarget.isSVR4ABI() &&
2774       (Subtarget.isPPC64() || isPositionIndependent())) {
2775     if (Subtarget.isPPC64())
2776       setUsesTOCBasePtr(DAG);
2777     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2778     return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA);
2779   }
2780 
2781   unsigned MOHiFlag, MOLoFlag;
2782   bool IsPIC = isPositionIndependent();
2783   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2784   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2785   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2786   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2787 }
2788 
2789 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2790                                               SelectionDAG &DAG) const {
2791   // FIXME: TLS addresses currently use medium model code sequences,
2792   // which is the most useful form.  Eventually support for small and
2793   // large models could be added if users need it, at the cost of
2794   // additional complexity.
2795   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2796   if (DAG.getTarget().useEmulatedTLS())
2797     return LowerToTLSEmulatedModel(GA, DAG);
2798 
2799   SDLoc dl(GA);
2800   const GlobalValue *GV = GA->getGlobal();
2801   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2802   bool is64bit = Subtarget.isPPC64();
2803   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2804   PICLevel::Level picLevel = M->getPICLevel();
2805 
2806   const TargetMachine &TM = getTargetMachine();
2807   TLSModel::Model Model = TM.getTLSModel(GV);
2808 
2809   if (Model == TLSModel::LocalExec) {
2810     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2811                                                PPCII::MO_TPREL_HA);
2812     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2813                                                PPCII::MO_TPREL_LO);
2814     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2815                              : DAG.getRegister(PPC::R2, MVT::i32);
2816 
2817     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2818     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2819   }
2820 
2821   if (Model == TLSModel::InitialExec) {
2822     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2823     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2824                                                 PPCII::MO_TLS);
2825     SDValue GOTPtr;
2826     if (is64bit) {
2827       setUsesTOCBasePtr(DAG);
2828       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2829       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2830                            PtrVT, GOTReg, TGA);
2831     } else {
2832       if (!TM.isPositionIndependent())
2833         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2834       else if (picLevel == PICLevel::SmallPIC)
2835         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2836       else
2837         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2838     }
2839     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2840                                    PtrVT, TGA, GOTPtr);
2841     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2842   }
2843 
2844   if (Model == TLSModel::GeneralDynamic) {
2845     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2846     SDValue GOTPtr;
2847     if (is64bit) {
2848       setUsesTOCBasePtr(DAG);
2849       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2850       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2851                                    GOTReg, TGA);
2852     } else {
2853       if (picLevel == PICLevel::SmallPIC)
2854         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2855       else
2856         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2857     }
2858     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2859                        GOTPtr, TGA, TGA);
2860   }
2861 
2862   if (Model == TLSModel::LocalDynamic) {
2863     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2864     SDValue GOTPtr;
2865     if (is64bit) {
2866       setUsesTOCBasePtr(DAG);
2867       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2868       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2869                            GOTReg, TGA);
2870     } else {
2871       if (picLevel == PICLevel::SmallPIC)
2872         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2873       else
2874         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2875     }
2876     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2877                                   PtrVT, GOTPtr, TGA, TGA);
2878     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2879                                       PtrVT, TLSAddr, TGA);
2880     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2881   }
2882 
2883   llvm_unreachable("Unknown TLS model!");
2884 }
2885 
2886 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2887                                               SelectionDAG &DAG) const {
2888   EVT PtrVT = Op.getValueType();
2889   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2890   SDLoc DL(GSDN);
2891   const GlobalValue *GV = GSDN->getGlobal();
2892 
2893   // 64-bit SVR4 ABI code is always position-independent.
2894   // The actual address of the GlobalValue is stored in the TOC.
2895   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2896     setUsesTOCBasePtr(DAG);
2897     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2898     return getTOCEntry(DAG, DL, true, GA);
2899   }
2900 
2901   unsigned MOHiFlag, MOLoFlag;
2902   bool IsPIC = isPositionIndependent();
2903   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2904 
2905   if (IsPIC && Subtarget.isSVR4ABI()) {
2906     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2907                                             GSDN->getOffset(),
2908                                             PPCII::MO_PIC_FLAG);
2909     return getTOCEntry(DAG, DL, false, GA);
2910   }
2911 
2912   SDValue GAHi =
2913     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2914   SDValue GALo =
2915     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2916 
2917   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2918 
2919   // If the global reference is actually to a non-lazy-pointer, we have to do an
2920   // extra load to get the address of the global.
2921   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2922     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2923   return Ptr;
2924 }
2925 
2926 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2927   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2928   SDLoc dl(Op);
2929 
2930   if (Op.getValueType() == MVT::v2i64) {
2931     // When the operands themselves are v2i64 values, we need to do something
2932     // special because VSX has no underlying comparison operations for these.
2933     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2934       // Equality can be handled by casting to the legal type for Altivec
2935       // comparisons, everything else needs to be expanded.
2936       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2937         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2938                  DAG.getSetCC(dl, MVT::v4i32,
2939                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2940                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2941                    CC));
2942       }
2943 
2944       return SDValue();
2945     }
2946 
2947     // We handle most of these in the usual way.
2948     return Op;
2949   }
2950 
2951   // If we're comparing for equality to zero, expose the fact that this is
2952   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2953   // fold the new nodes.
2954   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2955     return V;
2956 
2957   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2958     // Leave comparisons against 0 and -1 alone for now, since they're usually
2959     // optimized.  FIXME: revisit this when we can custom lower all setcc
2960     // optimizations.
2961     if (C->isAllOnesValue() || C->isNullValue())
2962       return SDValue();
2963   }
2964 
2965   // If we have an integer seteq/setne, turn it into a compare against zero
2966   // by xor'ing the rhs with the lhs, which is faster than setting a
2967   // condition register, reading it back out, and masking the correct bit.  The
2968   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2969   // the result to other bit-twiddling opportunities.
2970   EVT LHSVT = Op.getOperand(0).getValueType();
2971   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2972     EVT VT = Op.getValueType();
2973     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2974                                 Op.getOperand(1));
2975     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2976   }
2977   return SDValue();
2978 }
2979 
2980 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2981   SDNode *Node = Op.getNode();
2982   EVT VT = Node->getValueType(0);
2983   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2984   SDValue InChain = Node->getOperand(0);
2985   SDValue VAListPtr = Node->getOperand(1);
2986   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2987   SDLoc dl(Node);
2988 
2989   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2990 
2991   // gpr_index
2992   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2993                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2994   InChain = GprIndex.getValue(1);
2995 
2996   if (VT == MVT::i64) {
2997     // Check if GprIndex is even
2998     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2999                                  DAG.getConstant(1, dl, MVT::i32));
3000     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3001                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3002     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3003                                           DAG.getConstant(1, dl, MVT::i32));
3004     // Align GprIndex to be even if it isn't
3005     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3006                            GprIndex);
3007   }
3008 
3009   // fpr index is 1 byte after gpr
3010   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3011                                DAG.getConstant(1, dl, MVT::i32));
3012 
3013   // fpr
3014   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3015                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3016   InChain = FprIndex.getValue(1);
3017 
3018   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3019                                        DAG.getConstant(8, dl, MVT::i32));
3020 
3021   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3022                                         DAG.getConstant(4, dl, MVT::i32));
3023 
3024   // areas
3025   SDValue OverflowArea =
3026       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3027   InChain = OverflowArea.getValue(1);
3028 
3029   SDValue RegSaveArea =
3030       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3031   InChain = RegSaveArea.getValue(1);
3032 
3033   // select overflow_area if index > 8
3034   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3035                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3036 
3037   // adjustment constant gpr_index * 4/8
3038   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3039                                     VT.isInteger() ? GprIndex : FprIndex,
3040                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3041                                                     MVT::i32));
3042 
3043   // OurReg = RegSaveArea + RegConstant
3044   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3045                                RegConstant);
3046 
3047   // Floating types are 32 bytes into RegSaveArea
3048   if (VT.isFloatingPoint())
3049     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3050                          DAG.getConstant(32, dl, MVT::i32));
3051 
3052   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3053   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3054                                    VT.isInteger() ? GprIndex : FprIndex,
3055                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3056                                                    MVT::i32));
3057 
3058   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3059                               VT.isInteger() ? VAListPtr : FprPtr,
3060                               MachinePointerInfo(SV), MVT::i8);
3061 
3062   // determine if we should load from reg_save_area or overflow_area
3063   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3064 
3065   // increase overflow_area by 4/8 if gpr/fpr > 8
3066   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3067                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3068                                           dl, MVT::i32));
3069 
3070   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3071                              OverflowAreaPlusN);
3072 
3073   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3074                               MachinePointerInfo(), MVT::i32);
3075 
3076   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3077 }
3078 
3079 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3080   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3081 
3082   // We have to copy the entire va_list struct:
3083   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3084   return DAG.getMemcpy(Op.getOperand(0), Op,
3085                        Op.getOperand(1), Op.getOperand(2),
3086                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3087                        false, MachinePointerInfo(), MachinePointerInfo());
3088 }
3089 
3090 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3091                                                   SelectionDAG &DAG) const {
3092   return Op.getOperand(0);
3093 }
3094 
3095 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3096                                                 SelectionDAG &DAG) const {
3097   SDValue Chain = Op.getOperand(0);
3098   SDValue Trmp = Op.getOperand(1); // trampoline
3099   SDValue FPtr = Op.getOperand(2); // nested function
3100   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3101   SDLoc dl(Op);
3102 
3103   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3104   bool isPPC64 = (PtrVT == MVT::i64);
3105   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3106 
3107   TargetLowering::ArgListTy Args;
3108   TargetLowering::ArgListEntry Entry;
3109 
3110   Entry.Ty = IntPtrTy;
3111   Entry.Node = Trmp; Args.push_back(Entry);
3112 
3113   // TrampSize == (isPPC64 ? 48 : 40);
3114   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3115                                isPPC64 ? MVT::i64 : MVT::i32);
3116   Args.push_back(Entry);
3117 
3118   Entry.Node = FPtr; Args.push_back(Entry);
3119   Entry.Node = Nest; Args.push_back(Entry);
3120 
3121   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3122   TargetLowering::CallLoweringInfo CLI(DAG);
3123   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3124       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3125       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3126 
3127   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3128   return CallResult.second;
3129 }
3130 
3131 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3132   MachineFunction &MF = DAG.getMachineFunction();
3133   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3134   EVT PtrVT = getPointerTy(MF.getDataLayout());
3135 
3136   SDLoc dl(Op);
3137 
3138   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3139     // vastart just stores the address of the VarArgsFrameIndex slot into the
3140     // memory location argument.
3141     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3142     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3143     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3144                         MachinePointerInfo(SV));
3145   }
3146 
3147   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3148   // We suppose the given va_list is already allocated.
3149   //
3150   // typedef struct {
3151   //  char gpr;     /* index into the array of 8 GPRs
3152   //                 * stored in the register save area
3153   //                 * gpr=0 corresponds to r3,
3154   //                 * gpr=1 to r4, etc.
3155   //                 */
3156   //  char fpr;     /* index into the array of 8 FPRs
3157   //                 * stored in the register save area
3158   //                 * fpr=0 corresponds to f1,
3159   //                 * fpr=1 to f2, etc.
3160   //                 */
3161   //  char *overflow_arg_area;
3162   //                /* location on stack that holds
3163   //                 * the next overflow argument
3164   //                 */
3165   //  char *reg_save_area;
3166   //               /* where r3:r10 and f1:f8 (if saved)
3167   //                * are stored
3168   //                */
3169   // } va_list[1];
3170 
3171   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3172   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3173   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3174                                             PtrVT);
3175   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3176                                  PtrVT);
3177 
3178   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3179   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3180 
3181   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3182   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3183 
3184   uint64_t FPROffset = 1;
3185   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3186 
3187   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3188 
3189   // Store first byte : number of int regs
3190   SDValue firstStore =
3191       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3192                         MachinePointerInfo(SV), MVT::i8);
3193   uint64_t nextOffset = FPROffset;
3194   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3195                                   ConstFPROffset);
3196 
3197   // Store second byte : number of float regs
3198   SDValue secondStore =
3199       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3200                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3201   nextOffset += StackOffset;
3202   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3203 
3204   // Store second word : arguments given on stack
3205   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3206                                     MachinePointerInfo(SV, nextOffset));
3207   nextOffset += FrameOffset;
3208   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3209 
3210   // Store third word : arguments given in registers
3211   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3212                       MachinePointerInfo(SV, nextOffset));
3213 }
3214 
3215 /// FPR - The set of FP registers that should be allocated for arguments,
3216 /// on Darwin.
3217 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3218                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3219                                 PPC::F11, PPC::F12, PPC::F13};
3220 
3221 /// QFPR - The set of QPX registers that should be allocated for arguments.
3222 static const MCPhysReg QFPR[] = {
3223     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3224     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3225 
3226 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3227 /// the stack.
3228 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3229                                        unsigned PtrByteSize) {
3230   unsigned ArgSize = ArgVT.getStoreSize();
3231   if (Flags.isByVal())
3232     ArgSize = Flags.getByValSize();
3233 
3234   // Round up to multiples of the pointer size, except for array members,
3235   // which are always packed.
3236   if (!Flags.isInConsecutiveRegs())
3237     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3238 
3239   return ArgSize;
3240 }
3241 
3242 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3243 /// on the stack.
3244 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3245                                             ISD::ArgFlagsTy Flags,
3246                                             unsigned PtrByteSize) {
3247   unsigned Align = PtrByteSize;
3248 
3249   // Altivec parameters are padded to a 16 byte boundary.
3250   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3251       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3252       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3253       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3254     Align = 16;
3255   // QPX vector types stored in double-precision are padded to a 32 byte
3256   // boundary.
3257   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3258     Align = 32;
3259 
3260   // ByVal parameters are aligned as requested.
3261   if (Flags.isByVal()) {
3262     unsigned BVAlign = Flags.getByValAlign();
3263     if (BVAlign > PtrByteSize) {
3264       if (BVAlign % PtrByteSize != 0)
3265           llvm_unreachable(
3266             "ByVal alignment is not a multiple of the pointer size");
3267 
3268       Align = BVAlign;
3269     }
3270   }
3271 
3272   // Array members are always packed to their original alignment.
3273   if (Flags.isInConsecutiveRegs()) {
3274     // If the array member was split into multiple registers, the first
3275     // needs to be aligned to the size of the full type.  (Except for
3276     // ppcf128, which is only aligned as its f64 components.)
3277     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3278       Align = OrigVT.getStoreSize();
3279     else
3280       Align = ArgVT.getStoreSize();
3281   }
3282 
3283   return Align;
3284 }
3285 
3286 /// CalculateStackSlotUsed - Return whether this argument will use its
3287 /// stack slot (instead of being passed in registers).  ArgOffset,
3288 /// AvailableFPRs, and AvailableVRs must hold the current argument
3289 /// position, and will be updated to account for this argument.
3290 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3291                                    ISD::ArgFlagsTy Flags,
3292                                    unsigned PtrByteSize,
3293                                    unsigned LinkageSize,
3294                                    unsigned ParamAreaSize,
3295                                    unsigned &ArgOffset,
3296                                    unsigned &AvailableFPRs,
3297                                    unsigned &AvailableVRs, bool HasQPX) {
3298   bool UseMemory = false;
3299 
3300   // Respect alignment of argument on the stack.
3301   unsigned Align =
3302     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3303   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3304   // If there's no space left in the argument save area, we must
3305   // use memory (this check also catches zero-sized arguments).
3306   if (ArgOffset >= LinkageSize + ParamAreaSize)
3307     UseMemory = true;
3308 
3309   // Allocate argument on the stack.
3310   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3311   if (Flags.isInConsecutiveRegsLast())
3312     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3313   // If we overran the argument save area, we must use memory
3314   // (this check catches arguments passed partially in memory)
3315   if (ArgOffset > LinkageSize + ParamAreaSize)
3316     UseMemory = true;
3317 
3318   // However, if the argument is actually passed in an FPR or a VR,
3319   // we don't use memory after all.
3320   if (!Flags.isByVal()) {
3321     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3322         // QPX registers overlap with the scalar FP registers.
3323         (HasQPX && (ArgVT == MVT::v4f32 ||
3324                     ArgVT == MVT::v4f64 ||
3325                     ArgVT == MVT::v4i1)))
3326       if (AvailableFPRs > 0) {
3327         --AvailableFPRs;
3328         return false;
3329       }
3330     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3331         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3332         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3333         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3334       if (AvailableVRs > 0) {
3335         --AvailableVRs;
3336         return false;
3337       }
3338   }
3339 
3340   return UseMemory;
3341 }
3342 
3343 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3344 /// ensure minimum alignment required for target.
3345 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3346                                      unsigned NumBytes) {
3347   unsigned TargetAlign = Lowering->getStackAlignment();
3348   unsigned AlignMask = TargetAlign - 1;
3349   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3350   return NumBytes;
3351 }
3352 
3353 SDValue PPCTargetLowering::LowerFormalArguments(
3354     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3355     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3356     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3357   if (Subtarget.isSVR4ABI()) {
3358     if (Subtarget.isPPC64())
3359       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3360                                          dl, DAG, InVals);
3361     else
3362       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3363                                          dl, DAG, InVals);
3364   } else {
3365     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3366                                        dl, DAG, InVals);
3367   }
3368 }
3369 
3370 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3371     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3372     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3373     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3374 
3375   // 32-bit SVR4 ABI Stack Frame Layout:
3376   //              +-----------------------------------+
3377   //        +-->  |            Back chain             |
3378   //        |     +-----------------------------------+
3379   //        |     | Floating-point register save area |
3380   //        |     +-----------------------------------+
3381   //        |     |    General register save area     |
3382   //        |     +-----------------------------------+
3383   //        |     |          CR save word             |
3384   //        |     +-----------------------------------+
3385   //        |     |         VRSAVE save word          |
3386   //        |     +-----------------------------------+
3387   //        |     |         Alignment padding         |
3388   //        |     +-----------------------------------+
3389   //        |     |     Vector register save area     |
3390   //        |     +-----------------------------------+
3391   //        |     |       Local variable space        |
3392   //        |     +-----------------------------------+
3393   //        |     |        Parameter list area        |
3394   //        |     +-----------------------------------+
3395   //        |     |           LR save word            |
3396   //        |     +-----------------------------------+
3397   // SP-->  +---  |            Back chain             |
3398   //              +-----------------------------------+
3399   //
3400   // Specifications:
3401   //   System V Application Binary Interface PowerPC Processor Supplement
3402   //   AltiVec Technology Programming Interface Manual
3403 
3404   MachineFunction &MF = DAG.getMachineFunction();
3405   MachineFrameInfo &MFI = MF.getFrameInfo();
3406   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3407 
3408   EVT PtrVT = getPointerTy(MF.getDataLayout());
3409   // Potential tail calls could cause overwriting of argument stack slots.
3410   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3411                        (CallConv == CallingConv::Fast));
3412   unsigned PtrByteSize = 4;
3413 
3414   // Assign locations to all of the incoming arguments.
3415   SmallVector<CCValAssign, 16> ArgLocs;
3416   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3417                  *DAG.getContext());
3418 
3419   // Reserve space for the linkage area on the stack.
3420   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3421   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3422   if (useSoftFloat())
3423     CCInfo.PreAnalyzeFormalArguments(Ins);
3424 
3425   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3426   CCInfo.clearWasPPCF128();
3427 
3428   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3429     CCValAssign &VA = ArgLocs[i];
3430 
3431     // Arguments stored in registers.
3432     if (VA.isRegLoc()) {
3433       const TargetRegisterClass *RC;
3434       EVT ValVT = VA.getValVT();
3435 
3436       switch (ValVT.getSimpleVT().SimpleTy) {
3437         default:
3438           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3439         case MVT::i1:
3440         case MVT::i32:
3441           RC = &PPC::GPRCRegClass;
3442           break;
3443         case MVT::f32:
3444           if (Subtarget.hasP8Vector())
3445             RC = &PPC::VSSRCRegClass;
3446           else if (Subtarget.hasSPE())
3447             RC = &PPC::SPE4RCRegClass;
3448           else
3449             RC = &PPC::F4RCRegClass;
3450           break;
3451         case MVT::f64:
3452           if (Subtarget.hasVSX())
3453             RC = &PPC::VSFRCRegClass;
3454           else if (Subtarget.hasSPE())
3455             // SPE passes doubles in GPR pairs.
3456             RC = &PPC::GPRCRegClass;
3457           else
3458             RC = &PPC::F8RCRegClass;
3459           break;
3460         case MVT::v16i8:
3461         case MVT::v8i16:
3462         case MVT::v4i32:
3463           RC = &PPC::VRRCRegClass;
3464           break;
3465         case MVT::v4f32:
3466           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3467           break;
3468         case MVT::v2f64:
3469         case MVT::v2i64:
3470           RC = &PPC::VRRCRegClass;
3471           break;
3472         case MVT::v4f64:
3473           RC = &PPC::QFRCRegClass;
3474           break;
3475         case MVT::v4i1:
3476           RC = &PPC::QBRCRegClass;
3477           break;
3478       }
3479 
3480       SDValue ArgValue;
3481       // Transform the arguments stored in physical registers into
3482       // virtual ones.
3483       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3484         assert(i + 1 < e && "No second half of double precision argument");
3485         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3486         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3487         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3488         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3489         if (!Subtarget.isLittleEndian())
3490           std::swap (ArgValueLo, ArgValueHi);
3491         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3492                                ArgValueHi);
3493       } else {
3494         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3495         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3496                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3497         if (ValVT == MVT::i1)
3498           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3499       }
3500 
3501       InVals.push_back(ArgValue);
3502     } else {
3503       // Argument stored in memory.
3504       assert(VA.isMemLoc());
3505 
3506       // Get the extended size of the argument type in stack
3507       unsigned ArgSize = VA.getLocVT().getStoreSize();
3508       // Get the actual size of the argument type
3509       unsigned ObjSize = VA.getValVT().getStoreSize();
3510       unsigned ArgOffset = VA.getLocMemOffset();
3511       // Stack objects in PPC32 are right justified.
3512       ArgOffset += ArgSize - ObjSize;
3513       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3514 
3515       // Create load nodes to retrieve arguments from the stack.
3516       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3517       InVals.push_back(
3518           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3519     }
3520   }
3521 
3522   // Assign locations to all of the incoming aggregate by value arguments.
3523   // Aggregates passed by value are stored in the local variable space of the
3524   // caller's stack frame, right above the parameter list area.
3525   SmallVector<CCValAssign, 16> ByValArgLocs;
3526   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3527                       ByValArgLocs, *DAG.getContext());
3528 
3529   // Reserve stack space for the allocations in CCInfo.
3530   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3531 
3532   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3533 
3534   // Area that is at least reserved in the caller of this function.
3535   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3536   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3537 
3538   // Set the size that is at least reserved in caller of this function.  Tail
3539   // call optimized function's reserved stack space needs to be aligned so that
3540   // taking the difference between two stack areas will result in an aligned
3541   // stack.
3542   MinReservedArea =
3543       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3544   FuncInfo->setMinReservedArea(MinReservedArea);
3545 
3546   SmallVector<SDValue, 8> MemOps;
3547 
3548   // If the function takes variable number of arguments, make a frame index for
3549   // the start of the first vararg value... for expansion of llvm.va_start.
3550   if (isVarArg) {
3551     static const MCPhysReg GPArgRegs[] = {
3552       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3553       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3554     };
3555     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3556 
3557     static const MCPhysReg FPArgRegs[] = {
3558       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3559       PPC::F8
3560     };
3561     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3562 
3563     if (useSoftFloat() || hasSPE())
3564        NumFPArgRegs = 0;
3565 
3566     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3567     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3568 
3569     // Make room for NumGPArgRegs and NumFPArgRegs.
3570     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3571                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3572 
3573     FuncInfo->setVarArgsStackOffset(
3574       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3575                             CCInfo.getNextStackOffset(), true));
3576 
3577     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3578     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3579 
3580     // The fixed integer arguments of a variadic function are stored to the
3581     // VarArgsFrameIndex on the stack so that they may be loaded by
3582     // dereferencing the result of va_next.
3583     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3584       // Get an existing live-in vreg, or add a new one.
3585       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3586       if (!VReg)
3587         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3588 
3589       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3590       SDValue Store =
3591           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3592       MemOps.push_back(Store);
3593       // Increment the address by four for the next argument to store
3594       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3595       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3596     }
3597 
3598     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3599     // is set.
3600     // The double arguments are stored to the VarArgsFrameIndex
3601     // on the stack.
3602     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3603       // Get an existing live-in vreg, or add a new one.
3604       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3605       if (!VReg)
3606         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3607 
3608       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3609       SDValue Store =
3610           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3611       MemOps.push_back(Store);
3612       // Increment the address by eight for the next argument to store
3613       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3614                                          PtrVT);
3615       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3616     }
3617   }
3618 
3619   if (!MemOps.empty())
3620     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3621 
3622   return Chain;
3623 }
3624 
3625 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3626 // value to MVT::i64 and then truncate to the correct register size.
3627 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3628                                              EVT ObjectVT, SelectionDAG &DAG,
3629                                              SDValue ArgVal,
3630                                              const SDLoc &dl) const {
3631   if (Flags.isSExt())
3632     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3633                          DAG.getValueType(ObjectVT));
3634   else if (Flags.isZExt())
3635     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3636                          DAG.getValueType(ObjectVT));
3637 
3638   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3639 }
3640 
3641 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3642     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3643     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3644     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3645   // TODO: add description of PPC stack frame format, or at least some docs.
3646   //
3647   bool isELFv2ABI = Subtarget.isELFv2ABI();
3648   bool isLittleEndian = Subtarget.isLittleEndian();
3649   MachineFunction &MF = DAG.getMachineFunction();
3650   MachineFrameInfo &MFI = MF.getFrameInfo();
3651   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3652 
3653   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3654          "fastcc not supported on varargs functions");
3655 
3656   EVT PtrVT = getPointerTy(MF.getDataLayout());
3657   // Potential tail calls could cause overwriting of argument stack slots.
3658   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3659                        (CallConv == CallingConv::Fast));
3660   unsigned PtrByteSize = 8;
3661   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3662 
3663   static const MCPhysReg GPR[] = {
3664     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3665     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3666   };
3667   static const MCPhysReg VR[] = {
3668     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3669     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3670   };
3671 
3672   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3673   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3674   const unsigned Num_VR_Regs  = array_lengthof(VR);
3675   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3676 
3677   // Do a first pass over the arguments to determine whether the ABI
3678   // guarantees that our caller has allocated the parameter save area
3679   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3680   // in the ELFv2 ABI, it is true if this is a vararg function or if
3681   // any parameter is located in a stack slot.
3682 
3683   bool HasParameterArea = !isELFv2ABI || isVarArg;
3684   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3685   unsigned NumBytes = LinkageSize;
3686   unsigned AvailableFPRs = Num_FPR_Regs;
3687   unsigned AvailableVRs = Num_VR_Regs;
3688   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3689     if (Ins[i].Flags.isNest())
3690       continue;
3691 
3692     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3693                                PtrByteSize, LinkageSize, ParamAreaSize,
3694                                NumBytes, AvailableFPRs, AvailableVRs,
3695                                Subtarget.hasQPX()))
3696       HasParameterArea = true;
3697   }
3698 
3699   // Add DAG nodes to load the arguments or copy them out of registers.  On
3700   // entry to a function on PPC, the arguments start after the linkage area,
3701   // although the first ones are often in registers.
3702 
3703   unsigned ArgOffset = LinkageSize;
3704   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3705   unsigned &QFPR_idx = FPR_idx;
3706   SmallVector<SDValue, 8> MemOps;
3707   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3708   unsigned CurArgIdx = 0;
3709   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3710     SDValue ArgVal;
3711     bool needsLoad = false;
3712     EVT ObjectVT = Ins[ArgNo].VT;
3713     EVT OrigVT = Ins[ArgNo].ArgVT;
3714     unsigned ObjSize = ObjectVT.getStoreSize();
3715     unsigned ArgSize = ObjSize;
3716     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3717     if (Ins[ArgNo].isOrigArg()) {
3718       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3719       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3720     }
3721     // We re-align the argument offset for each argument, except when using the
3722     // fast calling convention, when we need to make sure we do that only when
3723     // we'll actually use a stack slot.
3724     unsigned CurArgOffset, Align;
3725     auto ComputeArgOffset = [&]() {
3726       /* Respect alignment of argument on the stack.  */
3727       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3728       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3729       CurArgOffset = ArgOffset;
3730     };
3731 
3732     if (CallConv != CallingConv::Fast) {
3733       ComputeArgOffset();
3734 
3735       /* Compute GPR index associated with argument offset.  */
3736       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3737       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3738     }
3739 
3740     // FIXME the codegen can be much improved in some cases.
3741     // We do not have to keep everything in memory.
3742     if (Flags.isByVal()) {
3743       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3744 
3745       if (CallConv == CallingConv::Fast)
3746         ComputeArgOffset();
3747 
3748       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3749       ObjSize = Flags.getByValSize();
3750       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3751       // Empty aggregate parameters do not take up registers.  Examples:
3752       //   struct { } a;
3753       //   union  { } b;
3754       //   int c[0];
3755       // etc.  However, we have to provide a place-holder in InVals, so
3756       // pretend we have an 8-byte item at the current address for that
3757       // purpose.
3758       if (!ObjSize) {
3759         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3760         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3761         InVals.push_back(FIN);
3762         continue;
3763       }
3764 
3765       // Create a stack object covering all stack doublewords occupied
3766       // by the argument.  If the argument is (fully or partially) on
3767       // the stack, or if the argument is fully in registers but the
3768       // caller has allocated the parameter save anyway, we can refer
3769       // directly to the caller's stack frame.  Otherwise, create a
3770       // local copy in our own frame.
3771       int FI;
3772       if (HasParameterArea ||
3773           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3774         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3775       else
3776         FI = MFI.CreateStackObject(ArgSize, Align, false);
3777       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3778 
3779       // Handle aggregates smaller than 8 bytes.
3780       if (ObjSize < PtrByteSize) {
3781         // The value of the object is its address, which differs from the
3782         // address of the enclosing doubleword on big-endian systems.
3783         SDValue Arg = FIN;
3784         if (!isLittleEndian) {
3785           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3786           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3787         }
3788         InVals.push_back(Arg);
3789 
3790         if (GPR_idx != Num_GPR_Regs) {
3791           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3792           FuncInfo->addLiveInAttr(VReg, Flags);
3793           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3794           SDValue Store;
3795 
3796           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3797             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3798                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3799             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3800                                       MachinePointerInfo(&*FuncArg), ObjType);
3801           } else {
3802             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3803             // store the whole register as-is to the parameter save area
3804             // slot.
3805             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3806                                  MachinePointerInfo(&*FuncArg));
3807           }
3808 
3809           MemOps.push_back(Store);
3810         }
3811         // Whether we copied from a register or not, advance the offset
3812         // into the parameter save area by a full doubleword.
3813         ArgOffset += PtrByteSize;
3814         continue;
3815       }
3816 
3817       // The value of the object is its address, which is the address of
3818       // its first stack doubleword.
3819       InVals.push_back(FIN);
3820 
3821       // Store whatever pieces of the object are in registers to memory.
3822       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3823         if (GPR_idx == Num_GPR_Regs)
3824           break;
3825 
3826         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3827         FuncInfo->addLiveInAttr(VReg, Flags);
3828         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3829         SDValue Addr = FIN;
3830         if (j) {
3831           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3832           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3833         }
3834         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3835                                      MachinePointerInfo(&*FuncArg, j));
3836         MemOps.push_back(Store);
3837         ++GPR_idx;
3838       }
3839       ArgOffset += ArgSize;
3840       continue;
3841     }
3842 
3843     switch (ObjectVT.getSimpleVT().SimpleTy) {
3844     default: llvm_unreachable("Unhandled argument type!");
3845     case MVT::i1:
3846     case MVT::i32:
3847     case MVT::i64:
3848       if (Flags.isNest()) {
3849         // The 'nest' parameter, if any, is passed in R11.
3850         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3851         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3852 
3853         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3854           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3855 
3856         break;
3857       }
3858 
3859       // These can be scalar arguments or elements of an integer array type
3860       // passed directly.  Clang may use those instead of "byval" aggregate
3861       // types to avoid forcing arguments to memory unnecessarily.
3862       if (GPR_idx != Num_GPR_Regs) {
3863         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3864         FuncInfo->addLiveInAttr(VReg, Flags);
3865         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3866 
3867         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3868           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3869           // value to MVT::i64 and then truncate to the correct register size.
3870           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3871       } else {
3872         if (CallConv == CallingConv::Fast)
3873           ComputeArgOffset();
3874 
3875         needsLoad = true;
3876         ArgSize = PtrByteSize;
3877       }
3878       if (CallConv != CallingConv::Fast || needsLoad)
3879         ArgOffset += 8;
3880       break;
3881 
3882     case MVT::f32:
3883     case MVT::f64:
3884       // These can be scalar arguments or elements of a float array type
3885       // passed directly.  The latter are used to implement ELFv2 homogenous
3886       // float aggregates.
3887       if (FPR_idx != Num_FPR_Regs) {
3888         unsigned VReg;
3889 
3890         if (ObjectVT == MVT::f32)
3891           VReg = MF.addLiveIn(FPR[FPR_idx],
3892                               Subtarget.hasP8Vector()
3893                                   ? &PPC::VSSRCRegClass
3894                                   : &PPC::F4RCRegClass);
3895         else
3896           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3897                                                 ? &PPC::VSFRCRegClass
3898                                                 : &PPC::F8RCRegClass);
3899 
3900         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3901         ++FPR_idx;
3902       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3903         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3904         // once we support fp <-> gpr moves.
3905 
3906         // This can only ever happen in the presence of f32 array types,
3907         // since otherwise we never run out of FPRs before running out
3908         // of GPRs.
3909         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3910         FuncInfo->addLiveInAttr(VReg, Flags);
3911         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3912 
3913         if (ObjectVT == MVT::f32) {
3914           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3915             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3916                                  DAG.getConstant(32, dl, MVT::i32));
3917           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3918         }
3919 
3920         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3921       } else {
3922         if (CallConv == CallingConv::Fast)
3923           ComputeArgOffset();
3924 
3925         needsLoad = true;
3926       }
3927 
3928       // When passing an array of floats, the array occupies consecutive
3929       // space in the argument area; only round up to the next doubleword
3930       // at the end of the array.  Otherwise, each float takes 8 bytes.
3931       if (CallConv != CallingConv::Fast || needsLoad) {
3932         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3933         ArgOffset += ArgSize;
3934         if (Flags.isInConsecutiveRegsLast())
3935           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3936       }
3937       break;
3938     case MVT::v4f32:
3939     case MVT::v4i32:
3940     case MVT::v8i16:
3941     case MVT::v16i8:
3942     case MVT::v2f64:
3943     case MVT::v2i64:
3944     case MVT::v1i128:
3945     case MVT::f128:
3946       if (!Subtarget.hasQPX()) {
3947         // These can be scalar arguments or elements of a vector array type
3948         // passed directly.  The latter are used to implement ELFv2 homogenous
3949         // vector aggregates.
3950         if (VR_idx != Num_VR_Regs) {
3951           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3952           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3953           ++VR_idx;
3954         } else {
3955           if (CallConv == CallingConv::Fast)
3956             ComputeArgOffset();
3957           needsLoad = true;
3958         }
3959         if (CallConv != CallingConv::Fast || needsLoad)
3960           ArgOffset += 16;
3961         break;
3962       } // not QPX
3963 
3964       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3965              "Invalid QPX parameter type");
3966       LLVM_FALLTHROUGH;
3967 
3968     case MVT::v4f64:
3969     case MVT::v4i1:
3970       // QPX vectors are treated like their scalar floating-point subregisters
3971       // (except that they're larger).
3972       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3973       if (QFPR_idx != Num_QFPR_Regs) {
3974         const TargetRegisterClass *RC;
3975         switch (ObjectVT.getSimpleVT().SimpleTy) {
3976         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3977         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3978         default:         RC = &PPC::QBRCRegClass; break;
3979         }
3980 
3981         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3982         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3983         ++QFPR_idx;
3984       } else {
3985         if (CallConv == CallingConv::Fast)
3986           ComputeArgOffset();
3987         needsLoad = true;
3988       }
3989       if (CallConv != CallingConv::Fast || needsLoad)
3990         ArgOffset += Sz;
3991       break;
3992     }
3993 
3994     // We need to load the argument to a virtual register if we determined
3995     // above that we ran out of physical registers of the appropriate type.
3996     if (needsLoad) {
3997       if (ObjSize < ArgSize && !isLittleEndian)
3998         CurArgOffset += ArgSize - ObjSize;
3999       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4000       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4001       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4002     }
4003 
4004     InVals.push_back(ArgVal);
4005   }
4006 
4007   // Area that is at least reserved in the caller of this function.
4008   unsigned MinReservedArea;
4009   if (HasParameterArea)
4010     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4011   else
4012     MinReservedArea = LinkageSize;
4013 
4014   // Set the size that is at least reserved in caller of this function.  Tail
4015   // call optimized functions' reserved stack space needs to be aligned so that
4016   // taking the difference between two stack areas will result in an aligned
4017   // stack.
4018   MinReservedArea =
4019       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4020   FuncInfo->setMinReservedArea(MinReservedArea);
4021 
4022   // If the function takes variable number of arguments, make a frame index for
4023   // the start of the first vararg value... for expansion of llvm.va_start.
4024   if (isVarArg) {
4025     int Depth = ArgOffset;
4026 
4027     FuncInfo->setVarArgsFrameIndex(
4028       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4029     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4030 
4031     // If this function is vararg, store any remaining integer argument regs
4032     // to their spots on the stack so that they may be loaded by dereferencing
4033     // the result of va_next.
4034     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4035          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4036       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4037       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4038       SDValue Store =
4039           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4040       MemOps.push_back(Store);
4041       // Increment the address by four for the next argument to store
4042       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4043       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4044     }
4045   }
4046 
4047   if (!MemOps.empty())
4048     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4049 
4050   return Chain;
4051 }
4052 
4053 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4054     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4055     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4056     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4057   // TODO: add description of PPC stack frame format, or at least some docs.
4058   //
4059   MachineFunction &MF = DAG.getMachineFunction();
4060   MachineFrameInfo &MFI = MF.getFrameInfo();
4061   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4062 
4063   EVT PtrVT = getPointerTy(MF.getDataLayout());
4064   bool isPPC64 = PtrVT == MVT::i64;
4065   // Potential tail calls could cause overwriting of argument stack slots.
4066   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4067                        (CallConv == CallingConv::Fast));
4068   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4069   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4070   unsigned ArgOffset = LinkageSize;
4071   // Area that is at least reserved in caller of this function.
4072   unsigned MinReservedArea = ArgOffset;
4073 
4074   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4075     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4076     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4077   };
4078   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4079     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4080     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4081   };
4082   static const MCPhysReg VR[] = {
4083     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4084     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4085   };
4086 
4087   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4088   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4089   const unsigned Num_VR_Regs  = array_lengthof( VR);
4090 
4091   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4092 
4093   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4094 
4095   // In 32-bit non-varargs functions, the stack space for vectors is after the
4096   // stack space for non-vectors.  We do not use this space unless we have
4097   // too many vectors to fit in registers, something that only occurs in
4098   // constructed examples:), but we have to walk the arglist to figure
4099   // that out...for the pathological case, compute VecArgOffset as the
4100   // start of the vector parameter area.  Computing VecArgOffset is the
4101   // entire point of the following loop.
4102   unsigned VecArgOffset = ArgOffset;
4103   if (!isVarArg && !isPPC64) {
4104     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4105          ++ArgNo) {
4106       EVT ObjectVT = Ins[ArgNo].VT;
4107       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4108 
4109       if (Flags.isByVal()) {
4110         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4111         unsigned ObjSize = Flags.getByValSize();
4112         unsigned ArgSize =
4113                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4114         VecArgOffset += ArgSize;
4115         continue;
4116       }
4117 
4118       switch(ObjectVT.getSimpleVT().SimpleTy) {
4119       default: llvm_unreachable("Unhandled argument type!");
4120       case MVT::i1:
4121       case MVT::i32:
4122       case MVT::f32:
4123         VecArgOffset += 4;
4124         break;
4125       case MVT::i64:  // PPC64
4126       case MVT::f64:
4127         // FIXME: We are guaranteed to be !isPPC64 at this point.
4128         // Does MVT::i64 apply?
4129         VecArgOffset += 8;
4130         break;
4131       case MVT::v4f32:
4132       case MVT::v4i32:
4133       case MVT::v8i16:
4134       case MVT::v16i8:
4135         // Nothing to do, we're only looking at Nonvector args here.
4136         break;
4137       }
4138     }
4139   }
4140   // We've found where the vector parameter area in memory is.  Skip the
4141   // first 12 parameters; these don't use that memory.
4142   VecArgOffset = ((VecArgOffset+15)/16)*16;
4143   VecArgOffset += 12*16;
4144 
4145   // Add DAG nodes to load the arguments or copy them out of registers.  On
4146   // entry to a function on PPC, the arguments start after the linkage area,
4147   // although the first ones are often in registers.
4148 
4149   SmallVector<SDValue, 8> MemOps;
4150   unsigned nAltivecParamsAtEnd = 0;
4151   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4152   unsigned CurArgIdx = 0;
4153   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4154     SDValue ArgVal;
4155     bool needsLoad = false;
4156     EVT ObjectVT = Ins[ArgNo].VT;
4157     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4158     unsigned ArgSize = ObjSize;
4159     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4160     if (Ins[ArgNo].isOrigArg()) {
4161       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4162       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4163     }
4164     unsigned CurArgOffset = ArgOffset;
4165 
4166     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4167     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4168         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4169       if (isVarArg || isPPC64) {
4170         MinReservedArea = ((MinReservedArea+15)/16)*16;
4171         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4172                                                   Flags,
4173                                                   PtrByteSize);
4174       } else  nAltivecParamsAtEnd++;
4175     } else
4176       // Calculate min reserved area.
4177       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4178                                                 Flags,
4179                                                 PtrByteSize);
4180 
4181     // FIXME the codegen can be much improved in some cases.
4182     // We do not have to keep everything in memory.
4183     if (Flags.isByVal()) {
4184       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4185 
4186       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4187       ObjSize = Flags.getByValSize();
4188       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4189       // Objects of size 1 and 2 are right justified, everything else is
4190       // left justified.  This means the memory address is adjusted forwards.
4191       if (ObjSize==1 || ObjSize==2) {
4192         CurArgOffset = CurArgOffset + (4 - ObjSize);
4193       }
4194       // The value of the object is its address.
4195       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4196       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4197       InVals.push_back(FIN);
4198       if (ObjSize==1 || ObjSize==2) {
4199         if (GPR_idx != Num_GPR_Regs) {
4200           unsigned VReg;
4201           if (isPPC64)
4202             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4203           else
4204             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4205           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4206           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4207           SDValue Store =
4208               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4209                                 MachinePointerInfo(&*FuncArg), ObjType);
4210           MemOps.push_back(Store);
4211           ++GPR_idx;
4212         }
4213 
4214         ArgOffset += PtrByteSize;
4215 
4216         continue;
4217       }
4218       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4219         // Store whatever pieces of the object are in registers
4220         // to memory.  ArgOffset will be the address of the beginning
4221         // of the object.
4222         if (GPR_idx != Num_GPR_Regs) {
4223           unsigned VReg;
4224           if (isPPC64)
4225             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4226           else
4227             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4228           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4229           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4230           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4231           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4232                                        MachinePointerInfo(&*FuncArg, j));
4233           MemOps.push_back(Store);
4234           ++GPR_idx;
4235           ArgOffset += PtrByteSize;
4236         } else {
4237           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4238           break;
4239         }
4240       }
4241       continue;
4242     }
4243 
4244     switch (ObjectVT.getSimpleVT().SimpleTy) {
4245     default: llvm_unreachable("Unhandled argument type!");
4246     case MVT::i1:
4247     case MVT::i32:
4248       if (!isPPC64) {
4249         if (GPR_idx != Num_GPR_Regs) {
4250           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4251           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4252 
4253           if (ObjectVT == MVT::i1)
4254             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4255 
4256           ++GPR_idx;
4257         } else {
4258           needsLoad = true;
4259           ArgSize = PtrByteSize;
4260         }
4261         // All int arguments reserve stack space in the Darwin ABI.
4262         ArgOffset += PtrByteSize;
4263         break;
4264       }
4265       LLVM_FALLTHROUGH;
4266     case MVT::i64:  // PPC64
4267       if (GPR_idx != Num_GPR_Regs) {
4268         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4269         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4270 
4271         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4272           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4273           // value to MVT::i64 and then truncate to the correct register size.
4274           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4275 
4276         ++GPR_idx;
4277       } else {
4278         needsLoad = true;
4279         ArgSize = PtrByteSize;
4280       }
4281       // All int arguments reserve stack space in the Darwin ABI.
4282       ArgOffset += 8;
4283       break;
4284 
4285     case MVT::f32:
4286     case MVT::f64:
4287       // Every 4 bytes of argument space consumes one of the GPRs available for
4288       // argument passing.
4289       if (GPR_idx != Num_GPR_Regs) {
4290         ++GPR_idx;
4291         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4292           ++GPR_idx;
4293       }
4294       if (FPR_idx != Num_FPR_Regs) {
4295         unsigned VReg;
4296 
4297         if (ObjectVT == MVT::f32)
4298           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4299         else
4300           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4301 
4302         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4303         ++FPR_idx;
4304       } else {
4305         needsLoad = true;
4306       }
4307 
4308       // All FP arguments reserve stack space in the Darwin ABI.
4309       ArgOffset += isPPC64 ? 8 : ObjSize;
4310       break;
4311     case MVT::v4f32:
4312     case MVT::v4i32:
4313     case MVT::v8i16:
4314     case MVT::v16i8:
4315       // Note that vector arguments in registers don't reserve stack space,
4316       // except in varargs functions.
4317       if (VR_idx != Num_VR_Regs) {
4318         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4319         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4320         if (isVarArg) {
4321           while ((ArgOffset % 16) != 0) {
4322             ArgOffset += PtrByteSize;
4323             if (GPR_idx != Num_GPR_Regs)
4324               GPR_idx++;
4325           }
4326           ArgOffset += 16;
4327           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4328         }
4329         ++VR_idx;
4330       } else {
4331         if (!isVarArg && !isPPC64) {
4332           // Vectors go after all the nonvectors.
4333           CurArgOffset = VecArgOffset;
4334           VecArgOffset += 16;
4335         } else {
4336           // Vectors are aligned.
4337           ArgOffset = ((ArgOffset+15)/16)*16;
4338           CurArgOffset = ArgOffset;
4339           ArgOffset += 16;
4340         }
4341         needsLoad = true;
4342       }
4343       break;
4344     }
4345 
4346     // We need to load the argument to a virtual register if we determined above
4347     // that we ran out of physical registers of the appropriate type.
4348     if (needsLoad) {
4349       int FI = MFI.CreateFixedObject(ObjSize,
4350                                      CurArgOffset + (ArgSize - ObjSize),
4351                                      isImmutable);
4352       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4353       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4354     }
4355 
4356     InVals.push_back(ArgVal);
4357   }
4358 
4359   // Allow for Altivec parameters at the end, if needed.
4360   if (nAltivecParamsAtEnd) {
4361     MinReservedArea = ((MinReservedArea+15)/16)*16;
4362     MinReservedArea += 16*nAltivecParamsAtEnd;
4363   }
4364 
4365   // Area that is at least reserved in the caller of this function.
4366   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4367 
4368   // Set the size that is at least reserved in caller of this function.  Tail
4369   // call optimized functions' reserved stack space needs to be aligned so that
4370   // taking the difference between two stack areas will result in an aligned
4371   // stack.
4372   MinReservedArea =
4373       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4374   FuncInfo->setMinReservedArea(MinReservedArea);
4375 
4376   // If the function takes variable number of arguments, make a frame index for
4377   // the start of the first vararg value... for expansion of llvm.va_start.
4378   if (isVarArg) {
4379     int Depth = ArgOffset;
4380 
4381     FuncInfo->setVarArgsFrameIndex(
4382       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4383                             Depth, true));
4384     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4385 
4386     // If this function is vararg, store any remaining integer argument regs
4387     // to their spots on the stack so that they may be loaded by dereferencing
4388     // the result of va_next.
4389     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4390       unsigned VReg;
4391 
4392       if (isPPC64)
4393         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4394       else
4395         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4396 
4397       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4398       SDValue Store =
4399           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4400       MemOps.push_back(Store);
4401       // Increment the address by four for the next argument to store
4402       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4403       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4404     }
4405   }
4406 
4407   if (!MemOps.empty())
4408     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4409 
4410   return Chain;
4411 }
4412 
4413 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4414 /// adjusted to accommodate the arguments for the tailcall.
4415 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4416                                    unsigned ParamSize) {
4417 
4418   if (!isTailCall) return 0;
4419 
4420   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4421   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4422   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4423   // Remember only if the new adjustment is bigger.
4424   if (SPDiff < FI->getTailCallSPDelta())
4425     FI->setTailCallSPDelta(SPDiff);
4426 
4427   return SPDiff;
4428 }
4429 
4430 static bool isFunctionGlobalAddress(SDValue Callee);
4431 
4432 static bool
4433 callsShareTOCBase(const Function *Caller, SDValue Callee,
4434                     const TargetMachine &TM) {
4435   // Need a GlobalValue to determine if a Caller and Callee share the same
4436   // TOCBase.
4437   const GlobalValue *GV = nullptr;
4438 
4439   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4440     GV = G->getGlobal();
4441   } else if (MCSymbolSDNode *M = dyn_cast<MCSymbolSDNode>(Callee)) {
4442     // On AIX only, we replace GlobalAddressSDNode with MCSymbolSDNode for
4443     // the callee of a direct function call. The MCSymbolSDNode contains the
4444     // MCSymbol for the funtion entry point.
4445     const auto *S = cast<MCSymbolXCOFF>(M->getMCSymbol());
4446     GV = S->getGlobalValue();
4447   }
4448 
4449   // If we failed to get a GlobalValue, then pessimistically assume they do not
4450   // share a TOCBase.
4451   if (!GV)
4452     return false;
4453 
4454   // The medium and large code models are expected to provide a sufficiently
4455   // large TOC to provide all data addressing needs of a module with a
4456   // single TOC. Since each module will be addressed with a single TOC then we
4457   // only need to check that caller and callee don't cross dso boundaries.
4458   if (CodeModel::Medium == TM.getCodeModel() ||
4459       CodeModel::Large == TM.getCodeModel())
4460     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4461 
4462   // Otherwise we need to ensure callee and caller are in the same section,
4463   // since the linker may allocate multiple TOCs, and we don't know which
4464   // sections will belong to the same TOC base.
4465 
4466   if (!GV->isStrongDefinitionForLinker())
4467     return false;
4468 
4469   // Any explicitly-specified sections and section prefixes must also match.
4470   // Also, if we're using -ffunction-sections, then each function is always in
4471   // a different section (the same is true for COMDAT functions).
4472   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4473       GV->getSection() != Caller->getSection())
4474     return false;
4475   if (const auto *F = dyn_cast<Function>(GV)) {
4476     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4477       return false;
4478   }
4479 
4480   // If the callee might be interposed, then we can't assume the ultimate call
4481   // target will be in the same section. Even in cases where we can assume that
4482   // interposition won't happen, in any case where the linker might insert a
4483   // stub to allow for interposition, we must generate code as though
4484   // interposition might occur. To understand why this matters, consider a
4485   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4486   // in the same section, but a is in a different module (i.e. has a different
4487   // TOC base pointer). If the linker allows for interposition between b and c,
4488   // then it will generate a stub for the call edge between b and c which will
4489   // save the TOC pointer into the designated stack slot allocated by b. If we
4490   // return true here, and therefore allow a tail call between b and c, that
4491   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4492   // pointer into the stack slot allocated by a (where the a -> b stub saved
4493   // a's TOC base pointer). If we're not considering a tail call, but rather,
4494   // whether a nop is needed after the call instruction in b, because the linker
4495   // will insert a stub, it might complain about a missing nop if we omit it
4496   // (although many don't complain in this case).
4497   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4498     return false;
4499 
4500   return true;
4501 }
4502 
4503 static bool
4504 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4505                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4506   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4507 
4508   const unsigned PtrByteSize = 8;
4509   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4510 
4511   static const MCPhysReg GPR[] = {
4512     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4513     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4514   };
4515   static const MCPhysReg VR[] = {
4516     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4517     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4518   };
4519 
4520   const unsigned NumGPRs = array_lengthof(GPR);
4521   const unsigned NumFPRs = 13;
4522   const unsigned NumVRs = array_lengthof(VR);
4523   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4524 
4525   unsigned NumBytes = LinkageSize;
4526   unsigned AvailableFPRs = NumFPRs;
4527   unsigned AvailableVRs = NumVRs;
4528 
4529   for (const ISD::OutputArg& Param : Outs) {
4530     if (Param.Flags.isNest()) continue;
4531 
4532     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4533                                PtrByteSize, LinkageSize, ParamAreaSize,
4534                                NumBytes, AvailableFPRs, AvailableVRs,
4535                                Subtarget.hasQPX()))
4536       return true;
4537   }
4538   return false;
4539 }
4540 
4541 static bool
4542 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4543   if (CS.arg_size() != CallerFn->arg_size())
4544     return false;
4545 
4546   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4547   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4548   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4549 
4550   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4551     const Value* CalleeArg = *CalleeArgIter;
4552     const Value* CallerArg = &(*CallerArgIter);
4553     if (CalleeArg == CallerArg)
4554       continue;
4555 
4556     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4557     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4558     //      }
4559     // 1st argument of callee is undef and has the same type as caller.
4560     if (CalleeArg->getType() == CallerArg->getType() &&
4561         isa<UndefValue>(CalleeArg))
4562       continue;
4563 
4564     return false;
4565   }
4566 
4567   return true;
4568 }
4569 
4570 // Returns true if TCO is possible between the callers and callees
4571 // calling conventions.
4572 static bool
4573 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4574                                     CallingConv::ID CalleeCC) {
4575   // Tail calls are possible with fastcc and ccc.
4576   auto isTailCallableCC  = [] (CallingConv::ID CC){
4577       return  CC == CallingConv::C || CC == CallingConv::Fast;
4578   };
4579   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4580     return false;
4581 
4582   // We can safely tail call both fastcc and ccc callees from a c calling
4583   // convention caller. If the caller is fastcc, we may have less stack space
4584   // than a non-fastcc caller with the same signature so disable tail-calls in
4585   // that case.
4586   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4587 }
4588 
4589 bool
4590 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4591                                     SDValue Callee,
4592                                     CallingConv::ID CalleeCC,
4593                                     ImmutableCallSite CS,
4594                                     bool isVarArg,
4595                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4596                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4597                                     SelectionDAG& DAG) const {
4598   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4599 
4600   if (DisableSCO && !TailCallOpt) return false;
4601 
4602   // Variadic argument functions are not supported.
4603   if (isVarArg) return false;
4604 
4605   auto &Caller = DAG.getMachineFunction().getFunction();
4606   // Check that the calling conventions are compatible for tco.
4607   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4608     return false;
4609 
4610   // Caller contains any byval parameter is not supported.
4611   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4612     return false;
4613 
4614   // Callee contains any byval parameter is not supported, too.
4615   // Note: This is a quick work around, because in some cases, e.g.
4616   // caller's stack size > callee's stack size, we are still able to apply
4617   // sibling call optimization. For example, gcc is able to do SCO for caller1
4618   // in the following example, but not for caller2.
4619   //   struct test {
4620   //     long int a;
4621   //     char ary[56];
4622   //   } gTest;
4623   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4624   //     b->a = v.a;
4625   //     return 0;
4626   //   }
4627   //   void caller1(struct test a, struct test c, struct test *b) {
4628   //     callee(gTest, b); }
4629   //   void caller2(struct test *b) { callee(gTest, b); }
4630   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4631     return false;
4632 
4633   // If callee and caller use different calling conventions, we cannot pass
4634   // parameters on stack since offsets for the parameter area may be different.
4635   if (Caller.getCallingConv() != CalleeCC &&
4636       needStackSlotPassParameters(Subtarget, Outs))
4637     return false;
4638 
4639   // No TCO/SCO on indirect call because Caller have to restore its TOC
4640   if (!isFunctionGlobalAddress(Callee) &&
4641       !isa<ExternalSymbolSDNode>(Callee))
4642     return false;
4643 
4644   // If the caller and callee potentially have different TOC bases then we
4645   // cannot tail call since we need to restore the TOC pointer after the call.
4646   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4647   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4648     return false;
4649 
4650   // TCO allows altering callee ABI, so we don't have to check further.
4651   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4652     return true;
4653 
4654   if (DisableSCO) return false;
4655 
4656   // If callee use the same argument list that caller is using, then we can
4657   // apply SCO on this case. If it is not, then we need to check if callee needs
4658   // stack for passing arguments.
4659   if (!hasSameArgumentList(&Caller, CS) &&
4660       needStackSlotPassParameters(Subtarget, Outs)) {
4661     return false;
4662   }
4663 
4664   return true;
4665 }
4666 
4667 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4668 /// for tail call optimization. Targets which want to do tail call
4669 /// optimization should implement this function.
4670 bool
4671 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4672                                                      CallingConv::ID CalleeCC,
4673                                                      bool isVarArg,
4674                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4675                                                      SelectionDAG& DAG) const {
4676   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4677     return false;
4678 
4679   // Variable argument functions are not supported.
4680   if (isVarArg)
4681     return false;
4682 
4683   MachineFunction &MF = DAG.getMachineFunction();
4684   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4685   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4686     // Functions containing by val parameters are not supported.
4687     for (unsigned i = 0; i != Ins.size(); i++) {
4688        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4689        if (Flags.isByVal()) return false;
4690     }
4691 
4692     // Non-PIC/GOT tail calls are supported.
4693     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4694       return true;
4695 
4696     // At the moment we can only do local tail calls (in same module, hidden
4697     // or protected) if we are generating PIC.
4698     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4699       return G->getGlobal()->hasHiddenVisibility()
4700           || G->getGlobal()->hasProtectedVisibility();
4701   }
4702 
4703   return false;
4704 }
4705 
4706 /// isCallCompatibleAddress - Return the immediate to use if the specified
4707 /// 32-bit value is representable in the immediate field of a BxA instruction.
4708 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4709   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4710   if (!C) return nullptr;
4711 
4712   int Addr = C->getZExtValue();
4713   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4714       SignExtend32<26>(Addr) != Addr)
4715     return nullptr;  // Top 6 bits have to be sext of immediate.
4716 
4717   return DAG
4718       .getConstant(
4719           (int)C->getZExtValue() >> 2, SDLoc(Op),
4720           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4721       .getNode();
4722 }
4723 
4724 namespace {
4725 
4726 struct TailCallArgumentInfo {
4727   SDValue Arg;
4728   SDValue FrameIdxOp;
4729   int FrameIdx = 0;
4730 
4731   TailCallArgumentInfo() = default;
4732 };
4733 
4734 } // end anonymous namespace
4735 
4736 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4737 static void StoreTailCallArgumentsToStackSlot(
4738     SelectionDAG &DAG, SDValue Chain,
4739     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4740     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4741   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4742     SDValue Arg = TailCallArgs[i].Arg;
4743     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4744     int FI = TailCallArgs[i].FrameIdx;
4745     // Store relative to framepointer.
4746     MemOpChains.push_back(DAG.getStore(
4747         Chain, dl, Arg, FIN,
4748         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4749   }
4750 }
4751 
4752 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4753 /// the appropriate stack slot for the tail call optimized function call.
4754 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4755                                              SDValue OldRetAddr, SDValue OldFP,
4756                                              int SPDiff, const SDLoc &dl) {
4757   if (SPDiff) {
4758     // Calculate the new stack slot for the return address.
4759     MachineFunction &MF = DAG.getMachineFunction();
4760     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4761     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4762     bool isPPC64 = Subtarget.isPPC64();
4763     int SlotSize = isPPC64 ? 8 : 4;
4764     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4765     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4766                                                          NewRetAddrLoc, true);
4767     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4768     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4769     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4770                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4771 
4772     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4773     // slot as the FP is never overwritten.
4774     if (Subtarget.isDarwinABI()) {
4775       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4776       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4777                                                          true);
4778       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4779       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4780                            MachinePointerInfo::getFixedStack(
4781                                DAG.getMachineFunction(), NewFPIdx));
4782     }
4783   }
4784   return Chain;
4785 }
4786 
4787 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4788 /// the position of the argument.
4789 static void
4790 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4791                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4792                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4793   int Offset = ArgOffset + SPDiff;
4794   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4795   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4796   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4797   SDValue FIN = DAG.getFrameIndex(FI, VT);
4798   TailCallArgumentInfo Info;
4799   Info.Arg = Arg;
4800   Info.FrameIdxOp = FIN;
4801   Info.FrameIdx = FI;
4802   TailCallArguments.push_back(Info);
4803 }
4804 
4805 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4806 /// stack slot. Returns the chain as result and the loaded frame pointers in
4807 /// LROpOut/FPOpout. Used when tail calling.
4808 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4809     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4810     SDValue &FPOpOut, const SDLoc &dl) const {
4811   if (SPDiff) {
4812     // Load the LR and FP stack slot for later adjusting.
4813     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4814     LROpOut = getReturnAddrFrameIndex(DAG);
4815     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4816     Chain = SDValue(LROpOut.getNode(), 1);
4817 
4818     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4819     // slot as the FP is never overwritten.
4820     if (Subtarget.isDarwinABI()) {
4821       FPOpOut = getFramePointerFrameIndex(DAG);
4822       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4823       Chain = SDValue(FPOpOut.getNode(), 1);
4824     }
4825   }
4826   return Chain;
4827 }
4828 
4829 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4830 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4831 /// specified by the specific parameter attribute. The copy will be passed as
4832 /// a byval function parameter.
4833 /// Sometimes what we are copying is the end of a larger object, the part that
4834 /// does not fit in registers.
4835 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4836                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4837                                          SelectionDAG &DAG, const SDLoc &dl) {
4838   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4839   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4840                        false, false, false, MachinePointerInfo(),
4841                        MachinePointerInfo());
4842 }
4843 
4844 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4845 /// tail calls.
4846 static void LowerMemOpCallTo(
4847     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4848     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4849     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4850     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4851   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4852   if (!isTailCall) {
4853     if (isVector) {
4854       SDValue StackPtr;
4855       if (isPPC64)
4856         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4857       else
4858         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4859       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4860                            DAG.getConstant(ArgOffset, dl, PtrVT));
4861     }
4862     MemOpChains.push_back(
4863         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4864     // Calculate and remember argument location.
4865   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4866                                   TailCallArguments);
4867 }
4868 
4869 static void
4870 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4871                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4872                 SDValue FPOp,
4873                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4874   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4875   // might overwrite each other in case of tail call optimization.
4876   SmallVector<SDValue, 8> MemOpChains2;
4877   // Do not flag preceding copytoreg stuff together with the following stuff.
4878   InFlag = SDValue();
4879   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4880                                     MemOpChains2, dl);
4881   if (!MemOpChains2.empty())
4882     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4883 
4884   // Store the return address to the appropriate stack slot.
4885   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4886 
4887   // Emit callseq_end just before tailcall node.
4888   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4889                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4890   InFlag = Chain.getValue(1);
4891 }
4892 
4893 // Is this global address that of a function that can be called by name? (as
4894 // opposed to something that must hold a descriptor for an indirect call).
4895 static bool isFunctionGlobalAddress(SDValue Callee) {
4896   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4897     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4898         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4899       return false;
4900 
4901     return G->getGlobal()->getValueType()->isFunctionTy();
4902   }
4903 
4904   return false;
4905 }
4906 
4907 static unsigned
4908 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4909             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4910             bool isPatchPoint, bool hasNest,
4911             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4912             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4913             ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4914   bool isPPC64 = Subtarget.isPPC64();
4915   bool isSVR4ABI = Subtarget.isSVR4ABI();
4916   bool isELFv2ABI = Subtarget.isELFv2ABI();
4917   bool isAIXABI = Subtarget.isAIXABI();
4918 
4919   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4920   NodeTys.push_back(MVT::Other);   // Returns a chain
4921   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4922 
4923   unsigned CallOpc = PPCISD::CALL;
4924 
4925   bool needIndirectCall = true;
4926   if (!isSVR4ABI || !isPPC64)
4927     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4928       // If this is an absolute destination address, use the munged value.
4929       Callee = SDValue(Dest, 0);
4930       needIndirectCall = false;
4931     }
4932 
4933   // PC-relative references to external symbols should go through $stub, unless
4934   // we're building with the leopard linker or later, which automatically
4935   // synthesizes these stubs.
4936   const TargetMachine &TM = DAG.getTarget();
4937   MachineFunction &MF = DAG.getMachineFunction();
4938   const Module *Mod = MF.getFunction().getParent();
4939   const GlobalValue *GV = nullptr;
4940   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4941     GV = G->getGlobal();
4942   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4943   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4944 
4945   if (isFunctionGlobalAddress(Callee)) {
4946     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4947 
4948     if (TM.getTargetTriple().isOSAIX()) {
4949       // Direct function calls reference the symbol for the function's entry
4950       // point, which is named by inserting a "." before the function's
4951       // C-linkage name.
4952       auto &Context = MF.getMMI().getContext();
4953       MCSymbol *S = Context.getOrCreateSymbol(Twine(".") +
4954                                               Twine(G->getGlobal()->getName()));
4955       cast<MCSymbolXCOFF>(S)->setGlobalValue(GV);
4956       Callee = DAG.getMCSymbol(S, PtrVT);
4957     } else {
4958       // A call to a TLS address is actually an indirect call to a
4959       // thread-specific pointer.
4960       unsigned OpFlags = 0;
4961       if (UsePlt)
4962         OpFlags = PPCII::MO_PLT;
4963 
4964       // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4965       // every direct call is) turn it into a TargetGlobalAddress /
4966       // TargetExternalSymbol node so that legalize doesn't hack it.
4967       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4968                                           Callee.getValueType(), 0, OpFlags);
4969     }
4970     needIndirectCall = false;
4971   }
4972 
4973   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4974     unsigned char OpFlags = 0;
4975 
4976     if (UsePlt)
4977       OpFlags = PPCII::MO_PLT;
4978 
4979     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4980                                          OpFlags);
4981     needIndirectCall = false;
4982   }
4983 
4984   if (isPatchPoint) {
4985     // We'll form an invalid direct call when lowering a patchpoint; the full
4986     // sequence for an indirect call is complicated, and many of the
4987     // instructions introduced might have side effects (and, thus, can't be
4988     // removed later). The call itself will be removed as soon as the
4989     // argument/return lowering is complete, so the fact that it has the wrong
4990     // kind of operands should not really matter.
4991     needIndirectCall = false;
4992   }
4993 
4994   if (needIndirectCall) {
4995     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4996     // to do the call, we can't use PPCISD::CALL.
4997     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4998 
4999     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
5000       // Function pointers in the 64-bit SVR4 ABI do not point to the function
5001       // entry point, but to the function descriptor (the function entry point
5002       // address is part of the function descriptor though).
5003       // The function descriptor is a three doubleword structure with the
5004       // following fields: function entry point, TOC base address and
5005       // environment pointer.
5006       // Thus for a call through a function pointer, the following actions need
5007       // to be performed:
5008       //   1. Save the TOC of the caller in the TOC save area of its stack
5009       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5010       //   2. Load the address of the function entry point from the function
5011       //      descriptor.
5012       //   3. Load the TOC of the callee from the function descriptor into r2.
5013       //   4. Load the environment pointer from the function descriptor into
5014       //      r11.
5015       //   5. Branch to the function entry point address.
5016       //   6. On return of the callee, the TOC of the caller needs to be
5017       //      restored (this is done in FinishCall()).
5018       //
5019       // The loads are scheduled at the beginning of the call sequence, and the
5020       // register copies are flagged together to ensure that no other
5021       // operations can be scheduled in between. E.g. without flagging the
5022       // copies together, a TOC access in the caller could be scheduled between
5023       // the assignment of the callee TOC and the branch to the callee, which
5024       // results in the TOC access going through the TOC of the callee instead
5025       // of going through the TOC of the caller, which leads to incorrect code.
5026 
5027       // Load the address of the function entry point from the function
5028       // descriptor.
5029       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
5030       if (LDChain.getValueType() == MVT::Glue)
5031         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
5032 
5033       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5034                           ? (MachineMemOperand::MODereferenceable |
5035                              MachineMemOperand::MOInvariant)
5036                           : MachineMemOperand::MONone;
5037 
5038       MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5039       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
5040                                         /* Alignment = */ 8, MMOFlags);
5041 
5042       // Load environment pointer into r11.
5043       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
5044       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
5045       SDValue LoadEnvPtr =
5046           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
5047                       /* Alignment = */ 8, MMOFlags);
5048 
5049       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
5050       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
5051       SDValue TOCPtr =
5052           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
5053                       /* Alignment = */ 8, MMOFlags);
5054 
5055       setUsesTOCBasePtr(DAG);
5056       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
5057                                         InFlag);
5058       Chain = TOCVal.getValue(0);
5059       InFlag = TOCVal.getValue(1);
5060 
5061       // If the function call has an explicit 'nest' parameter, it takes the
5062       // place of the environment pointer.
5063       if (!hasNest) {
5064         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
5065                                           InFlag);
5066 
5067         Chain = EnvVal.getValue(0);
5068         InFlag = EnvVal.getValue(1);
5069       }
5070 
5071       MTCTROps[0] = Chain;
5072       MTCTROps[1] = LoadFuncPtr;
5073       MTCTROps[2] = InFlag;
5074     }
5075 
5076     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
5077                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
5078     InFlag = Chain.getValue(1);
5079 
5080     NodeTys.clear();
5081     NodeTys.push_back(MVT::Other);
5082     NodeTys.push_back(MVT::Glue);
5083     Ops.push_back(Chain);
5084     CallOpc = PPCISD::BCTRL;
5085     Callee.setNode(nullptr);
5086     // Add use of X11 (holding environment pointer)
5087     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
5088       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
5089     // Add CTR register as callee so a bctr can be emitted later.
5090     if (isTailCall)
5091       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
5092   }
5093 
5094   // If this is a direct call, pass the chain and the callee.
5095   if (Callee.getNode()) {
5096     Ops.push_back(Chain);
5097     Ops.push_back(Callee);
5098   }
5099   // If this is a tail call add stack pointer delta.
5100   if (isTailCall)
5101     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5102 
5103   // Add argument registers to the end of the list so that they are known live
5104   // into the call.
5105   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5106     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5107                                   RegsToPass[i].second.getValueType()));
5108 
5109   // All calls, in the AIX ABI and 64-bit ELF ABIs, need the TOC register
5110   // live into the call.
5111   // We do need to reserve R2/X2 to appease the verifier for the PATCHPOINT.
5112   if ((isSVR4ABI && isPPC64) || isAIXABI) {
5113     setUsesTOCBasePtr(DAG);
5114 
5115     // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5116     // no way to mark dependencies as implicit here.
5117     // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5118     if (!isPatchPoint)
5119       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::X2
5120                                             : PPC::R2, PtrVT));
5121   }
5122 
5123   return CallOpc;
5124 }
5125 
5126 SDValue PPCTargetLowering::LowerCallResult(
5127     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5128     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5129     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5130   SmallVector<CCValAssign, 16> RVLocs;
5131   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5132                     *DAG.getContext());
5133 
5134   CCRetInfo.AnalyzeCallResult(
5135       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5136                ? RetCC_PPC_Cold
5137                : RetCC_PPC);
5138 
5139   // Copy all of the result registers out of their specified physreg.
5140   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5141     CCValAssign &VA = RVLocs[i];
5142     assert(VA.isRegLoc() && "Can only return in registers!");
5143 
5144     SDValue Val;
5145 
5146     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5147       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5148                                       InFlag);
5149       Chain = Lo.getValue(1);
5150       InFlag = Lo.getValue(2);
5151       VA = RVLocs[++i]; // skip ahead to next loc
5152       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5153                                       InFlag);
5154       Chain = Hi.getValue(1);
5155       InFlag = Hi.getValue(2);
5156       if (!Subtarget.isLittleEndian())
5157         std::swap (Lo, Hi);
5158       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5159     } else {
5160       Val = DAG.getCopyFromReg(Chain, dl,
5161                                VA.getLocReg(), VA.getLocVT(), InFlag);
5162       Chain = Val.getValue(1);
5163       InFlag = Val.getValue(2);
5164     }
5165 
5166     switch (VA.getLocInfo()) {
5167     default: llvm_unreachable("Unknown loc info!");
5168     case CCValAssign::Full: break;
5169     case CCValAssign::AExt:
5170       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5171       break;
5172     case CCValAssign::ZExt:
5173       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5174                         DAG.getValueType(VA.getValVT()));
5175       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5176       break;
5177     case CCValAssign::SExt:
5178       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5179                         DAG.getValueType(VA.getValVT()));
5180       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5181       break;
5182     }
5183 
5184     InVals.push_back(Val);
5185   }
5186 
5187   return Chain;
5188 }
5189 
5190 SDValue PPCTargetLowering::FinishCall(
5191     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5192     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5193     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
5194     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5195     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5196     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5197   std::vector<EVT> NodeTys;
5198   SmallVector<SDValue, 8> Ops;
5199   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
5200                                  SPDiff, isTailCall, isPatchPoint, hasNest,
5201                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
5202 
5203   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5204   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
5205     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5206 
5207   // When performing tail call optimization the callee pops its arguments off
5208   // the stack. Account for this here so these bytes can be pushed back on in
5209   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5210   int BytesCalleePops =
5211     (CallConv == CallingConv::Fast &&
5212      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
5213 
5214   // Add a register mask operand representing the call-preserved registers.
5215   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5216   const uint32_t *Mask =
5217       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5218   assert(Mask && "Missing call preserved mask for calling convention");
5219   Ops.push_back(DAG.getRegisterMask(Mask));
5220 
5221   if (InFlag.getNode())
5222     Ops.push_back(InFlag);
5223 
5224   // Emit tail call.
5225   if (isTailCall) {
5226     assert(((Callee.getOpcode() == ISD::Register &&
5227              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5228             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5229             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5230             isa<ConstantSDNode>(Callee)) &&
5231     "Expecting an global address, external symbol, absolute value or register");
5232 
5233     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5234     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5235   }
5236 
5237   // Add a NOP immediately after the branch instruction when using the 64-bit
5238   // SVR4 or the AIX ABI.
5239   // At link time, if caller and callee are in a different module and
5240   // thus have a different TOC, the call will be replaced with a call to a stub
5241   // function which saves the current TOC, loads the TOC of the callee and
5242   // branches to the callee. The NOP will be replaced with a load instruction
5243   // which restores the TOC of the caller from the TOC save slot of the current
5244   // stack frame. If caller and callee belong to the same module (and have the
5245   // same TOC), the NOP will remain unchanged, or become some other NOP.
5246 
5247   MachineFunction &MF = DAG.getMachineFunction();
5248   if (!isTailCall && !isPatchPoint &&
5249       ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) ||
5250        Subtarget.isAIXABI())) {
5251     if (CallOpc == PPCISD::BCTRL) {
5252       if (Subtarget.isAIXABI())
5253         report_fatal_error("Indirect call on AIX is not implemented.");
5254 
5255       // This is a call through a function pointer.
5256       // Restore the caller TOC from the save area into R2.
5257       // See PrepareCall() for more information about calls through function
5258       // pointers in the 64-bit SVR4 ABI.
5259       // We are using a target-specific load with r2 hard coded, because the
5260       // result of a target-independent load would never go directly into r2,
5261       // since r2 is a reserved register (which prevents the register allocator
5262       // from allocating it), resulting in an additional register being
5263       // allocated and an unnecessary move instruction being generated.
5264       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5265 
5266       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5267       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5268       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5269       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5270       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5271 
5272       // The address needs to go after the chain input but before the flag (or
5273       // any other variadic arguments).
5274       Ops.insert(std::next(Ops.begin()), AddTOC);
5275     } else if (CallOpc == PPCISD::CALL &&
5276       !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5277       // Otherwise insert NOP for non-local calls.
5278       CallOpc = PPCISD::CALL_NOP;
5279     }
5280   }
5281 
5282   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5283   InFlag = Chain.getValue(1);
5284 
5285   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5286                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5287                              InFlag, dl);
5288   if (!Ins.empty())
5289     InFlag = Chain.getValue(1);
5290 
5291   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5292                          Ins, dl, DAG, InVals);
5293 }
5294 
5295 SDValue
5296 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5297                              SmallVectorImpl<SDValue> &InVals) const {
5298   SelectionDAG &DAG                     = CLI.DAG;
5299   SDLoc &dl                             = CLI.DL;
5300   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5301   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5302   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5303   SDValue Chain                         = CLI.Chain;
5304   SDValue Callee                        = CLI.Callee;
5305   bool &isTailCall                      = CLI.IsTailCall;
5306   CallingConv::ID CallConv              = CLI.CallConv;
5307   bool isVarArg                         = CLI.IsVarArg;
5308   bool isPatchPoint                     = CLI.IsPatchPoint;
5309   ImmutableCallSite CS                  = CLI.CS;
5310 
5311   if (isTailCall) {
5312     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5313       isTailCall = false;
5314     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5315       isTailCall =
5316         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5317                                                  isVarArg, Outs, Ins, DAG);
5318     else
5319       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5320                                                      Ins, DAG);
5321     if (isTailCall) {
5322       ++NumTailCalls;
5323       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5324         ++NumSiblingCalls;
5325 
5326       assert(isa<GlobalAddressSDNode>(Callee) &&
5327              "Callee should be an llvm::Function object.");
5328       LLVM_DEBUG(
5329           const GlobalValue *GV =
5330               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5331           const unsigned Width =
5332               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5333           dbgs() << "TCO caller: "
5334                  << left_justify(DAG.getMachineFunction().getName(), Width)
5335                  << ", callee linkage: " << GV->getVisibility() << ", "
5336                  << GV->getLinkage() << "\n");
5337     }
5338   }
5339 
5340   if (!isTailCall && CS && CS.isMustTailCall())
5341     report_fatal_error("failed to perform tail call elimination on a call "
5342                        "site marked musttail");
5343 
5344   // When long calls (i.e. indirect calls) are always used, calls are always
5345   // made via function pointer. If we have a function name, first translate it
5346   // into a pointer.
5347   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5348       !isTailCall)
5349     Callee = LowerGlobalAddress(Callee, DAG);
5350 
5351   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5352     return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5353                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5354                             dl, DAG, InVals, CS);
5355 
5356   if (Subtarget.isSVR4ABI())
5357     return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5358                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5359                             dl, DAG, InVals, CS);
5360 
5361   if (Subtarget.isAIXABI())
5362     return LowerCall_AIX(Chain, Callee, CallConv, isVarArg,
5363                          isTailCall, isPatchPoint, Outs, OutVals, Ins,
5364                          dl, DAG, InVals, CS);
5365 
5366   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5367                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5368                           dl, DAG, InVals, CS);
5369 }
5370 
5371 SDValue PPCTargetLowering::LowerCall_32SVR4(
5372     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5373     bool isTailCall, bool isPatchPoint,
5374     const SmallVectorImpl<ISD::OutputArg> &Outs,
5375     const SmallVectorImpl<SDValue> &OutVals,
5376     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5377     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5378     ImmutableCallSite CS) const {
5379   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5380   // of the 32-bit SVR4 ABI stack frame layout.
5381 
5382   assert((CallConv == CallingConv::C ||
5383           CallConv == CallingConv::Cold ||
5384           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5385 
5386   unsigned PtrByteSize = 4;
5387 
5388   MachineFunction &MF = DAG.getMachineFunction();
5389 
5390   // Mark this function as potentially containing a function that contains a
5391   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5392   // and restoring the callers stack pointer in this functions epilog. This is
5393   // done because by tail calling the called function might overwrite the value
5394   // in this function's (MF) stack pointer stack slot 0(SP).
5395   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5396       CallConv == CallingConv::Fast)
5397     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5398 
5399   // Count how many bytes are to be pushed on the stack, including the linkage
5400   // area, parameter list area and the part of the local variable space which
5401   // contains copies of aggregates which are passed by value.
5402 
5403   // Assign locations to all of the outgoing arguments.
5404   SmallVector<CCValAssign, 16> ArgLocs;
5405   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5406 
5407   // Reserve space for the linkage area on the stack.
5408   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5409                        PtrByteSize);
5410   if (useSoftFloat())
5411     CCInfo.PreAnalyzeCallOperands(Outs);
5412 
5413   if (isVarArg) {
5414     // Handle fixed and variable vector arguments differently.
5415     // Fixed vector arguments go into registers as long as registers are
5416     // available. Variable vector arguments always go into memory.
5417     unsigned NumArgs = Outs.size();
5418 
5419     for (unsigned i = 0; i != NumArgs; ++i) {
5420       MVT ArgVT = Outs[i].VT;
5421       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5422       bool Result;
5423 
5424       if (Outs[i].IsFixed) {
5425         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5426                                CCInfo);
5427       } else {
5428         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5429                                       ArgFlags, CCInfo);
5430       }
5431 
5432       if (Result) {
5433 #ifndef NDEBUG
5434         errs() << "Call operand #" << i << " has unhandled type "
5435              << EVT(ArgVT).getEVTString() << "\n";
5436 #endif
5437         llvm_unreachable(nullptr);
5438       }
5439     }
5440   } else {
5441     // All arguments are treated the same.
5442     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5443   }
5444   CCInfo.clearWasPPCF128();
5445 
5446   // Assign locations to all of the outgoing aggregate by value arguments.
5447   SmallVector<CCValAssign, 16> ByValArgLocs;
5448   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5449 
5450   // Reserve stack space for the allocations in CCInfo.
5451   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5452 
5453   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5454 
5455   // Size of the linkage area, parameter list area and the part of the local
5456   // space variable where copies of aggregates which are passed by value are
5457   // stored.
5458   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5459 
5460   // Calculate by how many bytes the stack has to be adjusted in case of tail
5461   // call optimization.
5462   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5463 
5464   // Adjust the stack pointer for the new arguments...
5465   // These operations are automatically eliminated by the prolog/epilog pass
5466   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5467   SDValue CallSeqStart = Chain;
5468 
5469   // Load the return address and frame pointer so it can be moved somewhere else
5470   // later.
5471   SDValue LROp, FPOp;
5472   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5473 
5474   // Set up a copy of the stack pointer for use loading and storing any
5475   // arguments that may not fit in the registers available for argument
5476   // passing.
5477   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5478 
5479   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5480   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5481   SmallVector<SDValue, 8> MemOpChains;
5482 
5483   bool seenFloatArg = false;
5484   // Walk the register/memloc assignments, inserting copies/loads.
5485   // i - Tracks the index into the list of registers allocated for the call
5486   // RealArgIdx - Tracks the index into the list of actual function arguments
5487   // j - Tracks the index into the list of byval arguments
5488   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5489        i != e;
5490        ++i, ++RealArgIdx) {
5491     CCValAssign &VA = ArgLocs[i];
5492     SDValue Arg = OutVals[RealArgIdx];
5493     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5494 
5495     if (Flags.isByVal()) {
5496       // Argument is an aggregate which is passed by value, thus we need to
5497       // create a copy of it in the local variable space of the current stack
5498       // frame (which is the stack frame of the caller) and pass the address of
5499       // this copy to the callee.
5500       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5501       CCValAssign &ByValVA = ByValArgLocs[j++];
5502       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5503 
5504       // Memory reserved in the local variable space of the callers stack frame.
5505       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5506 
5507       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5508       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5509                            StackPtr, PtrOff);
5510 
5511       // Create a copy of the argument in the local area of the current
5512       // stack frame.
5513       SDValue MemcpyCall =
5514         CreateCopyOfByValArgument(Arg, PtrOff,
5515                                   CallSeqStart.getNode()->getOperand(0),
5516                                   Flags, DAG, dl);
5517 
5518       // This must go outside the CALLSEQ_START..END.
5519       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5520                                                      SDLoc(MemcpyCall));
5521       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5522                              NewCallSeqStart.getNode());
5523       Chain = CallSeqStart = NewCallSeqStart;
5524 
5525       // Pass the address of the aggregate copy on the stack either in a
5526       // physical register or in the parameter list area of the current stack
5527       // frame to the callee.
5528       Arg = PtrOff;
5529     }
5530 
5531     // When useCRBits() is true, there can be i1 arguments.
5532     // It is because getRegisterType(MVT::i1) => MVT::i1,
5533     // and for other integer types getRegisterType() => MVT::i32.
5534     // Extend i1 and ensure callee will get i32.
5535     if (Arg.getValueType() == MVT::i1)
5536       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5537                         dl, MVT::i32, Arg);
5538 
5539     if (VA.isRegLoc()) {
5540       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5541       // Put argument in a physical register.
5542       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5543         bool IsLE = Subtarget.isLittleEndian();
5544         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5545                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5546         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5547         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5548                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5549         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5550                              SVal.getValue(0)));
5551       } else
5552         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5553     } else {
5554       // Put argument in the parameter list area of the current stack frame.
5555       assert(VA.isMemLoc());
5556       unsigned LocMemOffset = VA.getLocMemOffset();
5557 
5558       if (!isTailCall) {
5559         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5560         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5561                              StackPtr, PtrOff);
5562 
5563         MemOpChains.push_back(
5564             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5565       } else {
5566         // Calculate and remember argument location.
5567         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5568                                  TailCallArguments);
5569       }
5570     }
5571   }
5572 
5573   if (!MemOpChains.empty())
5574     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5575 
5576   // Build a sequence of copy-to-reg nodes chained together with token chain
5577   // and flag operands which copy the outgoing args into the appropriate regs.
5578   SDValue InFlag;
5579   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5580     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5581                              RegsToPass[i].second, InFlag);
5582     InFlag = Chain.getValue(1);
5583   }
5584 
5585   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5586   // registers.
5587   if (isVarArg) {
5588     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5589     SDValue Ops[] = { Chain, InFlag };
5590 
5591     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5592                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5593 
5594     InFlag = Chain.getValue(1);
5595   }
5596 
5597   if (isTailCall)
5598     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5599                     TailCallArguments);
5600 
5601   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5602                     /* unused except on PPC64 ELFv1 */ false, DAG,
5603                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5604                     NumBytes, Ins, InVals, CS);
5605 }
5606 
5607 // Copy an argument into memory, being careful to do this outside the
5608 // call sequence for the call to which the argument belongs.
5609 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5610     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5611     SelectionDAG &DAG, const SDLoc &dl) const {
5612   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5613                         CallSeqStart.getNode()->getOperand(0),
5614                         Flags, DAG, dl);
5615   // The MEMCPY must go outside the CALLSEQ_START..END.
5616   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5617   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5618                                                  SDLoc(MemcpyCall));
5619   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5620                          NewCallSeqStart.getNode());
5621   return NewCallSeqStart;
5622 }
5623 
5624 SDValue PPCTargetLowering::LowerCall_64SVR4(
5625     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5626     bool isTailCall, bool isPatchPoint,
5627     const SmallVectorImpl<ISD::OutputArg> &Outs,
5628     const SmallVectorImpl<SDValue> &OutVals,
5629     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5630     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5631     ImmutableCallSite CS) const {
5632   bool isELFv2ABI = Subtarget.isELFv2ABI();
5633   bool isLittleEndian = Subtarget.isLittleEndian();
5634   unsigned NumOps = Outs.size();
5635   bool hasNest = false;
5636   bool IsSibCall = false;
5637 
5638   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5639   unsigned PtrByteSize = 8;
5640 
5641   MachineFunction &MF = DAG.getMachineFunction();
5642 
5643   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5644     IsSibCall = true;
5645 
5646   // Mark this function as potentially containing a function that contains a
5647   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5648   // and restoring the callers stack pointer in this functions epilog. This is
5649   // done because by tail calling the called function might overwrite the value
5650   // in this function's (MF) stack pointer stack slot 0(SP).
5651   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5652       CallConv == CallingConv::Fast)
5653     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5654 
5655   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5656          "fastcc not supported on varargs functions");
5657 
5658   // Count how many bytes are to be pushed on the stack, including the linkage
5659   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5660   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5661   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5662   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5663   unsigned NumBytes = LinkageSize;
5664   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5665   unsigned &QFPR_idx = FPR_idx;
5666 
5667   static const MCPhysReg GPR[] = {
5668     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5669     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5670   };
5671   static const MCPhysReg VR[] = {
5672     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5673     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5674   };
5675 
5676   const unsigned NumGPRs = array_lengthof(GPR);
5677   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5678   const unsigned NumVRs  = array_lengthof(VR);
5679   const unsigned NumQFPRs = NumFPRs;
5680 
5681   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5682   // can be passed to the callee in registers.
5683   // For the fast calling convention, there is another check below.
5684   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5685   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5686   if (!HasParameterArea) {
5687     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5688     unsigned AvailableFPRs = NumFPRs;
5689     unsigned AvailableVRs = NumVRs;
5690     unsigned NumBytesTmp = NumBytes;
5691     for (unsigned i = 0; i != NumOps; ++i) {
5692       if (Outs[i].Flags.isNest()) continue;
5693       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5694                                 PtrByteSize, LinkageSize, ParamAreaSize,
5695                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5696                                 Subtarget.hasQPX()))
5697         HasParameterArea = true;
5698     }
5699   }
5700 
5701   // When using the fast calling convention, we don't provide backing for
5702   // arguments that will be in registers.
5703   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5704 
5705   // Avoid allocating parameter area for fastcc functions if all the arguments
5706   // can be passed in the registers.
5707   if (CallConv == CallingConv::Fast)
5708     HasParameterArea = false;
5709 
5710   // Add up all the space actually used.
5711   for (unsigned i = 0; i != NumOps; ++i) {
5712     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5713     EVT ArgVT = Outs[i].VT;
5714     EVT OrigVT = Outs[i].ArgVT;
5715 
5716     if (Flags.isNest())
5717       continue;
5718 
5719     if (CallConv == CallingConv::Fast) {
5720       if (Flags.isByVal()) {
5721         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5722         if (NumGPRsUsed > NumGPRs)
5723           HasParameterArea = true;
5724       } else {
5725         switch (ArgVT.getSimpleVT().SimpleTy) {
5726         default: llvm_unreachable("Unexpected ValueType for argument!");
5727         case MVT::i1:
5728         case MVT::i32:
5729         case MVT::i64:
5730           if (++NumGPRsUsed <= NumGPRs)
5731             continue;
5732           break;
5733         case MVT::v4i32:
5734         case MVT::v8i16:
5735         case MVT::v16i8:
5736         case MVT::v2f64:
5737         case MVT::v2i64:
5738         case MVT::v1i128:
5739         case MVT::f128:
5740           if (++NumVRsUsed <= NumVRs)
5741             continue;
5742           break;
5743         case MVT::v4f32:
5744           // When using QPX, this is handled like a FP register, otherwise, it
5745           // is an Altivec register.
5746           if (Subtarget.hasQPX()) {
5747             if (++NumFPRsUsed <= NumFPRs)
5748               continue;
5749           } else {
5750             if (++NumVRsUsed <= NumVRs)
5751               continue;
5752           }
5753           break;
5754         case MVT::f32:
5755         case MVT::f64:
5756         case MVT::v4f64: // QPX
5757         case MVT::v4i1:  // QPX
5758           if (++NumFPRsUsed <= NumFPRs)
5759             continue;
5760           break;
5761         }
5762         HasParameterArea = true;
5763       }
5764     }
5765 
5766     /* Respect alignment of argument on the stack.  */
5767     unsigned Align =
5768       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5769     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5770 
5771     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5772     if (Flags.isInConsecutiveRegsLast())
5773       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5774   }
5775 
5776   unsigned NumBytesActuallyUsed = NumBytes;
5777 
5778   // In the old ELFv1 ABI,
5779   // the prolog code of the callee may store up to 8 GPR argument registers to
5780   // the stack, allowing va_start to index over them in memory if its varargs.
5781   // Because we cannot tell if this is needed on the caller side, we have to
5782   // conservatively assume that it is needed.  As such, make sure we have at
5783   // least enough stack space for the caller to store the 8 GPRs.
5784   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5785   // really requires memory operands, e.g. a vararg function.
5786   if (HasParameterArea)
5787     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5788   else
5789     NumBytes = LinkageSize;
5790 
5791   // Tail call needs the stack to be aligned.
5792   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5793       CallConv == CallingConv::Fast)
5794     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5795 
5796   int SPDiff = 0;
5797 
5798   // Calculate by how many bytes the stack has to be adjusted in case of tail
5799   // call optimization.
5800   if (!IsSibCall)
5801     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5802 
5803   // To protect arguments on the stack from being clobbered in a tail call,
5804   // force all the loads to happen before doing any other lowering.
5805   if (isTailCall)
5806     Chain = DAG.getStackArgumentTokenFactor(Chain);
5807 
5808   // Adjust the stack pointer for the new arguments...
5809   // These operations are automatically eliminated by the prolog/epilog pass
5810   if (!IsSibCall)
5811     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5812   SDValue CallSeqStart = Chain;
5813 
5814   // Load the return address and frame pointer so it can be move somewhere else
5815   // later.
5816   SDValue LROp, FPOp;
5817   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5818 
5819   // Set up a copy of the stack pointer for use loading and storing any
5820   // arguments that may not fit in the registers available for argument
5821   // passing.
5822   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5823 
5824   // Figure out which arguments are going to go in registers, and which in
5825   // memory.  Also, if this is a vararg function, floating point operations
5826   // must be stored to our stack, and loaded into integer regs as well, if
5827   // any integer regs are available for argument passing.
5828   unsigned ArgOffset = LinkageSize;
5829 
5830   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5831   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5832 
5833   SmallVector<SDValue, 8> MemOpChains;
5834   for (unsigned i = 0; i != NumOps; ++i) {
5835     SDValue Arg = OutVals[i];
5836     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5837     EVT ArgVT = Outs[i].VT;
5838     EVT OrigVT = Outs[i].ArgVT;
5839 
5840     // PtrOff will be used to store the current argument to the stack if a
5841     // register cannot be found for it.
5842     SDValue PtrOff;
5843 
5844     // We re-align the argument offset for each argument, except when using the
5845     // fast calling convention, when we need to make sure we do that only when
5846     // we'll actually use a stack slot.
5847     auto ComputePtrOff = [&]() {
5848       /* Respect alignment of argument on the stack.  */
5849       unsigned Align =
5850         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5851       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5852 
5853       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5854 
5855       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5856     };
5857 
5858     if (CallConv != CallingConv::Fast) {
5859       ComputePtrOff();
5860 
5861       /* Compute GPR index associated with argument offset.  */
5862       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5863       GPR_idx = std::min(GPR_idx, NumGPRs);
5864     }
5865 
5866     // Promote integers to 64-bit values.
5867     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5868       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5869       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5870       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5871     }
5872 
5873     // FIXME memcpy is used way more than necessary.  Correctness first.
5874     // Note: "by value" is code for passing a structure by value, not
5875     // basic types.
5876     if (Flags.isByVal()) {
5877       // Note: Size includes alignment padding, so
5878       //   struct x { short a; char b; }
5879       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5880       // These are the proper values we need for right-justifying the
5881       // aggregate in a parameter register.
5882       unsigned Size = Flags.getByValSize();
5883 
5884       // An empty aggregate parameter takes up no storage and no
5885       // registers.
5886       if (Size == 0)
5887         continue;
5888 
5889       if (CallConv == CallingConv::Fast)
5890         ComputePtrOff();
5891 
5892       // All aggregates smaller than 8 bytes must be passed right-justified.
5893       if (Size==1 || Size==2 || Size==4) {
5894         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5895         if (GPR_idx != NumGPRs) {
5896           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5897                                         MachinePointerInfo(), VT);
5898           MemOpChains.push_back(Load.getValue(1));
5899           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5900 
5901           ArgOffset += PtrByteSize;
5902           continue;
5903         }
5904       }
5905 
5906       if (GPR_idx == NumGPRs && Size < 8) {
5907         SDValue AddPtr = PtrOff;
5908         if (!isLittleEndian) {
5909           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5910                                           PtrOff.getValueType());
5911           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5912         }
5913         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5914                                                           CallSeqStart,
5915                                                           Flags, DAG, dl);
5916         ArgOffset += PtrByteSize;
5917         continue;
5918       }
5919       // Copy entire object into memory.  There are cases where gcc-generated
5920       // code assumes it is there, even if it could be put entirely into
5921       // registers.  (This is not what the doc says.)
5922 
5923       // FIXME: The above statement is likely due to a misunderstanding of the
5924       // documents.  All arguments must be copied into the parameter area BY
5925       // THE CALLEE in the event that the callee takes the address of any
5926       // formal argument.  That has not yet been implemented.  However, it is
5927       // reasonable to use the stack area as a staging area for the register
5928       // load.
5929 
5930       // Skip this for small aggregates, as we will use the same slot for a
5931       // right-justified copy, below.
5932       if (Size >= 8)
5933         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5934                                                           CallSeqStart,
5935                                                           Flags, DAG, dl);
5936 
5937       // When a register is available, pass a small aggregate right-justified.
5938       if (Size < 8 && GPR_idx != NumGPRs) {
5939         // The easiest way to get this right-justified in a register
5940         // is to copy the structure into the rightmost portion of a
5941         // local variable slot, then load the whole slot into the
5942         // register.
5943         // FIXME: The memcpy seems to produce pretty awful code for
5944         // small aggregates, particularly for packed ones.
5945         // FIXME: It would be preferable to use the slot in the
5946         // parameter save area instead of a new local variable.
5947         SDValue AddPtr = PtrOff;
5948         if (!isLittleEndian) {
5949           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5950           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5951         }
5952         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5953                                                           CallSeqStart,
5954                                                           Flags, DAG, dl);
5955 
5956         // Load the slot into the register.
5957         SDValue Load =
5958             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5959         MemOpChains.push_back(Load.getValue(1));
5960         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5961 
5962         // Done with this argument.
5963         ArgOffset += PtrByteSize;
5964         continue;
5965       }
5966 
5967       // For aggregates larger than PtrByteSize, copy the pieces of the
5968       // object that fit into registers from the parameter save area.
5969       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5970         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5971         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5972         if (GPR_idx != NumGPRs) {
5973           SDValue Load =
5974               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5975           MemOpChains.push_back(Load.getValue(1));
5976           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5977           ArgOffset += PtrByteSize;
5978         } else {
5979           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5980           break;
5981         }
5982       }
5983       continue;
5984     }
5985 
5986     switch (Arg.getSimpleValueType().SimpleTy) {
5987     default: llvm_unreachable("Unexpected ValueType for argument!");
5988     case MVT::i1:
5989     case MVT::i32:
5990     case MVT::i64:
5991       if (Flags.isNest()) {
5992         // The 'nest' parameter, if any, is passed in R11.
5993         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5994         hasNest = true;
5995         break;
5996       }
5997 
5998       // These can be scalar arguments or elements of an integer array type
5999       // passed directly.  Clang may use those instead of "byval" aggregate
6000       // types to avoid forcing arguments to memory unnecessarily.
6001       if (GPR_idx != NumGPRs) {
6002         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6003       } else {
6004         if (CallConv == CallingConv::Fast)
6005           ComputePtrOff();
6006 
6007         assert(HasParameterArea &&
6008                "Parameter area must exist to pass an argument in memory.");
6009         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6010                          true, isTailCall, false, MemOpChains,
6011                          TailCallArguments, dl);
6012         if (CallConv == CallingConv::Fast)
6013           ArgOffset += PtrByteSize;
6014       }
6015       if (CallConv != CallingConv::Fast)
6016         ArgOffset += PtrByteSize;
6017       break;
6018     case MVT::f32:
6019     case MVT::f64: {
6020       // These can be scalar arguments or elements of a float array type
6021       // passed directly.  The latter are used to implement ELFv2 homogenous
6022       // float aggregates.
6023 
6024       // Named arguments go into FPRs first, and once they overflow, the
6025       // remaining arguments go into GPRs and then the parameter save area.
6026       // Unnamed arguments for vararg functions always go to GPRs and
6027       // then the parameter save area.  For now, put all arguments to vararg
6028       // routines always in both locations (FPR *and* GPR or stack slot).
6029       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
6030       bool NeededLoad = false;
6031 
6032       // First load the argument into the next available FPR.
6033       if (FPR_idx != NumFPRs)
6034         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6035 
6036       // Next, load the argument into GPR or stack slot if needed.
6037       if (!NeedGPROrStack)
6038         ;
6039       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
6040         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6041         // once we support fp <-> gpr moves.
6042 
6043         // In the non-vararg case, this can only ever happen in the
6044         // presence of f32 array types, since otherwise we never run
6045         // out of FPRs before running out of GPRs.
6046         SDValue ArgVal;
6047 
6048         // Double values are always passed in a single GPR.
6049         if (Arg.getValueType() != MVT::f32) {
6050           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6051 
6052         // Non-array float values are extended and passed in a GPR.
6053         } else if (!Flags.isInConsecutiveRegs()) {
6054           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6055           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6056 
6057         // If we have an array of floats, we collect every odd element
6058         // together with its predecessor into one GPR.
6059         } else if (ArgOffset % PtrByteSize != 0) {
6060           SDValue Lo, Hi;
6061           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6062           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6063           if (!isLittleEndian)
6064             std::swap(Lo, Hi);
6065           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6066 
6067         // The final element, if even, goes into the first half of a GPR.
6068         } else if (Flags.isInConsecutiveRegsLast()) {
6069           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6070           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6071           if (!isLittleEndian)
6072             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6073                                  DAG.getConstant(32, dl, MVT::i32));
6074 
6075         // Non-final even elements are skipped; they will be handled
6076         // together the with subsequent argument on the next go-around.
6077         } else
6078           ArgVal = SDValue();
6079 
6080         if (ArgVal.getNode())
6081           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6082       } else {
6083         if (CallConv == CallingConv::Fast)
6084           ComputePtrOff();
6085 
6086         // Single-precision floating-point values are mapped to the
6087         // second (rightmost) word of the stack doubleword.
6088         if (Arg.getValueType() == MVT::f32 &&
6089             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6090           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6091           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6092         }
6093 
6094         assert(HasParameterArea &&
6095                "Parameter area must exist to pass an argument in memory.");
6096         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6097                          true, isTailCall, false, MemOpChains,
6098                          TailCallArguments, dl);
6099 
6100         NeededLoad = true;
6101       }
6102       // When passing an array of floats, the array occupies consecutive
6103       // space in the argument area; only round up to the next doubleword
6104       // at the end of the array.  Otherwise, each float takes 8 bytes.
6105       if (CallConv != CallingConv::Fast || NeededLoad) {
6106         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6107                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6108         if (Flags.isInConsecutiveRegsLast())
6109           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6110       }
6111       break;
6112     }
6113     case MVT::v4f32:
6114     case MVT::v4i32:
6115     case MVT::v8i16:
6116     case MVT::v16i8:
6117     case MVT::v2f64:
6118     case MVT::v2i64:
6119     case MVT::v1i128:
6120     case MVT::f128:
6121       if (!Subtarget.hasQPX()) {
6122       // These can be scalar arguments or elements of a vector array type
6123       // passed directly.  The latter are used to implement ELFv2 homogenous
6124       // vector aggregates.
6125 
6126       // For a varargs call, named arguments go into VRs or on the stack as
6127       // usual; unnamed arguments always go to the stack or the corresponding
6128       // GPRs when within range.  For now, we always put the value in both
6129       // locations (or even all three).
6130       if (isVarArg) {
6131         assert(HasParameterArea &&
6132                "Parameter area must exist if we have a varargs call.");
6133         // We could elide this store in the case where the object fits
6134         // entirely in R registers.  Maybe later.
6135         SDValue Store =
6136             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6137         MemOpChains.push_back(Store);
6138         if (VR_idx != NumVRs) {
6139           SDValue Load =
6140               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6141           MemOpChains.push_back(Load.getValue(1));
6142           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6143         }
6144         ArgOffset += 16;
6145         for (unsigned i=0; i<16; i+=PtrByteSize) {
6146           if (GPR_idx == NumGPRs)
6147             break;
6148           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6149                                    DAG.getConstant(i, dl, PtrVT));
6150           SDValue Load =
6151               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6152           MemOpChains.push_back(Load.getValue(1));
6153           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6154         }
6155         break;
6156       }
6157 
6158       // Non-varargs Altivec params go into VRs or on the stack.
6159       if (VR_idx != NumVRs) {
6160         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6161       } else {
6162         if (CallConv == CallingConv::Fast)
6163           ComputePtrOff();
6164 
6165         assert(HasParameterArea &&
6166                "Parameter area must exist to pass an argument in memory.");
6167         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6168                          true, isTailCall, true, MemOpChains,
6169                          TailCallArguments, dl);
6170         if (CallConv == CallingConv::Fast)
6171           ArgOffset += 16;
6172       }
6173 
6174       if (CallConv != CallingConv::Fast)
6175         ArgOffset += 16;
6176       break;
6177       } // not QPX
6178 
6179       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6180              "Invalid QPX parameter type");
6181 
6182       LLVM_FALLTHROUGH;
6183     case MVT::v4f64:
6184     case MVT::v4i1: {
6185       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6186       if (isVarArg) {
6187         assert(HasParameterArea &&
6188                "Parameter area must exist if we have a varargs call.");
6189         // We could elide this store in the case where the object fits
6190         // entirely in R registers.  Maybe later.
6191         SDValue Store =
6192             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6193         MemOpChains.push_back(Store);
6194         if (QFPR_idx != NumQFPRs) {
6195           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6196                                      PtrOff, MachinePointerInfo());
6197           MemOpChains.push_back(Load.getValue(1));
6198           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6199         }
6200         ArgOffset += (IsF32 ? 16 : 32);
6201         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6202           if (GPR_idx == NumGPRs)
6203             break;
6204           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6205                                    DAG.getConstant(i, dl, PtrVT));
6206           SDValue Load =
6207               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6208           MemOpChains.push_back(Load.getValue(1));
6209           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6210         }
6211         break;
6212       }
6213 
6214       // Non-varargs QPX params go into registers or on the stack.
6215       if (QFPR_idx != NumQFPRs) {
6216         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6217       } else {
6218         if (CallConv == CallingConv::Fast)
6219           ComputePtrOff();
6220 
6221         assert(HasParameterArea &&
6222                "Parameter area must exist to pass an argument in memory.");
6223         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6224                          true, isTailCall, true, MemOpChains,
6225                          TailCallArguments, dl);
6226         if (CallConv == CallingConv::Fast)
6227           ArgOffset += (IsF32 ? 16 : 32);
6228       }
6229 
6230       if (CallConv != CallingConv::Fast)
6231         ArgOffset += (IsF32 ? 16 : 32);
6232       break;
6233       }
6234     }
6235   }
6236 
6237   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6238          "mismatch in size of parameter area");
6239   (void)NumBytesActuallyUsed;
6240 
6241   if (!MemOpChains.empty())
6242     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6243 
6244   // Check if this is an indirect call (MTCTR/BCTRL).
6245   // See PrepareCall() for more information about calls through function
6246   // pointers in the 64-bit SVR4 ABI.
6247   if (!isTailCall && !isPatchPoint &&
6248       !isFunctionGlobalAddress(Callee) &&
6249       !isa<ExternalSymbolSDNode>(Callee)) {
6250     // Load r2 into a virtual register and store it to the TOC save area.
6251     setUsesTOCBasePtr(DAG);
6252     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6253     // TOC save area offset.
6254     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6255     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6256     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6257     Chain = DAG.getStore(
6258         Val.getValue(1), dl, Val, AddPtr,
6259         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6260     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6261     // This does not mean the MTCTR instruction must use R12; it's easier
6262     // to model this as an extra parameter, so do that.
6263     if (isELFv2ABI && !isPatchPoint)
6264       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6265   }
6266 
6267   // Build a sequence of copy-to-reg nodes chained together with token chain
6268   // and flag operands which copy the outgoing args into the appropriate regs.
6269   SDValue InFlag;
6270   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6271     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6272                              RegsToPass[i].second, InFlag);
6273     InFlag = Chain.getValue(1);
6274   }
6275 
6276   if (isTailCall && !IsSibCall)
6277     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6278                     TailCallArguments);
6279 
6280   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6281                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6282                     SPDiff, NumBytes, Ins, InVals, CS);
6283 }
6284 
6285 SDValue PPCTargetLowering::LowerCall_Darwin(
6286     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6287     bool isTailCall, bool isPatchPoint,
6288     const SmallVectorImpl<ISD::OutputArg> &Outs,
6289     const SmallVectorImpl<SDValue> &OutVals,
6290     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6291     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6292     ImmutableCallSite CS) const {
6293   unsigned NumOps = Outs.size();
6294 
6295   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6296   bool isPPC64 = PtrVT == MVT::i64;
6297   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6298 
6299   MachineFunction &MF = DAG.getMachineFunction();
6300 
6301   // Mark this function as potentially containing a function that contains a
6302   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6303   // and restoring the callers stack pointer in this functions epilog. This is
6304   // done because by tail calling the called function might overwrite the value
6305   // in this function's (MF) stack pointer stack slot 0(SP).
6306   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6307       CallConv == CallingConv::Fast)
6308     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6309 
6310   // Count how many bytes are to be pushed on the stack, including the linkage
6311   // area, and parameter passing area.  We start with 24/48 bytes, which is
6312   // prereserved space for [SP][CR][LR][3 x unused].
6313   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6314   unsigned NumBytes = LinkageSize;
6315 
6316   // Add up all the space actually used.
6317   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6318   // they all go in registers, but we must reserve stack space for them for
6319   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6320   // assigned stack space in order, with padding so Altivec parameters are
6321   // 16-byte aligned.
6322   unsigned nAltivecParamsAtEnd = 0;
6323   for (unsigned i = 0; i != NumOps; ++i) {
6324     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6325     EVT ArgVT = Outs[i].VT;
6326     // Varargs Altivec parameters are padded to a 16 byte boundary.
6327     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6328         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6329         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6330       if (!isVarArg && !isPPC64) {
6331         // Non-varargs Altivec parameters go after all the non-Altivec
6332         // parameters; handle those later so we know how much padding we need.
6333         nAltivecParamsAtEnd++;
6334         continue;
6335       }
6336       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6337       NumBytes = ((NumBytes+15)/16)*16;
6338     }
6339     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6340   }
6341 
6342   // Allow for Altivec parameters at the end, if needed.
6343   if (nAltivecParamsAtEnd) {
6344     NumBytes = ((NumBytes+15)/16)*16;
6345     NumBytes += 16*nAltivecParamsAtEnd;
6346   }
6347 
6348   // The prolog code of the callee may store up to 8 GPR argument registers to
6349   // the stack, allowing va_start to index over them in memory if its varargs.
6350   // Because we cannot tell if this is needed on the caller side, we have to
6351   // conservatively assume that it is needed.  As such, make sure we have at
6352   // least enough stack space for the caller to store the 8 GPRs.
6353   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6354 
6355   // Tail call needs the stack to be aligned.
6356   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6357       CallConv == CallingConv::Fast)
6358     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6359 
6360   // Calculate by how many bytes the stack has to be adjusted in case of tail
6361   // call optimization.
6362   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6363 
6364   // To protect arguments on the stack from being clobbered in a tail call,
6365   // force all the loads to happen before doing any other lowering.
6366   if (isTailCall)
6367     Chain = DAG.getStackArgumentTokenFactor(Chain);
6368 
6369   // Adjust the stack pointer for the new arguments...
6370   // These operations are automatically eliminated by the prolog/epilog pass
6371   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6372   SDValue CallSeqStart = Chain;
6373 
6374   // Load the return address and frame pointer so it can be move somewhere else
6375   // later.
6376   SDValue LROp, FPOp;
6377   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6378 
6379   // Set up a copy of the stack pointer for use loading and storing any
6380   // arguments that may not fit in the registers available for argument
6381   // passing.
6382   SDValue StackPtr;
6383   if (isPPC64)
6384     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6385   else
6386     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6387 
6388   // Figure out which arguments are going to go in registers, and which in
6389   // memory.  Also, if this is a vararg function, floating point operations
6390   // must be stored to our stack, and loaded into integer regs as well, if
6391   // any integer regs are available for argument passing.
6392   unsigned ArgOffset = LinkageSize;
6393   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6394 
6395   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6396     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6397     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6398   };
6399   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6400     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6401     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6402   };
6403   static const MCPhysReg VR[] = {
6404     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6405     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6406   };
6407   const unsigned NumGPRs = array_lengthof(GPR_32);
6408   const unsigned NumFPRs = 13;
6409   const unsigned NumVRs  = array_lengthof(VR);
6410 
6411   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6412 
6413   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6414   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6415 
6416   SmallVector<SDValue, 8> MemOpChains;
6417   for (unsigned i = 0; i != NumOps; ++i) {
6418     SDValue Arg = OutVals[i];
6419     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6420 
6421     // PtrOff will be used to store the current argument to the stack if a
6422     // register cannot be found for it.
6423     SDValue PtrOff;
6424 
6425     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6426 
6427     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6428 
6429     // On PPC64, promote integers to 64-bit values.
6430     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6431       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6432       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6433       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6434     }
6435 
6436     // FIXME memcpy is used way more than necessary.  Correctness first.
6437     // Note: "by value" is code for passing a structure by value, not
6438     // basic types.
6439     if (Flags.isByVal()) {
6440       unsigned Size = Flags.getByValSize();
6441       // Very small objects are passed right-justified.  Everything else is
6442       // passed left-justified.
6443       if (Size==1 || Size==2) {
6444         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6445         if (GPR_idx != NumGPRs) {
6446           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6447                                         MachinePointerInfo(), VT);
6448           MemOpChains.push_back(Load.getValue(1));
6449           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6450 
6451           ArgOffset += PtrByteSize;
6452         } else {
6453           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6454                                           PtrOff.getValueType());
6455           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6456           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6457                                                             CallSeqStart,
6458                                                             Flags, DAG, dl);
6459           ArgOffset += PtrByteSize;
6460         }
6461         continue;
6462       }
6463       // Copy entire object into memory.  There are cases where gcc-generated
6464       // code assumes it is there, even if it could be put entirely into
6465       // registers.  (This is not what the doc says.)
6466       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6467                                                         CallSeqStart,
6468                                                         Flags, DAG, dl);
6469 
6470       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6471       // copy the pieces of the object that fit into registers from the
6472       // parameter save area.
6473       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6474         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6475         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6476         if (GPR_idx != NumGPRs) {
6477           SDValue Load =
6478               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6479           MemOpChains.push_back(Load.getValue(1));
6480           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6481           ArgOffset += PtrByteSize;
6482         } else {
6483           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6484           break;
6485         }
6486       }
6487       continue;
6488     }
6489 
6490     switch (Arg.getSimpleValueType().SimpleTy) {
6491     default: llvm_unreachable("Unexpected ValueType for argument!");
6492     case MVT::i1:
6493     case MVT::i32:
6494     case MVT::i64:
6495       if (GPR_idx != NumGPRs) {
6496         if (Arg.getValueType() == MVT::i1)
6497           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6498 
6499         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6500       } else {
6501         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6502                          isPPC64, isTailCall, false, MemOpChains,
6503                          TailCallArguments, dl);
6504       }
6505       ArgOffset += PtrByteSize;
6506       break;
6507     case MVT::f32:
6508     case MVT::f64:
6509       if (FPR_idx != NumFPRs) {
6510         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6511 
6512         if (isVarArg) {
6513           SDValue Store =
6514               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6515           MemOpChains.push_back(Store);
6516 
6517           // Float varargs are always shadowed in available integer registers
6518           if (GPR_idx != NumGPRs) {
6519             SDValue Load =
6520                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6521             MemOpChains.push_back(Load.getValue(1));
6522             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6523           }
6524           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6525             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6526             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6527             SDValue Load =
6528                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6529             MemOpChains.push_back(Load.getValue(1));
6530             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6531           }
6532         } else {
6533           // If we have any FPRs remaining, we may also have GPRs remaining.
6534           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6535           // GPRs.
6536           if (GPR_idx != NumGPRs)
6537             ++GPR_idx;
6538           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6539               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6540             ++GPR_idx;
6541         }
6542       } else
6543         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6544                          isPPC64, isTailCall, false, MemOpChains,
6545                          TailCallArguments, dl);
6546       if (isPPC64)
6547         ArgOffset += 8;
6548       else
6549         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6550       break;
6551     case MVT::v4f32:
6552     case MVT::v4i32:
6553     case MVT::v8i16:
6554     case MVT::v16i8:
6555       if (isVarArg) {
6556         // These go aligned on the stack, or in the corresponding R registers
6557         // when within range.  The Darwin PPC ABI doc claims they also go in
6558         // V registers; in fact gcc does this only for arguments that are
6559         // prototyped, not for those that match the ...  We do it for all
6560         // arguments, seems to work.
6561         while (ArgOffset % 16 !=0) {
6562           ArgOffset += PtrByteSize;
6563           if (GPR_idx != NumGPRs)
6564             GPR_idx++;
6565         }
6566         // We could elide this store in the case where the object fits
6567         // entirely in R registers.  Maybe later.
6568         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6569                              DAG.getConstant(ArgOffset, dl, PtrVT));
6570         SDValue Store =
6571             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6572         MemOpChains.push_back(Store);
6573         if (VR_idx != NumVRs) {
6574           SDValue Load =
6575               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6576           MemOpChains.push_back(Load.getValue(1));
6577           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6578         }
6579         ArgOffset += 16;
6580         for (unsigned i=0; i<16; i+=PtrByteSize) {
6581           if (GPR_idx == NumGPRs)
6582             break;
6583           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6584                                    DAG.getConstant(i, dl, PtrVT));
6585           SDValue Load =
6586               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6587           MemOpChains.push_back(Load.getValue(1));
6588           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6589         }
6590         break;
6591       }
6592 
6593       // Non-varargs Altivec params generally go in registers, but have
6594       // stack space allocated at the end.
6595       if (VR_idx != NumVRs) {
6596         // Doesn't have GPR space allocated.
6597         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6598       } else if (nAltivecParamsAtEnd==0) {
6599         // We are emitting Altivec params in order.
6600         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6601                          isPPC64, isTailCall, true, MemOpChains,
6602                          TailCallArguments, dl);
6603         ArgOffset += 16;
6604       }
6605       break;
6606     }
6607   }
6608   // If all Altivec parameters fit in registers, as they usually do,
6609   // they get stack space following the non-Altivec parameters.  We
6610   // don't track this here because nobody below needs it.
6611   // If there are more Altivec parameters than fit in registers emit
6612   // the stores here.
6613   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6614     unsigned j = 0;
6615     // Offset is aligned; skip 1st 12 params which go in V registers.
6616     ArgOffset = ((ArgOffset+15)/16)*16;
6617     ArgOffset += 12*16;
6618     for (unsigned i = 0; i != NumOps; ++i) {
6619       SDValue Arg = OutVals[i];
6620       EVT ArgType = Outs[i].VT;
6621       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6622           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6623         if (++j > NumVRs) {
6624           SDValue PtrOff;
6625           // We are emitting Altivec params in order.
6626           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6627                            isPPC64, isTailCall, true, MemOpChains,
6628                            TailCallArguments, dl);
6629           ArgOffset += 16;
6630         }
6631       }
6632     }
6633   }
6634 
6635   if (!MemOpChains.empty())
6636     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6637 
6638   // On Darwin, R12 must contain the address of an indirect callee.  This does
6639   // not mean the MTCTR instruction must use R12; it's easier to model this as
6640   // an extra parameter, so do that.
6641   if (!isTailCall &&
6642       !isFunctionGlobalAddress(Callee) &&
6643       !isa<ExternalSymbolSDNode>(Callee) &&
6644       !isBLACompatibleAddress(Callee, DAG))
6645     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6646                                                    PPC::R12), Callee));
6647 
6648   // Build a sequence of copy-to-reg nodes chained together with token chain
6649   // and flag operands which copy the outgoing args into the appropriate regs.
6650   SDValue InFlag;
6651   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6652     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6653                              RegsToPass[i].second, InFlag);
6654     InFlag = Chain.getValue(1);
6655   }
6656 
6657   if (isTailCall)
6658     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6659                     TailCallArguments);
6660 
6661   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6662                     /* unused except on PPC64 ELFv1 */ false, DAG,
6663                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6664                     NumBytes, Ins, InVals, CS);
6665 }
6666 
6667 
6668 SDValue PPCTargetLowering::LowerCall_AIX(
6669     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6670     bool isTailCall, bool isPatchPoint,
6671     const SmallVectorImpl<ISD::OutputArg> &Outs,
6672     const SmallVectorImpl<SDValue> &OutVals,
6673     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6674     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6675     ImmutableCallSite CS) const {
6676 
6677   assert((CallConv == CallingConv::C || CallConv == CallingConv::Fast) &&
6678          "Unimplemented calling convention!");
6679   if (isVarArg || isPatchPoint)
6680     report_fatal_error("This call type is unimplemented on AIX.");
6681 
6682   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6683   bool isPPC64 = PtrVT == MVT::i64;
6684   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6685   unsigned NumOps = Outs.size();
6686 
6687 
6688   // Count how many bytes are to be pushed on the stack, including the linkage
6689   // area, parameter list area.
6690   // On XCOFF, we start with 24/48, which is reserved space for
6691   // [SP][CR][LR][2 x reserved][TOC].
6692   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6693 
6694   // The prolog code of the callee may store up to 8 GPR argument registers to
6695   // the stack, allowing va_start to index over them in memory if the callee
6696   // is variadic.
6697   // Because we cannot tell if this is needed on the caller side, we have to
6698   // conservatively assume that it is needed.  As such, make sure we have at
6699   // least enough stack space for the caller to store the 8 GPRs.
6700   unsigned NumBytes = LinkageSize + 8 * PtrByteSize;
6701 
6702   // Adjust the stack pointer for the new arguments...
6703   // These operations are automatically eliminated by the prolog/epilog
6704   // inserter pass.
6705   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6706   SDValue CallSeqStart = Chain;
6707 
6708   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6709     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6710     PPC::R7, PPC::R8, PPC::R9, PPC::R10
6711   };
6712   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6713     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6714     PPC::X7, PPC::X8, PPC::X9, PPC::X10
6715   };
6716 
6717   const unsigned NumGPRs = isPPC64 ? array_lengthof(GPR_64)
6718                                    : array_lengthof(GPR_32);
6719   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6720   unsigned GPR_idx = 0;
6721 
6722   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6723 
6724   if (isTailCall)
6725     report_fatal_error("Handling of tail call is unimplemented!");
6726   int SPDiff = 0;
6727 
6728   for (unsigned i = 0; i != NumOps; ++i) {
6729     SDValue Arg = OutVals[i];
6730     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6731 
6732     // Promote integers if needed.
6733     if (Arg.getValueType() == MVT::i1 ||
6734         (isPPC64 && Arg.getValueType() == MVT::i32)) {
6735       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6736       Arg = DAG.getNode(ExtOp, dl, PtrVT, Arg);
6737     }
6738 
6739     // Note: "by value" is code for passing a structure by value, not
6740     // basic types.
6741     if (Flags.isByVal())
6742       report_fatal_error("Passing structure by value is unimplemented!");
6743 
6744     switch (Arg.getSimpleValueType().SimpleTy) {
6745     default: llvm_unreachable("Unexpected ValueType for argument!");
6746     case MVT::i1:
6747     case MVT::i32:
6748     case MVT::i64:
6749       if (GPR_idx != NumGPRs)
6750         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6751       else
6752         report_fatal_error("Handling of placing parameters on the stack is "
6753                            "unimplemented!");
6754       break;
6755     case MVT::f32:
6756     case MVT::f64:
6757     case MVT::v4f32:
6758     case MVT::v4i32:
6759     case MVT::v8i16:
6760     case MVT::v16i8:
6761     case MVT::v2f64:
6762     case MVT::v2i64:
6763     case MVT::v1i128:
6764     case MVT::f128:
6765     case MVT::v4f64:
6766     case MVT::v4i1:
6767       report_fatal_error("Handling of this parameter type is unimplemented!");
6768     }
6769   }
6770 
6771   if (!isFunctionGlobalAddress(Callee) &&
6772       !isa<ExternalSymbolSDNode>(Callee))
6773     report_fatal_error("Handling of indirect call is unimplemented!");
6774 
6775   // Build a sequence of copy-to-reg nodes chained together with token chain
6776   // and flag operands which copy the outgoing args into the appropriate regs.
6777   SDValue InFlag;
6778   for (auto Reg : RegsToPass) {
6779     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
6780     InFlag = Chain.getValue(1);
6781   }
6782 
6783   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6784                     /* unused except on PPC64 ELFv1 */ false, DAG,
6785                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6786                     NumBytes, Ins, InVals, CS);
6787 }
6788 
6789 bool
6790 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6791                                   MachineFunction &MF, bool isVarArg,
6792                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6793                                   LLVMContext &Context) const {
6794   SmallVector<CCValAssign, 16> RVLocs;
6795   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6796   return CCInfo.CheckReturn(
6797       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6798                 ? RetCC_PPC_Cold
6799                 : RetCC_PPC);
6800 }
6801 
6802 SDValue
6803 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6804                                bool isVarArg,
6805                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6806                                const SmallVectorImpl<SDValue> &OutVals,
6807                                const SDLoc &dl, SelectionDAG &DAG) const {
6808   SmallVector<CCValAssign, 16> RVLocs;
6809   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6810                  *DAG.getContext());
6811   CCInfo.AnalyzeReturn(Outs,
6812                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6813                            ? RetCC_PPC_Cold
6814                            : RetCC_PPC);
6815 
6816   SDValue Flag;
6817   SmallVector<SDValue, 4> RetOps(1, Chain);
6818 
6819   // Copy the result values into the output registers.
6820   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
6821     CCValAssign &VA = RVLocs[i];
6822     assert(VA.isRegLoc() && "Can only return in registers!");
6823 
6824     SDValue Arg = OutVals[RealResIdx];
6825 
6826     switch (VA.getLocInfo()) {
6827     default: llvm_unreachable("Unknown loc info!");
6828     case CCValAssign::Full: break;
6829     case CCValAssign::AExt:
6830       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6831       break;
6832     case CCValAssign::ZExt:
6833       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6834       break;
6835     case CCValAssign::SExt:
6836       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6837       break;
6838     }
6839     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
6840       bool isLittleEndian = Subtarget.isLittleEndian();
6841       // Legalize ret f64 -> ret 2 x i32.
6842       SDValue SVal =
6843           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6844                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
6845       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
6846       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6847       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6848                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
6849       Flag = Chain.getValue(1);
6850       VA = RVLocs[++i]; // skip ahead to next loc
6851       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
6852     } else
6853       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6854     Flag = Chain.getValue(1);
6855     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6856   }
6857 
6858   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6859   const MCPhysReg *I =
6860     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6861   if (I) {
6862     for (; *I; ++I) {
6863 
6864       if (PPC::G8RCRegClass.contains(*I))
6865         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6866       else if (PPC::F8RCRegClass.contains(*I))
6867         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6868       else if (PPC::CRRCRegClass.contains(*I))
6869         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6870       else if (PPC::VRRCRegClass.contains(*I))
6871         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6872       else
6873         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6874     }
6875   }
6876 
6877   RetOps[0] = Chain;  // Update chain.
6878 
6879   // Add the flag if we have it.
6880   if (Flag.getNode())
6881     RetOps.push_back(Flag);
6882 
6883   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6884 }
6885 
6886 SDValue
6887 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6888                                                 SelectionDAG &DAG) const {
6889   SDLoc dl(Op);
6890 
6891   // Get the correct type for integers.
6892   EVT IntVT = Op.getValueType();
6893 
6894   // Get the inputs.
6895   SDValue Chain = Op.getOperand(0);
6896   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6897   // Build a DYNAREAOFFSET node.
6898   SDValue Ops[2] = {Chain, FPSIdx};
6899   SDVTList VTs = DAG.getVTList(IntVT);
6900   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6901 }
6902 
6903 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6904                                              SelectionDAG &DAG) const {
6905   // When we pop the dynamic allocation we need to restore the SP link.
6906   SDLoc dl(Op);
6907 
6908   // Get the correct type for pointers.
6909   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6910 
6911   // Construct the stack pointer operand.
6912   bool isPPC64 = Subtarget.isPPC64();
6913   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6914   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6915 
6916   // Get the operands for the STACKRESTORE.
6917   SDValue Chain = Op.getOperand(0);
6918   SDValue SaveSP = Op.getOperand(1);
6919 
6920   // Load the old link SP.
6921   SDValue LoadLinkSP =
6922       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6923 
6924   // Restore the stack pointer.
6925   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6926 
6927   // Store the old link SP.
6928   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6929 }
6930 
6931 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6932   MachineFunction &MF = DAG.getMachineFunction();
6933   bool isPPC64 = Subtarget.isPPC64();
6934   EVT PtrVT = getPointerTy(MF.getDataLayout());
6935 
6936   // Get current frame pointer save index.  The users of this index will be
6937   // primarily DYNALLOC instructions.
6938   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6939   int RASI = FI->getReturnAddrSaveIndex();
6940 
6941   // If the frame pointer save index hasn't been defined yet.
6942   if (!RASI) {
6943     // Find out what the fix offset of the frame pointer save area.
6944     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6945     // Allocate the frame index for frame pointer save area.
6946     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6947     // Save the result.
6948     FI->setReturnAddrSaveIndex(RASI);
6949   }
6950   return DAG.getFrameIndex(RASI, PtrVT);
6951 }
6952 
6953 SDValue
6954 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6955   MachineFunction &MF = DAG.getMachineFunction();
6956   bool isPPC64 = Subtarget.isPPC64();
6957   EVT PtrVT = getPointerTy(MF.getDataLayout());
6958 
6959   // Get current frame pointer save index.  The users of this index will be
6960   // primarily DYNALLOC instructions.
6961   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6962   int FPSI = FI->getFramePointerSaveIndex();
6963 
6964   // If the frame pointer save index hasn't been defined yet.
6965   if (!FPSI) {
6966     // Find out what the fix offset of the frame pointer save area.
6967     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6968     // Allocate the frame index for frame pointer save area.
6969     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6970     // Save the result.
6971     FI->setFramePointerSaveIndex(FPSI);
6972   }
6973   return DAG.getFrameIndex(FPSI, PtrVT);
6974 }
6975 
6976 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6977                                                    SelectionDAG &DAG) const {
6978   // Get the inputs.
6979   SDValue Chain = Op.getOperand(0);
6980   SDValue Size  = Op.getOperand(1);
6981   SDLoc dl(Op);
6982 
6983   // Get the correct type for pointers.
6984   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6985   // Negate the size.
6986   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6987                                 DAG.getConstant(0, dl, PtrVT), Size);
6988   // Construct a node for the frame pointer save index.
6989   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6990   // Build a DYNALLOC node.
6991   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6992   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6993   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6994 }
6995 
6996 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6997                                                      SelectionDAG &DAG) const {
6998   MachineFunction &MF = DAG.getMachineFunction();
6999 
7000   bool isPPC64 = Subtarget.isPPC64();
7001   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7002 
7003   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7004   return DAG.getFrameIndex(FI, PtrVT);
7005 }
7006 
7007 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7008                                                SelectionDAG &DAG) const {
7009   SDLoc DL(Op);
7010   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7011                      DAG.getVTList(MVT::i32, MVT::Other),
7012                      Op.getOperand(0), Op.getOperand(1));
7013 }
7014 
7015 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7016                                                 SelectionDAG &DAG) const {
7017   SDLoc DL(Op);
7018   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7019                      Op.getOperand(0), Op.getOperand(1));
7020 }
7021 
7022 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7023   if (Op.getValueType().isVector())
7024     return LowerVectorLoad(Op, DAG);
7025 
7026   assert(Op.getValueType() == MVT::i1 &&
7027          "Custom lowering only for i1 loads");
7028 
7029   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7030 
7031   SDLoc dl(Op);
7032   LoadSDNode *LD = cast<LoadSDNode>(Op);
7033 
7034   SDValue Chain = LD->getChain();
7035   SDValue BasePtr = LD->getBasePtr();
7036   MachineMemOperand *MMO = LD->getMemOperand();
7037 
7038   SDValue NewLD =
7039       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7040                      BasePtr, MVT::i8, MMO);
7041   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7042 
7043   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7044   return DAG.getMergeValues(Ops, dl);
7045 }
7046 
7047 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7048   if (Op.getOperand(1).getValueType().isVector())
7049     return LowerVectorStore(Op, DAG);
7050 
7051   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7052          "Custom lowering only for i1 stores");
7053 
7054   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7055 
7056   SDLoc dl(Op);
7057   StoreSDNode *ST = cast<StoreSDNode>(Op);
7058 
7059   SDValue Chain = ST->getChain();
7060   SDValue BasePtr = ST->getBasePtr();
7061   SDValue Value = ST->getValue();
7062   MachineMemOperand *MMO = ST->getMemOperand();
7063 
7064   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7065                       Value);
7066   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7067 }
7068 
7069 // FIXME: Remove this once the ANDI glue bug is fixed:
7070 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7071   assert(Op.getValueType() == MVT::i1 &&
7072          "Custom lowering only for i1 results");
7073 
7074   SDLoc DL(Op);
7075   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
7076                      Op.getOperand(0));
7077 }
7078 
7079 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7080                                                SelectionDAG &DAG) const {
7081 
7082   // Implements a vector truncate that fits in a vector register as a shuffle.
7083   // We want to legalize vector truncates down to where the source fits in
7084   // a vector register (and target is therefore smaller than vector register
7085   // size).  At that point legalization will try to custom lower the sub-legal
7086   // result and get here - where we can contain the truncate as a single target
7087   // operation.
7088 
7089   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7090   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7091   //
7092   // We will implement it for big-endian ordering as this (where x denotes
7093   // undefined):
7094   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7095   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7096   //
7097   // The same operation in little-endian ordering will be:
7098   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7099   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7100 
7101   assert(Op.getValueType().isVector() && "Vector type expected.");
7102 
7103   SDLoc DL(Op);
7104   SDValue N1 = Op.getOperand(0);
7105   unsigned SrcSize = N1.getValueType().getSizeInBits();
7106   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7107   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7108 
7109   EVT TrgVT = Op.getValueType();
7110   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7111   EVT EltVT = TrgVT.getVectorElementType();
7112   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7113   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7114 
7115   // First list the elements we want to keep.
7116   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7117   SmallVector<int, 16> ShuffV;
7118   if (Subtarget.isLittleEndian())
7119     for (unsigned i = 0; i < TrgNumElts; ++i)
7120       ShuffV.push_back(i * SizeMult);
7121   else
7122     for (unsigned i = 1; i <= TrgNumElts; ++i)
7123       ShuffV.push_back(i * SizeMult - 1);
7124 
7125   // Populate the remaining elements with undefs.
7126   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7127     // ShuffV.push_back(i + WideNumElts);
7128     ShuffV.push_back(WideNumElts + 1);
7129 
7130   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7131   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7132 }
7133 
7134 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7135 /// possible.
7136 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7137   // Not FP? Not a fsel.
7138   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7139       !Op.getOperand(2).getValueType().isFloatingPoint())
7140     return Op;
7141 
7142   // We might be able to do better than this under some circumstances, but in
7143   // general, fsel-based lowering of select is a finite-math-only optimization.
7144   // For more information, see section F.3 of the 2.06 ISA specification.
7145   if (!DAG.getTarget().Options.NoInfsFPMath ||
7146       !DAG.getTarget().Options.NoNaNsFPMath)
7147     return Op;
7148   // TODO: Propagate flags from the select rather than global settings.
7149   SDNodeFlags Flags;
7150   Flags.setNoInfs(true);
7151   Flags.setNoNaNs(true);
7152 
7153   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7154 
7155   EVT ResVT = Op.getValueType();
7156   EVT CmpVT = Op.getOperand(0).getValueType();
7157   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7158   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7159   SDLoc dl(Op);
7160 
7161   // If the RHS of the comparison is a 0.0, we don't need to do the
7162   // subtraction at all.
7163   SDValue Sel1;
7164   if (isFloatingPointZero(RHS))
7165     switch (CC) {
7166     default: break;       // SETUO etc aren't handled by fsel.
7167     case ISD::SETNE:
7168       std::swap(TV, FV);
7169       LLVM_FALLTHROUGH;
7170     case ISD::SETEQ:
7171       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7172         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7173       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7174       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7175         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7176       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7177                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7178     case ISD::SETULT:
7179     case ISD::SETLT:
7180       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7181       LLVM_FALLTHROUGH;
7182     case ISD::SETOGE:
7183     case ISD::SETGE:
7184       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7185         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7186       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7187     case ISD::SETUGT:
7188     case ISD::SETGT:
7189       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7190       LLVM_FALLTHROUGH;
7191     case ISD::SETOLE:
7192     case ISD::SETLE:
7193       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7194         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7195       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7196                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7197     }
7198 
7199   SDValue Cmp;
7200   switch (CC) {
7201   default: break;       // SETUO etc aren't handled by fsel.
7202   case ISD::SETNE:
7203     std::swap(TV, FV);
7204     LLVM_FALLTHROUGH;
7205   case ISD::SETEQ:
7206     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7207     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7208       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7209     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7210     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7211       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7212     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7213                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7214   case ISD::SETULT:
7215   case ISD::SETLT:
7216     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7217     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7218       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7219     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7220   case ISD::SETOGE:
7221   case ISD::SETGE:
7222     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7223     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7224       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7225     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7226   case ISD::SETUGT:
7227   case ISD::SETGT:
7228     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7229     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7230       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7231     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7232   case ISD::SETOLE:
7233   case ISD::SETLE:
7234     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, 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, TV, FV);
7238   }
7239   return Op;
7240 }
7241 
7242 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7243                                                SelectionDAG &DAG,
7244                                                const SDLoc &dl) const {
7245   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7246   SDValue Src = Op.getOperand(0);
7247   if (Src.getValueType() == MVT::f32)
7248     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7249 
7250   SDValue Tmp;
7251   switch (Op.getSimpleValueType().SimpleTy) {
7252   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7253   case MVT::i32:
7254     Tmp = DAG.getNode(
7255         Op.getOpcode() == ISD::FP_TO_SINT
7256             ? PPCISD::FCTIWZ
7257             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7258         dl, MVT::f64, Src);
7259     break;
7260   case MVT::i64:
7261     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7262            "i64 FP_TO_UINT is supported only with FPCVT");
7263     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7264                                                         PPCISD::FCTIDUZ,
7265                       dl, MVT::f64, Src);
7266     break;
7267   }
7268 
7269   // Convert the FP value to an int value through memory.
7270   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7271     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7272   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7273   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7274   MachinePointerInfo MPI =
7275       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7276 
7277   // Emit a store to the stack slot.
7278   SDValue Chain;
7279   if (i32Stack) {
7280     MachineFunction &MF = DAG.getMachineFunction();
7281     MachineMemOperand *MMO =
7282       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7283     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7284     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7285               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7286   } else
7287     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7288 
7289   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7290   // add in a bias on big endian.
7291   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7292     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7293                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7294     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7295   }
7296 
7297   RLI.Chain = Chain;
7298   RLI.Ptr = FIPtr;
7299   RLI.MPI = MPI;
7300 }
7301 
7302 /// Custom lowers floating point to integer conversions to use
7303 /// the direct move instructions available in ISA 2.07 to avoid the
7304 /// need for load/store combinations.
7305 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7306                                                     SelectionDAG &DAG,
7307                                                     const SDLoc &dl) const {
7308   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7309   SDValue Src = Op.getOperand(0);
7310 
7311   if (Src.getValueType() == MVT::f32)
7312     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7313 
7314   SDValue Tmp;
7315   switch (Op.getSimpleValueType().SimpleTy) {
7316   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7317   case MVT::i32:
7318     Tmp = DAG.getNode(
7319         Op.getOpcode() == ISD::FP_TO_SINT
7320             ? PPCISD::FCTIWZ
7321             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7322         dl, MVT::f64, Src);
7323     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7324     break;
7325   case MVT::i64:
7326     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7327            "i64 FP_TO_UINT is supported only with FPCVT");
7328     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7329                                                         PPCISD::FCTIDUZ,
7330                       dl, MVT::f64, Src);
7331     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7332     break;
7333   }
7334   return Tmp;
7335 }
7336 
7337 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7338                                           const SDLoc &dl) const {
7339 
7340   // FP to INT conversions are legal for f128.
7341   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7342     return Op;
7343 
7344   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7345   // PPC (the libcall is not available).
7346   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7347     if (Op.getValueType() == MVT::i32) {
7348       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7349         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7350                                  MVT::f64, Op.getOperand(0),
7351                                  DAG.getIntPtrConstant(0, dl));
7352         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7353                                  MVT::f64, Op.getOperand(0),
7354                                  DAG.getIntPtrConstant(1, dl));
7355 
7356         // Add the two halves of the long double in round-to-zero mode.
7357         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7358 
7359         // Now use a smaller FP_TO_SINT.
7360         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7361       }
7362       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7363         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7364         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7365         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7366         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7367         // FIXME: generated code sucks.
7368         // TODO: Are there fast-math-flags to propagate to this FSUB?
7369         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7370                                    Op.getOperand(0), Tmp);
7371         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7372         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7373                            DAG.getConstant(0x80000000, dl, MVT::i32));
7374         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7375                                     Op.getOperand(0));
7376         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7377                                ISD::SETGE);
7378       }
7379     }
7380 
7381     return SDValue();
7382   }
7383 
7384   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7385     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7386 
7387   ReuseLoadInfo RLI;
7388   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7389 
7390   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7391                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7392 }
7393 
7394 // We're trying to insert a regular store, S, and then a load, L. If the
7395 // incoming value, O, is a load, we might just be able to have our load use the
7396 // address used by O. However, we don't know if anything else will store to
7397 // that address before we can load from it. To prevent this situation, we need
7398 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7399 // the same chain operand as O, we create a token factor from the chain results
7400 // of O and L, and we replace all uses of O's chain result with that token
7401 // factor (see spliceIntoChain below for this last part).
7402 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7403                                             ReuseLoadInfo &RLI,
7404                                             SelectionDAG &DAG,
7405                                             ISD::LoadExtType ET) const {
7406   SDLoc dl(Op);
7407   if (ET == ISD::NON_EXTLOAD &&
7408       (Op.getOpcode() == ISD::FP_TO_UINT ||
7409        Op.getOpcode() == ISD::FP_TO_SINT) &&
7410       isOperationLegalOrCustom(Op.getOpcode(),
7411                                Op.getOperand(0).getValueType())) {
7412 
7413     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7414     return true;
7415   }
7416 
7417   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7418   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7419       LD->isNonTemporal())
7420     return false;
7421   if (LD->getMemoryVT() != MemVT)
7422     return false;
7423 
7424   RLI.Ptr = LD->getBasePtr();
7425   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7426     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7427            "Non-pre-inc AM on PPC?");
7428     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7429                           LD->getOffset());
7430   }
7431 
7432   RLI.Chain = LD->getChain();
7433   RLI.MPI = LD->getPointerInfo();
7434   RLI.IsDereferenceable = LD->isDereferenceable();
7435   RLI.IsInvariant = LD->isInvariant();
7436   RLI.Alignment = LD->getAlignment();
7437   RLI.AAInfo = LD->getAAInfo();
7438   RLI.Ranges = LD->getRanges();
7439 
7440   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7441   return true;
7442 }
7443 
7444 // Given the head of the old chain, ResChain, insert a token factor containing
7445 // it and NewResChain, and make users of ResChain now be users of that token
7446 // factor.
7447 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7448 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7449                                         SDValue NewResChain,
7450                                         SelectionDAG &DAG) const {
7451   if (!ResChain)
7452     return;
7453 
7454   SDLoc dl(NewResChain);
7455 
7456   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7457                            NewResChain, DAG.getUNDEF(MVT::Other));
7458   assert(TF.getNode() != NewResChain.getNode() &&
7459          "A new TF really is required here");
7460 
7461   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7462   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7463 }
7464 
7465 /// Analyze profitability of direct move
7466 /// prefer float load to int load plus direct move
7467 /// when there is no integer use of int load
7468 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7469   SDNode *Origin = Op.getOperand(0).getNode();
7470   if (Origin->getOpcode() != ISD::LOAD)
7471     return true;
7472 
7473   // If there is no LXSIBZX/LXSIHZX, like Power8,
7474   // prefer direct move if the memory size is 1 or 2 bytes.
7475   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7476   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7477     return true;
7478 
7479   for (SDNode::use_iterator UI = Origin->use_begin(),
7480                             UE = Origin->use_end();
7481        UI != UE; ++UI) {
7482 
7483     // Only look at the users of the loaded value.
7484     if (UI.getUse().get().getResNo() != 0)
7485       continue;
7486 
7487     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7488         UI->getOpcode() != ISD::UINT_TO_FP)
7489       return true;
7490   }
7491 
7492   return false;
7493 }
7494 
7495 /// Custom lowers integer to floating point conversions to use
7496 /// the direct move instructions available in ISA 2.07 to avoid the
7497 /// need for load/store combinations.
7498 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7499                                                     SelectionDAG &DAG,
7500                                                     const SDLoc &dl) const {
7501   assert((Op.getValueType() == MVT::f32 ||
7502           Op.getValueType() == MVT::f64) &&
7503          "Invalid floating point type as target of conversion");
7504   assert(Subtarget.hasFPCVT() &&
7505          "Int to FP conversions with direct moves require FPCVT");
7506   SDValue FP;
7507   SDValue Src = Op.getOperand(0);
7508   bool SinglePrec = Op.getValueType() == MVT::f32;
7509   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7510   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7511   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7512                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7513 
7514   if (WordInt) {
7515     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7516                      dl, MVT::f64, Src);
7517     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7518   }
7519   else {
7520     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7521     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7522   }
7523 
7524   return FP;
7525 }
7526 
7527 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7528 
7529   EVT VecVT = Vec.getValueType();
7530   assert(VecVT.isVector() && "Expected a vector type.");
7531   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7532 
7533   EVT EltVT = VecVT.getVectorElementType();
7534   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7535   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7536 
7537   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7538   SmallVector<SDValue, 16> Ops(NumConcat);
7539   Ops[0] = Vec;
7540   SDValue UndefVec = DAG.getUNDEF(VecVT);
7541   for (unsigned i = 1; i < NumConcat; ++i)
7542     Ops[i] = UndefVec;
7543 
7544   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7545 }
7546 
7547 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7548                                                 const SDLoc &dl) const {
7549 
7550   unsigned Opc = Op.getOpcode();
7551   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7552          "Unexpected conversion type");
7553   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7554          "Supports conversions to v2f64/v4f32 only.");
7555 
7556   bool SignedConv = Opc == ISD::SINT_TO_FP;
7557   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7558 
7559   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7560   EVT WideVT = Wide.getValueType();
7561   unsigned WideNumElts = WideVT.getVectorNumElements();
7562   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7563 
7564   SmallVector<int, 16> ShuffV;
7565   for (unsigned i = 0; i < WideNumElts; ++i)
7566     ShuffV.push_back(i + WideNumElts);
7567 
7568   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7569   int SaveElts = FourEltRes ? 4 : 2;
7570   if (Subtarget.isLittleEndian())
7571     for (int i = 0; i < SaveElts; i++)
7572       ShuffV[i * Stride] = i;
7573   else
7574     for (int i = 1; i <= SaveElts; i++)
7575       ShuffV[i * Stride - 1] = i - 1;
7576 
7577   SDValue ShuffleSrc2 =
7578       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7579   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7580   unsigned ExtendOp =
7581       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7582 
7583   SDValue Extend;
7584   if (!Subtarget.hasP9Altivec() && SignedConv) {
7585     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7586     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7587                          DAG.getValueType(Op.getOperand(0).getValueType()));
7588   } else
7589     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7590 
7591   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7592 }
7593 
7594 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7595                                           SelectionDAG &DAG) const {
7596   SDLoc dl(Op);
7597 
7598   EVT InVT = Op.getOperand(0).getValueType();
7599   EVT OutVT = Op.getValueType();
7600   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7601       isOperationCustom(Op.getOpcode(), InVT))
7602     return LowerINT_TO_FPVector(Op, DAG, dl);
7603 
7604   // Conversions to f128 are legal.
7605   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7606     return Op;
7607 
7608   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7609     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7610       return SDValue();
7611 
7612     SDValue Value = Op.getOperand(0);
7613     // The values are now known to be -1 (false) or 1 (true). To convert this
7614     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7615     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7616     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7617 
7618     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7619 
7620     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7621 
7622     if (Op.getValueType() != MVT::v4f64)
7623       Value = DAG.getNode(ISD::FP_ROUND, dl,
7624                           Op.getValueType(), Value,
7625                           DAG.getIntPtrConstant(1, dl));
7626     return Value;
7627   }
7628 
7629   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7630   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7631     return SDValue();
7632 
7633   if (Op.getOperand(0).getValueType() == MVT::i1)
7634     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7635                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7636                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7637 
7638   // If we have direct moves, we can do all the conversion, skip the store/load
7639   // however, without FPCVT we can't do most conversions.
7640   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7641       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7642     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7643 
7644   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7645          "UINT_TO_FP is supported only with FPCVT");
7646 
7647   // If we have FCFIDS, then use it when converting to single-precision.
7648   // Otherwise, convert to double-precision and then round.
7649   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7650                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7651                                                             : PPCISD::FCFIDS)
7652                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7653                                                             : PPCISD::FCFID);
7654   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7655                   ? MVT::f32
7656                   : MVT::f64;
7657 
7658   if (Op.getOperand(0).getValueType() == MVT::i64) {
7659     SDValue SINT = Op.getOperand(0);
7660     // When converting to single-precision, we actually need to convert
7661     // to double-precision first and then round to single-precision.
7662     // To avoid double-rounding effects during that operation, we have
7663     // to prepare the input operand.  Bits that might be truncated when
7664     // converting to double-precision are replaced by a bit that won't
7665     // be lost at this stage, but is below the single-precision rounding
7666     // position.
7667     //
7668     // However, if -enable-unsafe-fp-math is in effect, accept double
7669     // rounding to avoid the extra overhead.
7670     if (Op.getValueType() == MVT::f32 &&
7671         !Subtarget.hasFPCVT() &&
7672         !DAG.getTarget().Options.UnsafeFPMath) {
7673 
7674       // Twiddle input to make sure the low 11 bits are zero.  (If this
7675       // is the case, we are guaranteed the value will fit into the 53 bit
7676       // mantissa of an IEEE double-precision value without rounding.)
7677       // If any of those low 11 bits were not zero originally, make sure
7678       // bit 12 (value 2048) is set instead, so that the final rounding
7679       // to single-precision gets the correct result.
7680       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7681                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7682       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7683                           Round, DAG.getConstant(2047, dl, MVT::i64));
7684       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7685       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7686                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7687 
7688       // However, we cannot use that value unconditionally: if the magnitude
7689       // of the input value is small, the bit-twiddling we did above might
7690       // end up visibly changing the output.  Fortunately, in that case, we
7691       // don't need to twiddle bits since the original input will convert
7692       // exactly to double-precision floating-point already.  Therefore,
7693       // construct a conditional to use the original value if the top 11
7694       // bits are all sign-bit copies, and use the rounded value computed
7695       // above otherwise.
7696       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7697                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7698       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7699                          Cond, DAG.getConstant(1, dl, MVT::i64));
7700       Cond = DAG.getSetCC(dl, MVT::i32,
7701                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7702 
7703       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7704     }
7705 
7706     ReuseLoadInfo RLI;
7707     SDValue Bits;
7708 
7709     MachineFunction &MF = DAG.getMachineFunction();
7710     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7711       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7712                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7713       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7714     } else if (Subtarget.hasLFIWAX() &&
7715                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7716       MachineMemOperand *MMO =
7717         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7718                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7719       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7720       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7721                                      DAG.getVTList(MVT::f64, MVT::Other),
7722                                      Ops, MVT::i32, MMO);
7723       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7724     } else if (Subtarget.hasFPCVT() &&
7725                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7726       MachineMemOperand *MMO =
7727         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7728                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7729       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7730       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7731                                      DAG.getVTList(MVT::f64, MVT::Other),
7732                                      Ops, MVT::i32, MMO);
7733       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7734     } else if (((Subtarget.hasLFIWAX() &&
7735                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7736                 (Subtarget.hasFPCVT() &&
7737                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7738                SINT.getOperand(0).getValueType() == MVT::i32) {
7739       MachineFrameInfo &MFI = MF.getFrameInfo();
7740       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7741 
7742       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7743       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7744 
7745       SDValue Store =
7746           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7747                        MachinePointerInfo::getFixedStack(
7748                            DAG.getMachineFunction(), FrameIdx));
7749 
7750       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7751              "Expected an i32 store");
7752 
7753       RLI.Ptr = FIdx;
7754       RLI.Chain = Store;
7755       RLI.MPI =
7756           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7757       RLI.Alignment = 4;
7758 
7759       MachineMemOperand *MMO =
7760         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7761                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7762       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7763       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7764                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7765                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7766                                      Ops, MVT::i32, MMO);
7767     } else
7768       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7769 
7770     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7771 
7772     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7773       FP = DAG.getNode(ISD::FP_ROUND, dl,
7774                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7775     return FP;
7776   }
7777 
7778   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7779          "Unhandled INT_TO_FP type in custom expander!");
7780   // Since we only generate this in 64-bit mode, we can take advantage of
7781   // 64-bit registers.  In particular, sign extend the input value into the
7782   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7783   // then lfd it and fcfid it.
7784   MachineFunction &MF = DAG.getMachineFunction();
7785   MachineFrameInfo &MFI = MF.getFrameInfo();
7786   EVT PtrVT = getPointerTy(MF.getDataLayout());
7787 
7788   SDValue Ld;
7789   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7790     ReuseLoadInfo RLI;
7791     bool ReusingLoad;
7792     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7793                                             DAG))) {
7794       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7795       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7796 
7797       SDValue Store =
7798           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7799                        MachinePointerInfo::getFixedStack(
7800                            DAG.getMachineFunction(), FrameIdx));
7801 
7802       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7803              "Expected an i32 store");
7804 
7805       RLI.Ptr = FIdx;
7806       RLI.Chain = Store;
7807       RLI.MPI =
7808           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7809       RLI.Alignment = 4;
7810     }
7811 
7812     MachineMemOperand *MMO =
7813       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7814                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7815     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7816     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7817                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7818                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7819                                  Ops, MVT::i32, MMO);
7820     if (ReusingLoad)
7821       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7822   } else {
7823     assert(Subtarget.isPPC64() &&
7824            "i32->FP without LFIWAX supported only on PPC64");
7825 
7826     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7827     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7828 
7829     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7830                                 Op.getOperand(0));
7831 
7832     // STD the extended value into the stack slot.
7833     SDValue Store = DAG.getStore(
7834         DAG.getEntryNode(), dl, Ext64, FIdx,
7835         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7836 
7837     // Load the value as a double.
7838     Ld = DAG.getLoad(
7839         MVT::f64, dl, Store, FIdx,
7840         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7841   }
7842 
7843   // FCFID it and return it.
7844   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7845   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7846     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7847                      DAG.getIntPtrConstant(0, dl));
7848   return FP;
7849 }
7850 
7851 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7852                                             SelectionDAG &DAG) const {
7853   SDLoc dl(Op);
7854   /*
7855    The rounding mode is in bits 30:31 of FPSR, and has the following
7856    settings:
7857      00 Round to nearest
7858      01 Round to 0
7859      10 Round to +inf
7860      11 Round to -inf
7861 
7862   FLT_ROUNDS, on the other hand, expects the following:
7863     -1 Undefined
7864      0 Round to 0
7865      1 Round to nearest
7866      2 Round to +inf
7867      3 Round to -inf
7868 
7869   To perform the conversion, we do:
7870     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7871   */
7872 
7873   MachineFunction &MF = DAG.getMachineFunction();
7874   EVT VT = Op.getValueType();
7875   EVT PtrVT = getPointerTy(MF.getDataLayout());
7876 
7877   // Save FP Control Word to register
7878   EVT NodeTys[] = {
7879     MVT::f64,    // return register
7880     MVT::Glue    // unused in this context
7881   };
7882   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7883 
7884   // Save FP register to stack slot
7885   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7886   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7887   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7888                                MachinePointerInfo());
7889 
7890   // Load FP Control Word from low 32 bits of stack slot.
7891   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7892   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7893   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7894 
7895   // Transform as necessary
7896   SDValue CWD1 =
7897     DAG.getNode(ISD::AND, dl, MVT::i32,
7898                 CWD, DAG.getConstant(3, dl, MVT::i32));
7899   SDValue CWD2 =
7900     DAG.getNode(ISD::SRL, dl, MVT::i32,
7901                 DAG.getNode(ISD::AND, dl, MVT::i32,
7902                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7903                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7904                             DAG.getConstant(3, dl, MVT::i32)),
7905                 DAG.getConstant(1, dl, MVT::i32));
7906 
7907   SDValue RetVal =
7908     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7909 
7910   return DAG.getNode((VT.getSizeInBits() < 16 ?
7911                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7912 }
7913 
7914 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7915   EVT VT = Op.getValueType();
7916   unsigned BitWidth = VT.getSizeInBits();
7917   SDLoc dl(Op);
7918   assert(Op.getNumOperands() == 3 &&
7919          VT == Op.getOperand(1).getValueType() &&
7920          "Unexpected SHL!");
7921 
7922   // Expand into a bunch of logical ops.  Note that these ops
7923   // depend on the PPC behavior for oversized shift amounts.
7924   SDValue Lo = Op.getOperand(0);
7925   SDValue Hi = Op.getOperand(1);
7926   SDValue Amt = Op.getOperand(2);
7927   EVT AmtVT = Amt.getValueType();
7928 
7929   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7930                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7931   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7932   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7933   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7934   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7935                              DAG.getConstant(-BitWidth, dl, AmtVT));
7936   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7937   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7938   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7939   SDValue OutOps[] = { OutLo, OutHi };
7940   return DAG.getMergeValues(OutOps, dl);
7941 }
7942 
7943 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7944   EVT VT = Op.getValueType();
7945   SDLoc dl(Op);
7946   unsigned BitWidth = VT.getSizeInBits();
7947   assert(Op.getNumOperands() == 3 &&
7948          VT == Op.getOperand(1).getValueType() &&
7949          "Unexpected SRL!");
7950 
7951   // Expand into a bunch of logical ops.  Note that these ops
7952   // depend on the PPC behavior for oversized shift amounts.
7953   SDValue Lo = Op.getOperand(0);
7954   SDValue Hi = Op.getOperand(1);
7955   SDValue Amt = Op.getOperand(2);
7956   EVT AmtVT = Amt.getValueType();
7957 
7958   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7959                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7960   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7961   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7962   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7963   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7964                              DAG.getConstant(-BitWidth, dl, AmtVT));
7965   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7966   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7967   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7968   SDValue OutOps[] = { OutLo, OutHi };
7969   return DAG.getMergeValues(OutOps, dl);
7970 }
7971 
7972 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7973   SDLoc dl(Op);
7974   EVT VT = Op.getValueType();
7975   unsigned BitWidth = VT.getSizeInBits();
7976   assert(Op.getNumOperands() == 3 &&
7977          VT == Op.getOperand(1).getValueType() &&
7978          "Unexpected SRA!");
7979 
7980   // Expand into a bunch of logical ops, followed by a select_cc.
7981   SDValue Lo = Op.getOperand(0);
7982   SDValue Hi = Op.getOperand(1);
7983   SDValue Amt = Op.getOperand(2);
7984   EVT AmtVT = Amt.getValueType();
7985 
7986   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7987                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7988   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7989   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7990   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7991   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7992                              DAG.getConstant(-BitWidth, dl, AmtVT));
7993   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7994   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7995   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7996                                   Tmp4, Tmp6, ISD::SETLE);
7997   SDValue OutOps[] = { OutLo, OutHi };
7998   return DAG.getMergeValues(OutOps, dl);
7999 }
8000 
8001 //===----------------------------------------------------------------------===//
8002 // Vector related lowering.
8003 //
8004 
8005 /// BuildSplatI - Build a canonical splati of Val with an element size of
8006 /// SplatSize.  Cast the result to VT.
8007 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8008                            SelectionDAG &DAG, const SDLoc &dl) {
8009   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
8010 
8011   static const MVT VTys[] = { // canonical VT to use for each size.
8012     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8013   };
8014 
8015   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8016 
8017   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8018   if (Val == -1)
8019     SplatSize = 1;
8020 
8021   EVT CanonicalVT = VTys[SplatSize-1];
8022 
8023   // Build a canonical splat for this value.
8024   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8025 }
8026 
8027 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8028 /// specified intrinsic ID.
8029 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8030                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8031   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8032   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8033                      DAG.getConstant(IID, dl, MVT::i32), Op);
8034 }
8035 
8036 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8037 /// specified intrinsic ID.
8038 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8039                                 SelectionDAG &DAG, const SDLoc &dl,
8040                                 EVT DestVT = MVT::Other) {
8041   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8042   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8043                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8044 }
8045 
8046 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8047 /// specified intrinsic ID.
8048 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8049                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8050                                 EVT DestVT = MVT::Other) {
8051   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8052   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8053                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8054 }
8055 
8056 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8057 /// amount.  The result has the specified value type.
8058 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8059                            SelectionDAG &DAG, const SDLoc &dl) {
8060   // Force LHS/RHS to be the right type.
8061   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8062   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8063 
8064   int Ops[16];
8065   for (unsigned i = 0; i != 16; ++i)
8066     Ops[i] = i + Amt;
8067   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8068   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8069 }
8070 
8071 /// Do we have an efficient pattern in a .td file for this node?
8072 ///
8073 /// \param V - pointer to the BuildVectorSDNode being matched
8074 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8075 ///
8076 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8077 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8078 /// the opposite is true (expansion is beneficial) are:
8079 /// - The node builds a vector out of integers that are not 32 or 64-bits
8080 /// - The node builds a vector out of constants
8081 /// - The node is a "load-and-splat"
8082 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8083 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8084                                             bool HasDirectMove,
8085                                             bool HasP8Vector) {
8086   EVT VecVT = V->getValueType(0);
8087   bool RightType = VecVT == MVT::v2f64 ||
8088     (HasP8Vector && VecVT == MVT::v4f32) ||
8089     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8090   if (!RightType)
8091     return false;
8092 
8093   bool IsSplat = true;
8094   bool IsLoad = false;
8095   SDValue Op0 = V->getOperand(0);
8096 
8097   // This function is called in a block that confirms the node is not a constant
8098   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8099   // different constants.
8100   if (V->isConstant())
8101     return false;
8102   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8103     if (V->getOperand(i).isUndef())
8104       return false;
8105     // We want to expand nodes that represent load-and-splat even if the
8106     // loaded value is a floating point truncation or conversion to int.
8107     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8108         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8109          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8110         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8111          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8112         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8113          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8114       IsLoad = true;
8115     // If the operands are different or the input is not a load and has more
8116     // uses than just this BV node, then it isn't a splat.
8117     if (V->getOperand(i) != Op0 ||
8118         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8119       IsSplat = false;
8120   }
8121   return !(IsSplat && IsLoad);
8122 }
8123 
8124 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8125 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8126 
8127   SDLoc dl(Op);
8128   SDValue Op0 = Op->getOperand(0);
8129 
8130   if (!EnableQuadPrecision ||
8131       (Op.getValueType() != MVT::f128 ) ||
8132       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8133       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8134       (Op0.getOperand(1).getValueType() != MVT::i64))
8135     return SDValue();
8136 
8137   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8138                      Op0.getOperand(1));
8139 }
8140 
8141 // If this is a case we can't handle, return null and let the default
8142 // expansion code take care of it.  If we CAN select this case, and if it
8143 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8144 // this case more efficiently than a constant pool load, lower it to the
8145 // sequence of ops that should be used.
8146 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8147                                              SelectionDAG &DAG) const {
8148   SDLoc dl(Op);
8149   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8150   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8151 
8152   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8153     // We first build an i32 vector, load it into a QPX register,
8154     // then convert it to a floating-point vector and compare it
8155     // to a zero vector to get the boolean result.
8156     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8157     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8158     MachinePointerInfo PtrInfo =
8159         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8160     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8161     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8162 
8163     assert(BVN->getNumOperands() == 4 &&
8164       "BUILD_VECTOR for v4i1 does not have 4 operands");
8165 
8166     bool IsConst = true;
8167     for (unsigned i = 0; i < 4; ++i) {
8168       if (BVN->getOperand(i).isUndef()) continue;
8169       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8170         IsConst = false;
8171         break;
8172       }
8173     }
8174 
8175     if (IsConst) {
8176       Constant *One =
8177         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8178       Constant *NegOne =
8179         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8180 
8181       Constant *CV[4];
8182       for (unsigned i = 0; i < 4; ++i) {
8183         if (BVN->getOperand(i).isUndef())
8184           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8185         else if (isNullConstant(BVN->getOperand(i)))
8186           CV[i] = NegOne;
8187         else
8188           CV[i] = One;
8189       }
8190 
8191       Constant *CP = ConstantVector::get(CV);
8192       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8193                                           16 /* alignment */);
8194 
8195       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8196       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8197       return DAG.getMemIntrinsicNode(
8198           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8199           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8200     }
8201 
8202     SmallVector<SDValue, 4> Stores;
8203     for (unsigned i = 0; i < 4; ++i) {
8204       if (BVN->getOperand(i).isUndef()) continue;
8205 
8206       unsigned Offset = 4*i;
8207       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8208       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8209 
8210       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8211       if (StoreSize > 4) {
8212         Stores.push_back(
8213             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8214                               PtrInfo.getWithOffset(Offset), MVT::i32));
8215       } else {
8216         SDValue StoreValue = BVN->getOperand(i);
8217         if (StoreSize < 4)
8218           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8219 
8220         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8221                                       PtrInfo.getWithOffset(Offset)));
8222       }
8223     }
8224 
8225     SDValue StoreChain;
8226     if (!Stores.empty())
8227       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8228     else
8229       StoreChain = DAG.getEntryNode();
8230 
8231     // Now load from v4i32 into the QPX register; this will extend it to
8232     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8233     // is typed as v4f64 because the QPX register integer states are not
8234     // explicitly represented.
8235 
8236     SDValue Ops[] = {StoreChain,
8237                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8238                      FIdx};
8239     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8240 
8241     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8242       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8243     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8244       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8245       LoadedVect);
8246 
8247     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8248 
8249     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8250   }
8251 
8252   // All other QPX vectors are handled by generic code.
8253   if (Subtarget.hasQPX())
8254     return SDValue();
8255 
8256   // Check if this is a splat of a constant value.
8257   APInt APSplatBits, APSplatUndef;
8258   unsigned SplatBitSize;
8259   bool HasAnyUndefs;
8260   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8261                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8262       SplatBitSize > 32) {
8263     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8264     // lowered to VSX instructions under certain conditions.
8265     // Without VSX, there is no pattern more efficient than expanding the node.
8266     if (Subtarget.hasVSX() &&
8267         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8268                                         Subtarget.hasP8Vector()))
8269       return Op;
8270     return SDValue();
8271   }
8272 
8273   unsigned SplatBits = APSplatBits.getZExtValue();
8274   unsigned SplatUndef = APSplatUndef.getZExtValue();
8275   unsigned SplatSize = SplatBitSize / 8;
8276 
8277   // First, handle single instruction cases.
8278 
8279   // All zeros?
8280   if (SplatBits == 0) {
8281     // Canonicalize all zero vectors to be v4i32.
8282     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8283       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8284       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8285     }
8286     return Op;
8287   }
8288 
8289   // We have XXSPLTIB for constant splats one byte wide
8290   if (Subtarget.hasP9Vector() && SplatSize == 1) {
8291     // This is a splat of 1-byte elements with some elements potentially undef.
8292     // Rather than trying to match undef in the SDAG patterns, ensure that all
8293     // elements are the same constant.
8294     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
8295       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
8296                                                        dl, MVT::i32));
8297       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
8298       if (Op.getValueType() != MVT::v16i8)
8299         return DAG.getBitcast(Op.getValueType(), NewBV);
8300       return NewBV;
8301     }
8302 
8303     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
8304     // detect that constant splats like v8i16: 0xABAB are really just splats
8305     // of a 1-byte constant. In this case, we need to convert the node to a
8306     // splat of v16i8 and a bitcast.
8307     if (Op.getValueType() != MVT::v16i8)
8308       return DAG.getBitcast(Op.getValueType(),
8309                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
8310 
8311     return Op;
8312   }
8313 
8314   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8315   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8316                     (32-SplatBitSize));
8317   if (SextVal >= -16 && SextVal <= 15)
8318     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8319 
8320   // Two instruction sequences.
8321 
8322   // If this value is in the range [-32,30] and is even, use:
8323   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8324   // If this value is in the range [17,31] and is odd, use:
8325   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8326   // If this value is in the range [-31,-17] and is odd, use:
8327   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8328   // Note the last two are three-instruction sequences.
8329   if (SextVal >= -32 && SextVal <= 31) {
8330     // To avoid having these optimizations undone by constant folding,
8331     // we convert to a pseudo that will be expanded later into one of
8332     // the above forms.
8333     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8334     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8335               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8336     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8337     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8338     if (VT == Op.getValueType())
8339       return RetVal;
8340     else
8341       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8342   }
8343 
8344   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8345   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8346   // for fneg/fabs.
8347   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8348     // Make -1 and vspltisw -1:
8349     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8350 
8351     // Make the VSLW intrinsic, computing 0x8000_0000.
8352     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8353                                    OnesV, DAG, dl);
8354 
8355     // xor by OnesV to invert it.
8356     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8357     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8358   }
8359 
8360   // Check to see if this is a wide variety of vsplti*, binop self cases.
8361   static const signed char SplatCsts[] = {
8362     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8363     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8364   };
8365 
8366   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8367     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8368     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8369     int i = SplatCsts[idx];
8370 
8371     // Figure out what shift amount will be used by altivec if shifted by i in
8372     // this splat size.
8373     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8374 
8375     // vsplti + shl self.
8376     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8377       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8378       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8379         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8380         Intrinsic::ppc_altivec_vslw
8381       };
8382       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8383       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8384     }
8385 
8386     // vsplti + srl self.
8387     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8388       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8389       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8390         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8391         Intrinsic::ppc_altivec_vsrw
8392       };
8393       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8394       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8395     }
8396 
8397     // vsplti + sra self.
8398     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8399       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8400       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8401         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8402         Intrinsic::ppc_altivec_vsraw
8403       };
8404       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8405       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8406     }
8407 
8408     // vsplti + rol self.
8409     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8410                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8411       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8412       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8413         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8414         Intrinsic::ppc_altivec_vrlw
8415       };
8416       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8417       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8418     }
8419 
8420     // t = vsplti c, result = vsldoi t, t, 1
8421     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8422       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8423       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8424       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8425     }
8426     // t = vsplti c, result = vsldoi t, t, 2
8427     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8428       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8429       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8430       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8431     }
8432     // t = vsplti c, result = vsldoi t, t, 3
8433     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8434       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8435       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8436       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8437     }
8438   }
8439 
8440   return SDValue();
8441 }
8442 
8443 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8444 /// the specified operations to build the shuffle.
8445 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8446                                       SDValue RHS, SelectionDAG &DAG,
8447                                       const SDLoc &dl) {
8448   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8449   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8450   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8451 
8452   enum {
8453     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8454     OP_VMRGHW,
8455     OP_VMRGLW,
8456     OP_VSPLTISW0,
8457     OP_VSPLTISW1,
8458     OP_VSPLTISW2,
8459     OP_VSPLTISW3,
8460     OP_VSLDOI4,
8461     OP_VSLDOI8,
8462     OP_VSLDOI12
8463   };
8464 
8465   if (OpNum == OP_COPY) {
8466     if (LHSID == (1*9+2)*9+3) return LHS;
8467     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8468     return RHS;
8469   }
8470 
8471   SDValue OpLHS, OpRHS;
8472   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8473   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8474 
8475   int ShufIdxs[16];
8476   switch (OpNum) {
8477   default: llvm_unreachable("Unknown i32 permute!");
8478   case OP_VMRGHW:
8479     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8480     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8481     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8482     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8483     break;
8484   case OP_VMRGLW:
8485     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8486     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8487     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8488     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8489     break;
8490   case OP_VSPLTISW0:
8491     for (unsigned i = 0; i != 16; ++i)
8492       ShufIdxs[i] = (i&3)+0;
8493     break;
8494   case OP_VSPLTISW1:
8495     for (unsigned i = 0; i != 16; ++i)
8496       ShufIdxs[i] = (i&3)+4;
8497     break;
8498   case OP_VSPLTISW2:
8499     for (unsigned i = 0; i != 16; ++i)
8500       ShufIdxs[i] = (i&3)+8;
8501     break;
8502   case OP_VSPLTISW3:
8503     for (unsigned i = 0; i != 16; ++i)
8504       ShufIdxs[i] = (i&3)+12;
8505     break;
8506   case OP_VSLDOI4:
8507     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8508   case OP_VSLDOI8:
8509     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8510   case OP_VSLDOI12:
8511     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8512   }
8513   EVT VT = OpLHS.getValueType();
8514   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8515   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8516   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8517   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8518 }
8519 
8520 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8521 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8522 /// SDValue.
8523 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8524                                            SelectionDAG &DAG) const {
8525   const unsigned BytesInVector = 16;
8526   bool IsLE = Subtarget.isLittleEndian();
8527   SDLoc dl(N);
8528   SDValue V1 = N->getOperand(0);
8529   SDValue V2 = N->getOperand(1);
8530   unsigned ShiftElts = 0, InsertAtByte = 0;
8531   bool Swap = false;
8532 
8533   // Shifts required to get the byte we want at element 7.
8534   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8535                                    0, 15, 14, 13, 12, 11, 10, 9};
8536   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8537                                 1, 2,  3,  4,  5,  6,  7,  8};
8538 
8539   ArrayRef<int> Mask = N->getMask();
8540   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8541 
8542   // For each mask element, find out if we're just inserting something
8543   // from V2 into V1 or vice versa.
8544   // Possible permutations inserting an element from V2 into V1:
8545   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8546   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8547   //   ...
8548   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8549   // Inserting from V1 into V2 will be similar, except mask range will be
8550   // [16,31].
8551 
8552   bool FoundCandidate = false;
8553   // If both vector operands for the shuffle are the same vector, the mask
8554   // will contain only elements from the first one and the second one will be
8555   // undef.
8556   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8557   // Go through the mask of half-words to find an element that's being moved
8558   // from one vector to the other.
8559   for (unsigned i = 0; i < BytesInVector; ++i) {
8560     unsigned CurrentElement = Mask[i];
8561     // If 2nd operand is undefined, we should only look for element 7 in the
8562     // Mask.
8563     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8564       continue;
8565 
8566     bool OtherElementsInOrder = true;
8567     // Examine the other elements in the Mask to see if they're in original
8568     // order.
8569     for (unsigned j = 0; j < BytesInVector; ++j) {
8570       if (j == i)
8571         continue;
8572       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8573       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8574       // in which we always assume we're always picking from the 1st operand.
8575       int MaskOffset =
8576           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8577       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8578         OtherElementsInOrder = false;
8579         break;
8580       }
8581     }
8582     // If other elements are in original order, we record the number of shifts
8583     // we need to get the element we want into element 7. Also record which byte
8584     // in the vector we should insert into.
8585     if (OtherElementsInOrder) {
8586       // If 2nd operand is undefined, we assume no shifts and no swapping.
8587       if (V2.isUndef()) {
8588         ShiftElts = 0;
8589         Swap = false;
8590       } else {
8591         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8592         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8593                          : BigEndianShifts[CurrentElement & 0xF];
8594         Swap = CurrentElement < BytesInVector;
8595       }
8596       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8597       FoundCandidate = true;
8598       break;
8599     }
8600   }
8601 
8602   if (!FoundCandidate)
8603     return SDValue();
8604 
8605   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8606   // optionally with VECSHL if shift is required.
8607   if (Swap)
8608     std::swap(V1, V2);
8609   if (V2.isUndef())
8610     V2 = V1;
8611   if (ShiftElts) {
8612     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8613                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8614     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8615                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8616   }
8617   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8618                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8619 }
8620 
8621 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8622 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8623 /// SDValue.
8624 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8625                                            SelectionDAG &DAG) const {
8626   const unsigned NumHalfWords = 8;
8627   const unsigned BytesInVector = NumHalfWords * 2;
8628   // Check that the shuffle is on half-words.
8629   if (!isNByteElemShuffleMask(N, 2, 1))
8630     return SDValue();
8631 
8632   bool IsLE = Subtarget.isLittleEndian();
8633   SDLoc dl(N);
8634   SDValue V1 = N->getOperand(0);
8635   SDValue V2 = N->getOperand(1);
8636   unsigned ShiftElts = 0, InsertAtByte = 0;
8637   bool Swap = false;
8638 
8639   // Shifts required to get the half-word we want at element 3.
8640   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8641   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8642 
8643   uint32_t Mask = 0;
8644   uint32_t OriginalOrderLow = 0x1234567;
8645   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8646   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8647   // 32-bit space, only need 4-bit nibbles per element.
8648   for (unsigned i = 0; i < NumHalfWords; ++i) {
8649     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8650     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8651   }
8652 
8653   // For each mask element, find out if we're just inserting something
8654   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8655   // from V2 into V1:
8656   //   X, 1, 2, 3, 4, 5, 6, 7
8657   //   0, X, 2, 3, 4, 5, 6, 7
8658   //   0, 1, X, 3, 4, 5, 6, 7
8659   //   0, 1, 2, X, 4, 5, 6, 7
8660   //   0, 1, 2, 3, X, 5, 6, 7
8661   //   0, 1, 2, 3, 4, X, 6, 7
8662   //   0, 1, 2, 3, 4, 5, X, 7
8663   //   0, 1, 2, 3, 4, 5, 6, X
8664   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8665 
8666   bool FoundCandidate = false;
8667   // Go through the mask of half-words to find an element that's being moved
8668   // from one vector to the other.
8669   for (unsigned i = 0; i < NumHalfWords; ++i) {
8670     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8671     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8672     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8673     uint32_t TargetOrder = 0x0;
8674 
8675     // If both vector operands for the shuffle are the same vector, the mask
8676     // will contain only elements from the first one and the second one will be
8677     // undef.
8678     if (V2.isUndef()) {
8679       ShiftElts = 0;
8680       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8681       TargetOrder = OriginalOrderLow;
8682       Swap = false;
8683       // Skip if not the correct element or mask of other elements don't equal
8684       // to our expected order.
8685       if (MaskOneElt == VINSERTHSrcElem &&
8686           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8687         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8688         FoundCandidate = true;
8689         break;
8690       }
8691     } else { // If both operands are defined.
8692       // Target order is [8,15] if the current mask is between [0,7].
8693       TargetOrder =
8694           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8695       // Skip if mask of other elements don't equal our expected order.
8696       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8697         // We only need the last 3 bits for the number of shifts.
8698         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8699                          : BigEndianShifts[MaskOneElt & 0x7];
8700         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8701         Swap = MaskOneElt < NumHalfWords;
8702         FoundCandidate = true;
8703         break;
8704       }
8705     }
8706   }
8707 
8708   if (!FoundCandidate)
8709     return SDValue();
8710 
8711   // Candidate found, construct the proper SDAG sequence with VINSERTH,
8712   // optionally with VECSHL if shift is required.
8713   if (Swap)
8714     std::swap(V1, V2);
8715   if (V2.isUndef())
8716     V2 = V1;
8717   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8718   if (ShiftElts) {
8719     // Double ShiftElts because we're left shifting on v16i8 type.
8720     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8721                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8722     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8723     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8724                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8725     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8726   }
8727   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8728   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8729                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8730   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8731 }
8732 
8733 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8734 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8735 /// return the code it can be lowered into.  Worst case, it can always be
8736 /// lowered into a vperm.
8737 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8738                                                SelectionDAG &DAG) const {
8739   SDLoc dl(Op);
8740   SDValue V1 = Op.getOperand(0);
8741   SDValue V2 = Op.getOperand(1);
8742   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8743   EVT VT = Op.getValueType();
8744   bool isLittleEndian = Subtarget.isLittleEndian();
8745 
8746   unsigned ShiftElts, InsertAtByte;
8747   bool Swap = false;
8748   if (Subtarget.hasP9Vector() &&
8749       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8750                            isLittleEndian)) {
8751     if (Swap)
8752       std::swap(V1, V2);
8753     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8754     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8755     if (ShiftElts) {
8756       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8757                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8758       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8759                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8760       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8761     }
8762     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8763                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8764     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8765   }
8766 
8767   if (Subtarget.hasP9Altivec()) {
8768     SDValue NewISDNode;
8769     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8770       return NewISDNode;
8771 
8772     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8773       return NewISDNode;
8774   }
8775 
8776   if (Subtarget.hasVSX() &&
8777       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8778     if (Swap)
8779       std::swap(V1, V2);
8780     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8781     SDValue Conv2 =
8782         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8783 
8784     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8785                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8786     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8787   }
8788 
8789   if (Subtarget.hasVSX() &&
8790     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8791     if (Swap)
8792       std::swap(V1, V2);
8793     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8794     SDValue Conv2 =
8795         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8796 
8797     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8798                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8799     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8800   }
8801 
8802   if (Subtarget.hasP9Vector()) {
8803      if (PPC::isXXBRHShuffleMask(SVOp)) {
8804       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8805       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8806       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8807     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8808       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8809       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8810       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8811     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8812       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8813       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8814       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8815     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8816       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8817       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8818       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8819     }
8820   }
8821 
8822   if (Subtarget.hasVSX()) {
8823     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8824       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8825 
8826       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8827       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8828                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8829       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8830     }
8831 
8832     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8833     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8834       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8835       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8836       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8837     }
8838   }
8839 
8840   if (Subtarget.hasQPX()) {
8841     if (VT.getVectorNumElements() != 4)
8842       return SDValue();
8843 
8844     if (V2.isUndef()) V2 = V1;
8845 
8846     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8847     if (AlignIdx != -1) {
8848       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8849                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8850     } else if (SVOp->isSplat()) {
8851       int SplatIdx = SVOp->getSplatIndex();
8852       if (SplatIdx >= 4) {
8853         std::swap(V1, V2);
8854         SplatIdx -= 4;
8855       }
8856 
8857       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8858                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8859     }
8860 
8861     // Lower this into a qvgpci/qvfperm pair.
8862 
8863     // Compute the qvgpci literal
8864     unsigned idx = 0;
8865     for (unsigned i = 0; i < 4; ++i) {
8866       int m = SVOp->getMaskElt(i);
8867       unsigned mm = m >= 0 ? (unsigned) m : i;
8868       idx |= mm << (3-i)*3;
8869     }
8870 
8871     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8872                              DAG.getConstant(idx, dl, MVT::i32));
8873     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8874   }
8875 
8876   // Cases that are handled by instructions that take permute immediates
8877   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8878   // selected by the instruction selector.
8879   if (V2.isUndef()) {
8880     if (PPC::isSplatShuffleMask(SVOp, 1) ||
8881         PPC::isSplatShuffleMask(SVOp, 2) ||
8882         PPC::isSplatShuffleMask(SVOp, 4) ||
8883         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8884         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8885         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8886         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8887         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8888         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8889         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8890         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8891         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8892         (Subtarget.hasP8Altivec() && (
8893          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8894          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8895          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8896       return Op;
8897     }
8898   }
8899 
8900   // Altivec has a variety of "shuffle immediates" that take two vector inputs
8901   // and produce a fixed permutation.  If any of these match, do not lower to
8902   // VPERM.
8903   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8904   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8905       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8906       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8907       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8908       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8909       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8910       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8911       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8912       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8913       (Subtarget.hasP8Altivec() && (
8914        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8915        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8916        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8917     return Op;
8918 
8919   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
8920   // perfect shuffle table to emit an optimal matching sequence.
8921   ArrayRef<int> PermMask = SVOp->getMask();
8922 
8923   unsigned PFIndexes[4];
8924   bool isFourElementShuffle = true;
8925   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8926     unsigned EltNo = 8;   // Start out undef.
8927     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
8928       if (PermMask[i*4+j] < 0)
8929         continue;   // Undef, ignore it.
8930 
8931       unsigned ByteSource = PermMask[i*4+j];
8932       if ((ByteSource & 3) != j) {
8933         isFourElementShuffle = false;
8934         break;
8935       }
8936 
8937       if (EltNo == 8) {
8938         EltNo = ByteSource/4;
8939       } else if (EltNo != ByteSource/4) {
8940         isFourElementShuffle = false;
8941         break;
8942       }
8943     }
8944     PFIndexes[i] = EltNo;
8945   }
8946 
8947   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8948   // perfect shuffle vector to determine if it is cost effective to do this as
8949   // discrete instructions, or whether we should use a vperm.
8950   // For now, we skip this for little endian until such time as we have a
8951   // little-endian perfect shuffle table.
8952   if (isFourElementShuffle && !isLittleEndian) {
8953     // Compute the index in the perfect shuffle table.
8954     unsigned PFTableIndex =
8955       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8956 
8957     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8958     unsigned Cost  = (PFEntry >> 30);
8959 
8960     // Determining when to avoid vperm is tricky.  Many things affect the cost
8961     // of vperm, particularly how many times the perm mask needs to be computed.
8962     // For example, if the perm mask can be hoisted out of a loop or is already
8963     // used (perhaps because there are multiple permutes with the same shuffle
8964     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
8965     // the loop requires an extra register.
8966     //
8967     // As a compromise, we only emit discrete instructions if the shuffle can be
8968     // generated in 3 or fewer operations.  When we have loop information
8969     // available, if this block is within a loop, we should avoid using vperm
8970     // for 3-operation perms and use a constant pool load instead.
8971     if (Cost < 3)
8972       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8973   }
8974 
8975   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8976   // vector that will get spilled to the constant pool.
8977   if (V2.isUndef()) V2 = V1;
8978 
8979   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8980   // that it is in input element units, not in bytes.  Convert now.
8981 
8982   // For little endian, the order of the input vectors is reversed, and
8983   // the permutation mask is complemented with respect to 31.  This is
8984   // necessary to produce proper semantics with the big-endian-biased vperm
8985   // instruction.
8986   EVT EltVT = V1.getValueType().getVectorElementType();
8987   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8988 
8989   SmallVector<SDValue, 16> ResultMask;
8990   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8991     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8992 
8993     for (unsigned j = 0; j != BytesPerElement; ++j)
8994       if (isLittleEndian)
8995         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8996                                              dl, MVT::i32));
8997       else
8998         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8999                                              MVT::i32));
9000   }
9001 
9002   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9003   if (isLittleEndian)
9004     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9005                        V2, V1, VPermMask);
9006   else
9007     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9008                        V1, V2, VPermMask);
9009 }
9010 
9011 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9012 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9013 /// information about the intrinsic.
9014 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9015                                  bool &isDot, const PPCSubtarget &Subtarget) {
9016   unsigned IntrinsicID =
9017       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9018   CompareOpc = -1;
9019   isDot = false;
9020   switch (IntrinsicID) {
9021   default:
9022     return false;
9023   // Comparison predicates.
9024   case Intrinsic::ppc_altivec_vcmpbfp_p:
9025     CompareOpc = 966;
9026     isDot = true;
9027     break;
9028   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9029     CompareOpc = 198;
9030     isDot = true;
9031     break;
9032   case Intrinsic::ppc_altivec_vcmpequb_p:
9033     CompareOpc = 6;
9034     isDot = true;
9035     break;
9036   case Intrinsic::ppc_altivec_vcmpequh_p:
9037     CompareOpc = 70;
9038     isDot = true;
9039     break;
9040   case Intrinsic::ppc_altivec_vcmpequw_p:
9041     CompareOpc = 134;
9042     isDot = true;
9043     break;
9044   case Intrinsic::ppc_altivec_vcmpequd_p:
9045     if (Subtarget.hasP8Altivec()) {
9046       CompareOpc = 199;
9047       isDot = true;
9048     } else
9049       return false;
9050     break;
9051   case Intrinsic::ppc_altivec_vcmpneb_p:
9052   case Intrinsic::ppc_altivec_vcmpneh_p:
9053   case Intrinsic::ppc_altivec_vcmpnew_p:
9054   case Intrinsic::ppc_altivec_vcmpnezb_p:
9055   case Intrinsic::ppc_altivec_vcmpnezh_p:
9056   case Intrinsic::ppc_altivec_vcmpnezw_p:
9057     if (Subtarget.hasP9Altivec()) {
9058       switch (IntrinsicID) {
9059       default:
9060         llvm_unreachable("Unknown comparison intrinsic.");
9061       case Intrinsic::ppc_altivec_vcmpneb_p:
9062         CompareOpc = 7;
9063         break;
9064       case Intrinsic::ppc_altivec_vcmpneh_p:
9065         CompareOpc = 71;
9066         break;
9067       case Intrinsic::ppc_altivec_vcmpnew_p:
9068         CompareOpc = 135;
9069         break;
9070       case Intrinsic::ppc_altivec_vcmpnezb_p:
9071         CompareOpc = 263;
9072         break;
9073       case Intrinsic::ppc_altivec_vcmpnezh_p:
9074         CompareOpc = 327;
9075         break;
9076       case Intrinsic::ppc_altivec_vcmpnezw_p:
9077         CompareOpc = 391;
9078         break;
9079       }
9080       isDot = true;
9081     } else
9082       return false;
9083     break;
9084   case Intrinsic::ppc_altivec_vcmpgefp_p:
9085     CompareOpc = 454;
9086     isDot = true;
9087     break;
9088   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9089     CompareOpc = 710;
9090     isDot = true;
9091     break;
9092   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9093     CompareOpc = 774;
9094     isDot = true;
9095     break;
9096   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9097     CompareOpc = 838;
9098     isDot = true;
9099     break;
9100   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9101     CompareOpc = 902;
9102     isDot = true;
9103     break;
9104   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9105     if (Subtarget.hasP8Altivec()) {
9106       CompareOpc = 967;
9107       isDot = true;
9108     } else
9109       return false;
9110     break;
9111   case Intrinsic::ppc_altivec_vcmpgtub_p:
9112     CompareOpc = 518;
9113     isDot = true;
9114     break;
9115   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9116     CompareOpc = 582;
9117     isDot = true;
9118     break;
9119   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9120     CompareOpc = 646;
9121     isDot = true;
9122     break;
9123   case Intrinsic::ppc_altivec_vcmpgtud_p:
9124     if (Subtarget.hasP8Altivec()) {
9125       CompareOpc = 711;
9126       isDot = true;
9127     } else
9128       return false;
9129     break;
9130 
9131   // VSX predicate comparisons use the same infrastructure
9132   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9133   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9134   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9135   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9136   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9137   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9138     if (Subtarget.hasVSX()) {
9139       switch (IntrinsicID) {
9140       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9141         CompareOpc = 99;
9142         break;
9143       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9144         CompareOpc = 115;
9145         break;
9146       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9147         CompareOpc = 107;
9148         break;
9149       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9150         CompareOpc = 67;
9151         break;
9152       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9153         CompareOpc = 83;
9154         break;
9155       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9156         CompareOpc = 75;
9157         break;
9158       }
9159       isDot = true;
9160     } else
9161       return false;
9162     break;
9163 
9164   // Normal Comparisons.
9165   case Intrinsic::ppc_altivec_vcmpbfp:
9166     CompareOpc = 966;
9167     break;
9168   case Intrinsic::ppc_altivec_vcmpeqfp:
9169     CompareOpc = 198;
9170     break;
9171   case Intrinsic::ppc_altivec_vcmpequb:
9172     CompareOpc = 6;
9173     break;
9174   case Intrinsic::ppc_altivec_vcmpequh:
9175     CompareOpc = 70;
9176     break;
9177   case Intrinsic::ppc_altivec_vcmpequw:
9178     CompareOpc = 134;
9179     break;
9180   case Intrinsic::ppc_altivec_vcmpequd:
9181     if (Subtarget.hasP8Altivec())
9182       CompareOpc = 199;
9183     else
9184       return false;
9185     break;
9186   case Intrinsic::ppc_altivec_vcmpneb:
9187   case Intrinsic::ppc_altivec_vcmpneh:
9188   case Intrinsic::ppc_altivec_vcmpnew:
9189   case Intrinsic::ppc_altivec_vcmpnezb:
9190   case Intrinsic::ppc_altivec_vcmpnezh:
9191   case Intrinsic::ppc_altivec_vcmpnezw:
9192     if (Subtarget.hasP9Altivec())
9193       switch (IntrinsicID) {
9194       default:
9195         llvm_unreachable("Unknown comparison intrinsic.");
9196       case Intrinsic::ppc_altivec_vcmpneb:
9197         CompareOpc = 7;
9198         break;
9199       case Intrinsic::ppc_altivec_vcmpneh:
9200         CompareOpc = 71;
9201         break;
9202       case Intrinsic::ppc_altivec_vcmpnew:
9203         CompareOpc = 135;
9204         break;
9205       case Intrinsic::ppc_altivec_vcmpnezb:
9206         CompareOpc = 263;
9207         break;
9208       case Intrinsic::ppc_altivec_vcmpnezh:
9209         CompareOpc = 327;
9210         break;
9211       case Intrinsic::ppc_altivec_vcmpnezw:
9212         CompareOpc = 391;
9213         break;
9214       }
9215     else
9216       return false;
9217     break;
9218   case Intrinsic::ppc_altivec_vcmpgefp:
9219     CompareOpc = 454;
9220     break;
9221   case Intrinsic::ppc_altivec_vcmpgtfp:
9222     CompareOpc = 710;
9223     break;
9224   case Intrinsic::ppc_altivec_vcmpgtsb:
9225     CompareOpc = 774;
9226     break;
9227   case Intrinsic::ppc_altivec_vcmpgtsh:
9228     CompareOpc = 838;
9229     break;
9230   case Intrinsic::ppc_altivec_vcmpgtsw:
9231     CompareOpc = 902;
9232     break;
9233   case Intrinsic::ppc_altivec_vcmpgtsd:
9234     if (Subtarget.hasP8Altivec())
9235       CompareOpc = 967;
9236     else
9237       return false;
9238     break;
9239   case Intrinsic::ppc_altivec_vcmpgtub:
9240     CompareOpc = 518;
9241     break;
9242   case Intrinsic::ppc_altivec_vcmpgtuh:
9243     CompareOpc = 582;
9244     break;
9245   case Intrinsic::ppc_altivec_vcmpgtuw:
9246     CompareOpc = 646;
9247     break;
9248   case Intrinsic::ppc_altivec_vcmpgtud:
9249     if (Subtarget.hasP8Altivec())
9250       CompareOpc = 711;
9251     else
9252       return false;
9253     break;
9254   }
9255   return true;
9256 }
9257 
9258 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9259 /// lower, do it, otherwise return null.
9260 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9261                                                    SelectionDAG &DAG) const {
9262   unsigned IntrinsicID =
9263     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9264 
9265   SDLoc dl(Op);
9266 
9267   if (IntrinsicID == Intrinsic::thread_pointer) {
9268     // Reads the thread pointer register, used for __builtin_thread_pointer.
9269     if (Subtarget.isPPC64())
9270       return DAG.getRegister(PPC::X13, MVT::i64);
9271     return DAG.getRegister(PPC::R2, MVT::i32);
9272   }
9273 
9274   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9275   // opcode number of the comparison.
9276   int CompareOpc;
9277   bool isDot;
9278   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9279     return SDValue();    // Don't custom lower most intrinsics.
9280 
9281   // If this is a non-dot comparison, make the VCMP node and we are done.
9282   if (!isDot) {
9283     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9284                               Op.getOperand(1), Op.getOperand(2),
9285                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9286     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9287   }
9288 
9289   // Create the PPCISD altivec 'dot' comparison node.
9290   SDValue Ops[] = {
9291     Op.getOperand(2),  // LHS
9292     Op.getOperand(3),  // RHS
9293     DAG.getConstant(CompareOpc, dl, MVT::i32)
9294   };
9295   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9296   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9297 
9298   // Now that we have the comparison, emit a copy from the CR to a GPR.
9299   // This is flagged to the above dot comparison.
9300   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9301                                 DAG.getRegister(PPC::CR6, MVT::i32),
9302                                 CompNode.getValue(1));
9303 
9304   // Unpack the result based on how the target uses it.
9305   unsigned BitNo;   // Bit # of CR6.
9306   bool InvertBit;   // Invert result?
9307   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9308   default:  // Can't happen, don't crash on invalid number though.
9309   case 0:   // Return the value of the EQ bit of CR6.
9310     BitNo = 0; InvertBit = false;
9311     break;
9312   case 1:   // Return the inverted value of the EQ bit of CR6.
9313     BitNo = 0; InvertBit = true;
9314     break;
9315   case 2:   // Return the value of the LT bit of CR6.
9316     BitNo = 2; InvertBit = false;
9317     break;
9318   case 3:   // Return the inverted value of the LT bit of CR6.
9319     BitNo = 2; InvertBit = true;
9320     break;
9321   }
9322 
9323   // Shift the bit into the low position.
9324   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9325                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9326   // Isolate the bit.
9327   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9328                       DAG.getConstant(1, dl, MVT::i32));
9329 
9330   // If we are supposed to, toggle the bit.
9331   if (InvertBit)
9332     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9333                         DAG.getConstant(1, dl, MVT::i32));
9334   return Flags;
9335 }
9336 
9337 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9338                                                SelectionDAG &DAG) const {
9339   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9340   // the beginning of the argument list.
9341   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9342   SDLoc DL(Op);
9343   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9344   case Intrinsic::ppc_cfence: {
9345     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9346     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9347     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9348                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9349                                                   Op.getOperand(ArgStart + 1)),
9350                                       Op.getOperand(0)),
9351                    0);
9352   }
9353   default:
9354     break;
9355   }
9356   return SDValue();
9357 }
9358 
9359 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9360   // Check for a DIV with the same operands as this REM.
9361   for (auto UI : Op.getOperand(1)->uses()) {
9362     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9363         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9364       if (UI->getOperand(0) == Op.getOperand(0) &&
9365           UI->getOperand(1) == Op.getOperand(1))
9366         return SDValue();
9367   }
9368   return Op;
9369 }
9370 
9371 // Lower scalar BSWAP64 to xxbrd.
9372 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9373   SDLoc dl(Op);
9374   // MTVSRDD
9375   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9376                    Op.getOperand(0));
9377   // XXBRD
9378   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
9379   // MFVSRD
9380   int VectorIndex = 0;
9381   if (Subtarget.isLittleEndian())
9382     VectorIndex = 1;
9383   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9384                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9385   return Op;
9386 }
9387 
9388 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9389 // compared to a value that is atomically loaded (atomic loads zero-extend).
9390 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9391                                                 SelectionDAG &DAG) const {
9392   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9393          "Expecting an atomic compare-and-swap here.");
9394   SDLoc dl(Op);
9395   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9396   EVT MemVT = AtomicNode->getMemoryVT();
9397   if (MemVT.getSizeInBits() >= 32)
9398     return Op;
9399 
9400   SDValue CmpOp = Op.getOperand(2);
9401   // If this is already correctly zero-extended, leave it alone.
9402   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9403   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9404     return Op;
9405 
9406   // Clear the high bits of the compare operand.
9407   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9408   SDValue NewCmpOp =
9409     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9410                 DAG.getConstant(MaskVal, dl, MVT::i32));
9411 
9412   // Replace the existing compare operand with the properly zero-extended one.
9413   SmallVector<SDValue, 4> Ops;
9414   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9415     Ops.push_back(AtomicNode->getOperand(i));
9416   Ops[2] = NewCmpOp;
9417   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9418   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9419   auto NodeTy =
9420     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9421   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9422 }
9423 
9424 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9425                                                  SelectionDAG &DAG) const {
9426   SDLoc dl(Op);
9427   // Create a stack slot that is 16-byte aligned.
9428   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9429   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9430   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9431   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9432 
9433   // Store the input value into Value#0 of the stack slot.
9434   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9435                                MachinePointerInfo());
9436   // Load it out.
9437   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9438 }
9439 
9440 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9441                                                   SelectionDAG &DAG) const {
9442   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9443          "Should only be called for ISD::INSERT_VECTOR_ELT");
9444 
9445   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9446   // We have legal lowering for constant indices but not for variable ones.
9447   if (!C)
9448     return SDValue();
9449 
9450   EVT VT = Op.getValueType();
9451   SDLoc dl(Op);
9452   SDValue V1 = Op.getOperand(0);
9453   SDValue V2 = Op.getOperand(1);
9454   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9455   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9456     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9457     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9458     unsigned InsertAtElement = C->getZExtValue();
9459     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9460     if (Subtarget.isLittleEndian()) {
9461       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9462     }
9463     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9464                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9465   }
9466   return Op;
9467 }
9468 
9469 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9470                                                    SelectionDAG &DAG) const {
9471   SDLoc dl(Op);
9472   SDNode *N = Op.getNode();
9473 
9474   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9475          "Unknown extract_vector_elt type");
9476 
9477   SDValue Value = N->getOperand(0);
9478 
9479   // The first part of this is like the store lowering except that we don't
9480   // need to track the chain.
9481 
9482   // The values are now known to be -1 (false) or 1 (true). To convert this
9483   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9484   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9485   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9486 
9487   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9488   // understand how to form the extending load.
9489   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9490 
9491   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9492 
9493   // Now convert to an integer and store.
9494   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9495     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9496     Value);
9497 
9498   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9499   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9500   MachinePointerInfo PtrInfo =
9501       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9502   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9503   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9504 
9505   SDValue StoreChain = DAG.getEntryNode();
9506   SDValue Ops[] = {StoreChain,
9507                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9508                    Value, FIdx};
9509   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9510 
9511   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9512     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9513 
9514   // Extract the value requested.
9515   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9516   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9517   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9518 
9519   SDValue IntVal =
9520       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9521 
9522   if (!Subtarget.useCRBits())
9523     return IntVal;
9524 
9525   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9526 }
9527 
9528 /// Lowering for QPX v4i1 loads
9529 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9530                                            SelectionDAG &DAG) const {
9531   SDLoc dl(Op);
9532   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9533   SDValue LoadChain = LN->getChain();
9534   SDValue BasePtr = LN->getBasePtr();
9535 
9536   if (Op.getValueType() == MVT::v4f64 ||
9537       Op.getValueType() == MVT::v4f32) {
9538     EVT MemVT = LN->getMemoryVT();
9539     unsigned Alignment = LN->getAlignment();
9540 
9541     // If this load is properly aligned, then it is legal.
9542     if (Alignment >= MemVT.getStoreSize())
9543       return Op;
9544 
9545     EVT ScalarVT = Op.getValueType().getScalarType(),
9546         ScalarMemVT = MemVT.getScalarType();
9547     unsigned Stride = ScalarMemVT.getStoreSize();
9548 
9549     SDValue Vals[4], LoadChains[4];
9550     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9551       SDValue Load;
9552       if (ScalarVT != ScalarMemVT)
9553         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9554                               BasePtr,
9555                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9556                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9557                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9558       else
9559         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9560                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9561                            MinAlign(Alignment, Idx * Stride),
9562                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9563 
9564       if (Idx == 0 && LN->isIndexed()) {
9565         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9566                "Unknown addressing mode on vector load");
9567         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9568                                   LN->getAddressingMode());
9569       }
9570 
9571       Vals[Idx] = Load;
9572       LoadChains[Idx] = Load.getValue(1);
9573 
9574       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9575                             DAG.getConstant(Stride, dl,
9576                                             BasePtr.getValueType()));
9577     }
9578 
9579     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9580     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9581 
9582     if (LN->isIndexed()) {
9583       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9584       return DAG.getMergeValues(RetOps, dl);
9585     }
9586 
9587     SDValue RetOps[] = { Value, TF };
9588     return DAG.getMergeValues(RetOps, dl);
9589   }
9590 
9591   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9592   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9593 
9594   // To lower v4i1 from a byte array, we load the byte elements of the
9595   // vector and then reuse the BUILD_VECTOR logic.
9596 
9597   SDValue VectElmts[4], VectElmtChains[4];
9598   for (unsigned i = 0; i < 4; ++i) {
9599     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9600     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9601 
9602     VectElmts[i] = DAG.getExtLoad(
9603         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9604         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9605         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9606     VectElmtChains[i] = VectElmts[i].getValue(1);
9607   }
9608 
9609   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9610   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9611 
9612   SDValue RVals[] = { Value, LoadChain };
9613   return DAG.getMergeValues(RVals, dl);
9614 }
9615 
9616 /// Lowering for QPX v4i1 stores
9617 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9618                                             SelectionDAG &DAG) const {
9619   SDLoc dl(Op);
9620   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9621   SDValue StoreChain = SN->getChain();
9622   SDValue BasePtr = SN->getBasePtr();
9623   SDValue Value = SN->getValue();
9624 
9625   if (Value.getValueType() == MVT::v4f64 ||
9626       Value.getValueType() == MVT::v4f32) {
9627     EVT MemVT = SN->getMemoryVT();
9628     unsigned Alignment = SN->getAlignment();
9629 
9630     // If this store is properly aligned, then it is legal.
9631     if (Alignment >= MemVT.getStoreSize())
9632       return Op;
9633 
9634     EVT ScalarVT = Value.getValueType().getScalarType(),
9635         ScalarMemVT = MemVT.getScalarType();
9636     unsigned Stride = ScalarMemVT.getStoreSize();
9637 
9638     SDValue Stores[4];
9639     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9640       SDValue Ex = DAG.getNode(
9641           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9642           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9643       SDValue Store;
9644       if (ScalarVT != ScalarMemVT)
9645         Store =
9646             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9647                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9648                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9649                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9650       else
9651         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9652                              SN->getPointerInfo().getWithOffset(Idx * Stride),
9653                              MinAlign(Alignment, Idx * Stride),
9654                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
9655 
9656       if (Idx == 0 && SN->isIndexed()) {
9657         assert(SN->getAddressingMode() == ISD::PRE_INC &&
9658                "Unknown addressing mode on vector store");
9659         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9660                                     SN->getAddressingMode());
9661       }
9662 
9663       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9664                             DAG.getConstant(Stride, dl,
9665                                             BasePtr.getValueType()));
9666       Stores[Idx] = Store;
9667     }
9668 
9669     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9670 
9671     if (SN->isIndexed()) {
9672       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9673       return DAG.getMergeValues(RetOps, dl);
9674     }
9675 
9676     return TF;
9677   }
9678 
9679   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9680   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9681 
9682   // The values are now known to be -1 (false) or 1 (true). To convert this
9683   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9684   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9685   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9686 
9687   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9688   // understand how to form the extending load.
9689   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9690 
9691   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9692 
9693   // Now convert to an integer and store.
9694   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9695     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9696     Value);
9697 
9698   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9699   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9700   MachinePointerInfo PtrInfo =
9701       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9702   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9703   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9704 
9705   SDValue Ops[] = {StoreChain,
9706                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9707                    Value, FIdx};
9708   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9709 
9710   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9711     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9712 
9713   // Move data into the byte array.
9714   SDValue Loads[4], LoadChains[4];
9715   for (unsigned i = 0; i < 4; ++i) {
9716     unsigned Offset = 4*i;
9717     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9718     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9719 
9720     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9721                            PtrInfo.getWithOffset(Offset));
9722     LoadChains[i] = Loads[i].getValue(1);
9723   }
9724 
9725   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9726 
9727   SDValue Stores[4];
9728   for (unsigned i = 0; i < 4; ++i) {
9729     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9730     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9731 
9732     Stores[i] = DAG.getTruncStore(
9733         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9734         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9735         SN->getAAInfo());
9736   }
9737 
9738   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9739 
9740   return StoreChain;
9741 }
9742 
9743 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9744   SDLoc dl(Op);
9745   if (Op.getValueType() == MVT::v4i32) {
9746     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9747 
9748     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9749     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9750 
9751     SDValue RHSSwap =   // = vrlw RHS, 16
9752       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9753 
9754     // Shrinkify inputs to v8i16.
9755     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9756     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9757     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9758 
9759     // Low parts multiplied together, generating 32-bit results (we ignore the
9760     // top parts).
9761     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9762                                         LHS, RHS, DAG, dl, MVT::v4i32);
9763 
9764     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9765                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9766     // Shift the high parts up 16 bits.
9767     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9768                               Neg16, DAG, dl);
9769     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9770   } else if (Op.getValueType() == MVT::v8i16) {
9771     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9772 
9773     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9774 
9775     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9776                             LHS, RHS, Zero, DAG, dl);
9777   } else if (Op.getValueType() == MVT::v16i8) {
9778     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9779     bool isLittleEndian = Subtarget.isLittleEndian();
9780 
9781     // Multiply the even 8-bit parts, producing 16-bit sums.
9782     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9783                                            LHS, RHS, DAG, dl, MVT::v8i16);
9784     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9785 
9786     // Multiply the odd 8-bit parts, producing 16-bit sums.
9787     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9788                                           LHS, RHS, DAG, dl, MVT::v8i16);
9789     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9790 
9791     // Merge the results together.  Because vmuleub and vmuloub are
9792     // instructions with a big-endian bias, we must reverse the
9793     // element numbering and reverse the meaning of "odd" and "even"
9794     // when generating little endian code.
9795     int Ops[16];
9796     for (unsigned i = 0; i != 8; ++i) {
9797       if (isLittleEndian) {
9798         Ops[i*2  ] = 2*i;
9799         Ops[i*2+1] = 2*i+16;
9800       } else {
9801         Ops[i*2  ] = 2*i+1;
9802         Ops[i*2+1] = 2*i+1+16;
9803       }
9804     }
9805     if (isLittleEndian)
9806       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9807     else
9808       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9809   } else {
9810     llvm_unreachable("Unknown mul to lower!");
9811   }
9812 }
9813 
9814 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
9815 
9816   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
9817 
9818   EVT VT = Op.getValueType();
9819   assert(VT.isVector() &&
9820          "Only set vector abs as custom, scalar abs shouldn't reach here!");
9821   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
9822           VT == MVT::v16i8) &&
9823          "Unexpected vector element type!");
9824   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
9825          "Current subtarget doesn't support smax v2i64!");
9826 
9827   // For vector abs, it can be lowered to:
9828   // abs x
9829   // ==>
9830   // y = -x
9831   // smax(x, y)
9832 
9833   SDLoc dl(Op);
9834   SDValue X = Op.getOperand(0);
9835   SDValue Zero = DAG.getConstant(0, dl, VT);
9836   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
9837 
9838   // SMAX patch https://reviews.llvm.org/D47332
9839   // hasn't landed yet, so use intrinsic first here.
9840   // TODO: Should use SMAX directly once SMAX patch landed
9841   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
9842   if (VT == MVT::v2i64)
9843     BifID = Intrinsic::ppc_altivec_vmaxsd;
9844   else if (VT == MVT::v8i16)
9845     BifID = Intrinsic::ppc_altivec_vmaxsh;
9846   else if (VT == MVT::v16i8)
9847     BifID = Intrinsic::ppc_altivec_vmaxsb;
9848 
9849   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
9850 }
9851 
9852 // Custom lowering for fpext vf32 to v2f64
9853 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
9854 
9855   assert(Op.getOpcode() == ISD::FP_EXTEND &&
9856          "Should only be called for ISD::FP_EXTEND");
9857 
9858   // We only want to custom lower an extend from v2f32 to v2f64.
9859   if (Op.getValueType() != MVT::v2f64 ||
9860       Op.getOperand(0).getValueType() != MVT::v2f32)
9861     return SDValue();
9862 
9863   SDLoc dl(Op);
9864   SDValue Op0 = Op.getOperand(0);
9865 
9866   switch (Op0.getOpcode()) {
9867   default:
9868     return SDValue();
9869   case ISD::FADD:
9870   case ISD::FMUL:
9871   case ISD::FSUB: {
9872     SDValue NewLoad[2];
9873     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
9874       // Ensure both input are loads.
9875       SDValue LdOp = Op0.getOperand(i);
9876       if (LdOp.getOpcode() != ISD::LOAD)
9877         return SDValue();
9878       // Generate new load node.
9879       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
9880       SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() };
9881       NewLoad[i] =
9882         DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl,
9883                                 DAG.getVTList(MVT::v4f32, MVT::Other),
9884                                 LoadOps, LD->getMemoryVT(),
9885                                 LD->getMemOperand());
9886     }
9887     SDValue NewOp = DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32,
9888                               NewLoad[0], NewLoad[1],
9889                               Op0.getNode()->getFlags());
9890     return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewOp);
9891   }
9892   case ISD::LOAD: {
9893     LoadSDNode *LD = cast<LoadSDNode>(Op0);
9894     SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() };
9895     SDValue NewLd =
9896       DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl,
9897                               DAG.getVTList(MVT::v4f32, MVT::Other),
9898                               LoadOps, LD->getMemoryVT(), LD->getMemOperand());
9899     return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewLd);
9900   }
9901   }
9902   llvm_unreachable("ERROR:Should return for all cases within swtich.");
9903 }
9904 
9905 /// LowerOperation - Provide custom lowering hooks for some operations.
9906 ///
9907 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9908   switch (Op.getOpcode()) {
9909   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9910   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9911   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9912   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9913   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9914   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9915   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9916   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
9917   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
9918 
9919   // Variable argument lowering.
9920   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9921   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9922   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9923 
9924   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
9925   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9926   case ISD::GET_DYNAMIC_AREA_OFFSET:
9927     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9928 
9929   // Exception handling lowering.
9930   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
9931   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
9932   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
9933 
9934   case ISD::LOAD:               return LowerLOAD(Op, DAG);
9935   case ISD::STORE:              return LowerSTORE(Op, DAG);
9936   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
9937   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
9938   case ISD::FP_TO_UINT:
9939   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
9940   case ISD::UINT_TO_FP:
9941   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
9942   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9943 
9944   // Lower 64-bit shifts.
9945   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
9946   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
9947   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
9948 
9949   // Vector-related lowering.
9950   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9951   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9952   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9953   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9954   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9955   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9956   case ISD::MUL:                return LowerMUL(Op, DAG);
9957   case ISD::ABS:                return LowerABS(Op, DAG);
9958   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
9959 
9960   // For counter-based loop handling.
9961   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
9962 
9963   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9964 
9965   // Frame & Return address.
9966   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9967   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9968 
9969   case ISD::INTRINSIC_VOID:
9970     return LowerINTRINSIC_VOID(Op, DAG);
9971   case ISD::SREM:
9972   case ISD::UREM:
9973     return LowerREM(Op, DAG);
9974   case ISD::BSWAP:
9975     return LowerBSWAP(Op, DAG);
9976   case ISD::ATOMIC_CMP_SWAP:
9977     return LowerATOMIC_CMP_SWAP(Op, DAG);
9978   }
9979 }
9980 
9981 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9982                                            SmallVectorImpl<SDValue>&Results,
9983                                            SelectionDAG &DAG) const {
9984   SDLoc dl(N);
9985   switch (N->getOpcode()) {
9986   default:
9987     llvm_unreachable("Do not know how to custom type legalize this operation!");
9988   case ISD::READCYCLECOUNTER: {
9989     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9990     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9991 
9992     Results.push_back(RTB);
9993     Results.push_back(RTB.getValue(1));
9994     Results.push_back(RTB.getValue(2));
9995     break;
9996   }
9997   case ISD::INTRINSIC_W_CHAIN: {
9998     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9999         Intrinsic::loop_decrement)
10000       break;
10001 
10002     assert(N->getValueType(0) == MVT::i1 &&
10003            "Unexpected result type for CTR decrement intrinsic");
10004     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10005                                  N->getValueType(0));
10006     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10007     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10008                                  N->getOperand(1));
10009 
10010     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10011     Results.push_back(NewInt.getValue(1));
10012     break;
10013   }
10014   case ISD::VAARG: {
10015     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10016       return;
10017 
10018     EVT VT = N->getValueType(0);
10019 
10020     if (VT == MVT::i64) {
10021       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10022 
10023       Results.push_back(NewNode);
10024       Results.push_back(NewNode.getValue(1));
10025     }
10026     return;
10027   }
10028   case ISD::FP_TO_SINT:
10029   case ISD::FP_TO_UINT:
10030     // LowerFP_TO_INT() can only handle f32 and f64.
10031     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10032       return;
10033     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10034     return;
10035   case ISD::TRUNCATE: {
10036     EVT TrgVT = N->getValueType(0);
10037     if (TrgVT.isVector() &&
10038         isOperationCustom(N->getOpcode(), TrgVT) &&
10039         N->getOperand(0).getValueType().getSizeInBits() <= 128)
10040       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10041     return;
10042   }
10043   case ISD::BITCAST:
10044     // Don't handle bitcast here.
10045     return;
10046   }
10047 }
10048 
10049 //===----------------------------------------------------------------------===//
10050 //  Other Lowering Code
10051 //===----------------------------------------------------------------------===//
10052 
10053 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10054   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10055   Function *Func = Intrinsic::getDeclaration(M, Id);
10056   return Builder.CreateCall(Func, {});
10057 }
10058 
10059 // The mappings for emitLeading/TrailingFence is taken from
10060 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10061 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10062                                                  Instruction *Inst,
10063                                                  AtomicOrdering Ord) const {
10064   if (Ord == AtomicOrdering::SequentiallyConsistent)
10065     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10066   if (isReleaseOrStronger(Ord))
10067     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10068   return nullptr;
10069 }
10070 
10071 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10072                                                   Instruction *Inst,
10073                                                   AtomicOrdering Ord) const {
10074   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10075     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10076     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10077     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10078     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10079       return Builder.CreateCall(
10080           Intrinsic::getDeclaration(
10081               Builder.GetInsertBlock()->getParent()->getParent(),
10082               Intrinsic::ppc_cfence, {Inst->getType()}),
10083           {Inst});
10084     // FIXME: Can use isync for rmw operation.
10085     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10086   }
10087   return nullptr;
10088 }
10089 
10090 MachineBasicBlock *
10091 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10092                                     unsigned AtomicSize,
10093                                     unsigned BinOpcode,
10094                                     unsigned CmpOpcode,
10095                                     unsigned CmpPred) const {
10096   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10097   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10098 
10099   auto LoadMnemonic = PPC::LDARX;
10100   auto StoreMnemonic = PPC::STDCX;
10101   switch (AtomicSize) {
10102   default:
10103     llvm_unreachable("Unexpected size of atomic entity");
10104   case 1:
10105     LoadMnemonic = PPC::LBARX;
10106     StoreMnemonic = PPC::STBCX;
10107     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10108     break;
10109   case 2:
10110     LoadMnemonic = PPC::LHARX;
10111     StoreMnemonic = PPC::STHCX;
10112     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10113     break;
10114   case 4:
10115     LoadMnemonic = PPC::LWARX;
10116     StoreMnemonic = PPC::STWCX;
10117     break;
10118   case 8:
10119     LoadMnemonic = PPC::LDARX;
10120     StoreMnemonic = PPC::STDCX;
10121     break;
10122   }
10123 
10124   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10125   MachineFunction *F = BB->getParent();
10126   MachineFunction::iterator It = ++BB->getIterator();
10127 
10128   Register dest = MI.getOperand(0).getReg();
10129   Register ptrA = MI.getOperand(1).getReg();
10130   Register ptrB = MI.getOperand(2).getReg();
10131   Register incr = MI.getOperand(3).getReg();
10132   DebugLoc dl = MI.getDebugLoc();
10133 
10134   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10135   MachineBasicBlock *loop2MBB =
10136     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10137   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10138   F->insert(It, loopMBB);
10139   if (CmpOpcode)
10140     F->insert(It, loop2MBB);
10141   F->insert(It, exitMBB);
10142   exitMBB->splice(exitMBB->begin(), BB,
10143                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10144   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10145 
10146   MachineRegisterInfo &RegInfo = F->getRegInfo();
10147   Register TmpReg = (!BinOpcode) ? incr :
10148     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10149                                            : &PPC::GPRCRegClass);
10150 
10151   //  thisMBB:
10152   //   ...
10153   //   fallthrough --> loopMBB
10154   BB->addSuccessor(loopMBB);
10155 
10156   //  loopMBB:
10157   //   l[wd]arx dest, ptr
10158   //   add r0, dest, incr
10159   //   st[wd]cx. r0, ptr
10160   //   bne- loopMBB
10161   //   fallthrough --> exitMBB
10162 
10163   // For max/min...
10164   //  loopMBB:
10165   //   l[wd]arx dest, ptr
10166   //   cmpl?[wd] incr, dest
10167   //   bgt exitMBB
10168   //  loop2MBB:
10169   //   st[wd]cx. dest, ptr
10170   //   bne- loopMBB
10171   //   fallthrough --> exitMBB
10172 
10173   BB = loopMBB;
10174   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10175     .addReg(ptrA).addReg(ptrB);
10176   if (BinOpcode)
10177     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10178   if (CmpOpcode) {
10179     // Signed comparisons of byte or halfword values must be sign-extended.
10180     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10181       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10182       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10183               ExtReg).addReg(dest);
10184       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10185         .addReg(incr).addReg(ExtReg);
10186     } else
10187       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10188         .addReg(incr).addReg(dest);
10189 
10190     BuildMI(BB, dl, TII->get(PPC::BCC))
10191       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10192     BB->addSuccessor(loop2MBB);
10193     BB->addSuccessor(exitMBB);
10194     BB = loop2MBB;
10195   }
10196   BuildMI(BB, dl, TII->get(StoreMnemonic))
10197     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10198   BuildMI(BB, dl, TII->get(PPC::BCC))
10199     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10200   BB->addSuccessor(loopMBB);
10201   BB->addSuccessor(exitMBB);
10202 
10203   //  exitMBB:
10204   //   ...
10205   BB = exitMBB;
10206   return BB;
10207 }
10208 
10209 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10210     MachineInstr &MI, MachineBasicBlock *BB,
10211     bool is8bit, // operation
10212     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10213   // If we support part-word atomic mnemonics, just use them
10214   if (Subtarget.hasPartwordAtomics())
10215     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10216                             CmpPred);
10217 
10218   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10219   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10220   // In 64 bit mode we have to use 64 bits for addresses, even though the
10221   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10222   // registers without caring whether they're 32 or 64, but here we're
10223   // doing actual arithmetic on the addresses.
10224   bool is64bit = Subtarget.isPPC64();
10225   bool isLittleEndian = Subtarget.isLittleEndian();
10226   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10227 
10228   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10229   MachineFunction *F = BB->getParent();
10230   MachineFunction::iterator It = ++BB->getIterator();
10231 
10232   unsigned dest = MI.getOperand(0).getReg();
10233   unsigned ptrA = MI.getOperand(1).getReg();
10234   unsigned ptrB = MI.getOperand(2).getReg();
10235   unsigned incr = MI.getOperand(3).getReg();
10236   DebugLoc dl = MI.getDebugLoc();
10237 
10238   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10239   MachineBasicBlock *loop2MBB =
10240       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10241   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10242   F->insert(It, loopMBB);
10243   if (CmpOpcode)
10244     F->insert(It, loop2MBB);
10245   F->insert(It, exitMBB);
10246   exitMBB->splice(exitMBB->begin(), BB,
10247                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10248   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10249 
10250   MachineRegisterInfo &RegInfo = F->getRegInfo();
10251   const TargetRegisterClass *RC =
10252       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10253   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10254 
10255   Register PtrReg = RegInfo.createVirtualRegister(RC);
10256   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10257   Register ShiftReg =
10258       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10259   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10260   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10261   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10262   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10263   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10264   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10265   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10266   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10267   Register Ptr1Reg;
10268   Register TmpReg =
10269       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10270 
10271   //  thisMBB:
10272   //   ...
10273   //   fallthrough --> loopMBB
10274   BB->addSuccessor(loopMBB);
10275 
10276   // The 4-byte load must be aligned, while a char or short may be
10277   // anywhere in the word.  Hence all this nasty bookkeeping code.
10278   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10279   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10280   //   xori shift, shift1, 24 [16]
10281   //   rlwinm ptr, ptr1, 0, 0, 29
10282   //   slw incr2, incr, shift
10283   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10284   //   slw mask, mask2, shift
10285   //  loopMBB:
10286   //   lwarx tmpDest, ptr
10287   //   add tmp, tmpDest, incr2
10288   //   andc tmp2, tmpDest, mask
10289   //   and tmp3, tmp, mask
10290   //   or tmp4, tmp3, tmp2
10291   //   stwcx. tmp4, ptr
10292   //   bne- loopMBB
10293   //   fallthrough --> exitMBB
10294   //   srw dest, tmpDest, shift
10295   if (ptrA != ZeroReg) {
10296     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10297     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10298         .addReg(ptrA)
10299         .addReg(ptrB);
10300   } else {
10301     Ptr1Reg = ptrB;
10302   }
10303   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10304   // mode.
10305   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10306       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10307       .addImm(3)
10308       .addImm(27)
10309       .addImm(is8bit ? 28 : 27);
10310   if (!isLittleEndian)
10311     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10312         .addReg(Shift1Reg)
10313         .addImm(is8bit ? 24 : 16);
10314   if (is64bit)
10315     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10316         .addReg(Ptr1Reg)
10317         .addImm(0)
10318         .addImm(61);
10319   else
10320     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10321         .addReg(Ptr1Reg)
10322         .addImm(0)
10323         .addImm(0)
10324         .addImm(29);
10325   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10326   if (is8bit)
10327     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10328   else {
10329     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10330     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10331         .addReg(Mask3Reg)
10332         .addImm(65535);
10333   }
10334   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10335       .addReg(Mask2Reg)
10336       .addReg(ShiftReg);
10337 
10338   BB = loopMBB;
10339   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10340       .addReg(ZeroReg)
10341       .addReg(PtrReg);
10342   if (BinOpcode)
10343     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10344         .addReg(Incr2Reg)
10345         .addReg(TmpDestReg);
10346   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10347       .addReg(TmpDestReg)
10348       .addReg(MaskReg);
10349   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10350   if (CmpOpcode) {
10351     // For unsigned comparisons, we can directly compare the shifted values.
10352     // For signed comparisons we shift and sign extend.
10353     unsigned SReg = RegInfo.createVirtualRegister(GPRC);
10354     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10355         .addReg(TmpDestReg)
10356         .addReg(MaskReg);
10357     unsigned ValueReg = SReg;
10358     unsigned CmpReg = Incr2Reg;
10359     if (CmpOpcode == PPC::CMPW) {
10360       ValueReg = RegInfo.createVirtualRegister(GPRC);
10361       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10362           .addReg(SReg)
10363           .addReg(ShiftReg);
10364       unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC);
10365       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10366           .addReg(ValueReg);
10367       ValueReg = ValueSReg;
10368       CmpReg = incr;
10369     }
10370     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10371         .addReg(CmpReg)
10372         .addReg(ValueReg);
10373     BuildMI(BB, dl, TII->get(PPC::BCC))
10374         .addImm(CmpPred)
10375         .addReg(PPC::CR0)
10376         .addMBB(exitMBB);
10377     BB->addSuccessor(loop2MBB);
10378     BB->addSuccessor(exitMBB);
10379     BB = loop2MBB;
10380   }
10381   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10382   BuildMI(BB, dl, TII->get(PPC::STWCX))
10383       .addReg(Tmp4Reg)
10384       .addReg(ZeroReg)
10385       .addReg(PtrReg);
10386   BuildMI(BB, dl, TII->get(PPC::BCC))
10387       .addImm(PPC::PRED_NE)
10388       .addReg(PPC::CR0)
10389       .addMBB(loopMBB);
10390   BB->addSuccessor(loopMBB);
10391   BB->addSuccessor(exitMBB);
10392 
10393   //  exitMBB:
10394   //   ...
10395   BB = exitMBB;
10396   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10397       .addReg(TmpDestReg)
10398       .addReg(ShiftReg);
10399   return BB;
10400 }
10401 
10402 llvm::MachineBasicBlock *
10403 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10404                                     MachineBasicBlock *MBB) const {
10405   DebugLoc DL = MI.getDebugLoc();
10406   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10407   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10408 
10409   MachineFunction *MF = MBB->getParent();
10410   MachineRegisterInfo &MRI = MF->getRegInfo();
10411 
10412   const BasicBlock *BB = MBB->getBasicBlock();
10413   MachineFunction::iterator I = ++MBB->getIterator();
10414 
10415   unsigned DstReg = MI.getOperand(0).getReg();
10416   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10417   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10418   unsigned mainDstReg = MRI.createVirtualRegister(RC);
10419   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
10420 
10421   MVT PVT = getPointerTy(MF->getDataLayout());
10422   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10423          "Invalid Pointer Size!");
10424   // For v = setjmp(buf), we generate
10425   //
10426   // thisMBB:
10427   //  SjLjSetup mainMBB
10428   //  bl mainMBB
10429   //  v_restore = 1
10430   //  b sinkMBB
10431   //
10432   // mainMBB:
10433   //  buf[LabelOffset] = LR
10434   //  v_main = 0
10435   //
10436   // sinkMBB:
10437   //  v = phi(main, restore)
10438   //
10439 
10440   MachineBasicBlock *thisMBB = MBB;
10441   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10442   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10443   MF->insert(I, mainMBB);
10444   MF->insert(I, sinkMBB);
10445 
10446   MachineInstrBuilder MIB;
10447 
10448   // Transfer the remainder of BB and its successor edges to sinkMBB.
10449   sinkMBB->splice(sinkMBB->begin(), MBB,
10450                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10451   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10452 
10453   // Note that the structure of the jmp_buf used here is not compatible
10454   // with that used by libc, and is not designed to be. Specifically, it
10455   // stores only those 'reserved' registers that LLVM does not otherwise
10456   // understand how to spill. Also, by convention, by the time this
10457   // intrinsic is called, Clang has already stored the frame address in the
10458   // first slot of the buffer and stack address in the third. Following the
10459   // X86 target code, we'll store the jump address in the second slot. We also
10460   // need to save the TOC pointer (R2) to handle jumps between shared
10461   // libraries, and that will be stored in the fourth slot. The thread
10462   // identifier (R13) is not affected.
10463 
10464   // thisMBB:
10465   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10466   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10467   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10468 
10469   // Prepare IP either in reg.
10470   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10471   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
10472   unsigned BufReg = MI.getOperand(1).getReg();
10473 
10474   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
10475     setUsesTOCBasePtr(*MBB->getParent());
10476     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10477               .addReg(PPC::X2)
10478               .addImm(TOCOffset)
10479               .addReg(BufReg)
10480               .cloneMemRefs(MI);
10481   }
10482 
10483   // Naked functions never have a base pointer, and so we use r1. For all
10484   // other functions, this decision must be delayed until during PEI.
10485   unsigned BaseReg;
10486   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10487     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10488   else
10489     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10490 
10491   MIB = BuildMI(*thisMBB, MI, DL,
10492                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10493             .addReg(BaseReg)
10494             .addImm(BPOffset)
10495             .addReg(BufReg)
10496             .cloneMemRefs(MI);
10497 
10498   // Setup
10499   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10500   MIB.addRegMask(TRI->getNoPreservedMask());
10501 
10502   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10503 
10504   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10505           .addMBB(mainMBB);
10506   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10507 
10508   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10509   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10510 
10511   // mainMBB:
10512   //  mainDstReg = 0
10513   MIB =
10514       BuildMI(mainMBB, DL,
10515               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10516 
10517   // Store IP
10518   if (Subtarget.isPPC64()) {
10519     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10520             .addReg(LabelReg)
10521             .addImm(LabelOffset)
10522             .addReg(BufReg);
10523   } else {
10524     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10525             .addReg(LabelReg)
10526             .addImm(LabelOffset)
10527             .addReg(BufReg);
10528   }
10529   MIB.cloneMemRefs(MI);
10530 
10531   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10532   mainMBB->addSuccessor(sinkMBB);
10533 
10534   // sinkMBB:
10535   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10536           TII->get(PPC::PHI), DstReg)
10537     .addReg(mainDstReg).addMBB(mainMBB)
10538     .addReg(restoreDstReg).addMBB(thisMBB);
10539 
10540   MI.eraseFromParent();
10541   return sinkMBB;
10542 }
10543 
10544 MachineBasicBlock *
10545 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10546                                      MachineBasicBlock *MBB) const {
10547   DebugLoc DL = MI.getDebugLoc();
10548   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10549 
10550   MachineFunction *MF = MBB->getParent();
10551   MachineRegisterInfo &MRI = MF->getRegInfo();
10552 
10553   MVT PVT = getPointerTy(MF->getDataLayout());
10554   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10555          "Invalid Pointer Size!");
10556 
10557   const TargetRegisterClass *RC =
10558     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10559   unsigned Tmp = MRI.createVirtualRegister(RC);
10560   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10561   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10562   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10563   unsigned BP =
10564       (PVT == MVT::i64)
10565           ? PPC::X30
10566           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10567                                                               : PPC::R30);
10568 
10569   MachineInstrBuilder MIB;
10570 
10571   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10572   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10573   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10574   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10575 
10576   unsigned BufReg = MI.getOperand(0).getReg();
10577 
10578   // Reload FP (the jumped-to function may not have had a
10579   // frame pointer, and if so, then its r31 will be restored
10580   // as necessary).
10581   if (PVT == MVT::i64) {
10582     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10583             .addImm(0)
10584             .addReg(BufReg);
10585   } else {
10586     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10587             .addImm(0)
10588             .addReg(BufReg);
10589   }
10590   MIB.cloneMemRefs(MI);
10591 
10592   // Reload IP
10593   if (PVT == MVT::i64) {
10594     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10595             .addImm(LabelOffset)
10596             .addReg(BufReg);
10597   } else {
10598     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10599             .addImm(LabelOffset)
10600             .addReg(BufReg);
10601   }
10602   MIB.cloneMemRefs(MI);
10603 
10604   // Reload SP
10605   if (PVT == MVT::i64) {
10606     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10607             .addImm(SPOffset)
10608             .addReg(BufReg);
10609   } else {
10610     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10611             .addImm(SPOffset)
10612             .addReg(BufReg);
10613   }
10614   MIB.cloneMemRefs(MI);
10615 
10616   // Reload BP
10617   if (PVT == MVT::i64) {
10618     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10619             .addImm(BPOffset)
10620             .addReg(BufReg);
10621   } else {
10622     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10623             .addImm(BPOffset)
10624             .addReg(BufReg);
10625   }
10626   MIB.cloneMemRefs(MI);
10627 
10628   // Reload TOC
10629   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
10630     setUsesTOCBasePtr(*MBB->getParent());
10631     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
10632               .addImm(TOCOffset)
10633               .addReg(BufReg)
10634               .cloneMemRefs(MI);
10635   }
10636 
10637   // Jump
10638   BuildMI(*MBB, MI, DL,
10639           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
10640   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
10641 
10642   MI.eraseFromParent();
10643   return MBB;
10644 }
10645 
10646 MachineBasicBlock *
10647 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10648                                                MachineBasicBlock *BB) const {
10649   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
10650       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10651     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
10652         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10653       // Call lowering should have added an r2 operand to indicate a dependence
10654       // on the TOC base pointer value. It can't however, because there is no
10655       // way to mark the dependence as implicit there, and so the stackmap code
10656       // will confuse it with a regular operand. Instead, add the dependence
10657       // here.
10658       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10659     }
10660 
10661     return emitPatchPoint(MI, BB);
10662   }
10663 
10664   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10665       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10666     return emitEHSjLjSetJmp(MI, BB);
10667   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10668              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10669     return emitEHSjLjLongJmp(MI, BB);
10670   }
10671 
10672   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10673 
10674   // To "insert" these instructions we actually have to insert their
10675   // control-flow patterns.
10676   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10677   MachineFunction::iterator It = ++BB->getIterator();
10678 
10679   MachineFunction *F = BB->getParent();
10680 
10681   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10682       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
10683       MI.getOpcode() == PPC::SELECT_I8) {
10684     SmallVector<MachineOperand, 2> Cond;
10685     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10686         MI.getOpcode() == PPC::SELECT_CC_I8)
10687       Cond.push_back(MI.getOperand(4));
10688     else
10689       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10690     Cond.push_back(MI.getOperand(1));
10691 
10692     DebugLoc dl = MI.getDebugLoc();
10693     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10694                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10695   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10696              MI.getOpcode() == PPC::SELECT_CC_I8 ||
10697              MI.getOpcode() == PPC::SELECT_CC_F4 ||
10698              MI.getOpcode() == PPC::SELECT_CC_F8 ||
10699              MI.getOpcode() == PPC::SELECT_CC_F16 ||
10700              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10701              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10702              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10703              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10704              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10705              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10706              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10707              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
10708              MI.getOpcode() == PPC::SELECT_CC_SPE ||
10709              MI.getOpcode() == PPC::SELECT_I4 ||
10710              MI.getOpcode() == PPC::SELECT_I8 ||
10711              MI.getOpcode() == PPC::SELECT_F4 ||
10712              MI.getOpcode() == PPC::SELECT_F8 ||
10713              MI.getOpcode() == PPC::SELECT_F16 ||
10714              MI.getOpcode() == PPC::SELECT_QFRC ||
10715              MI.getOpcode() == PPC::SELECT_QSRC ||
10716              MI.getOpcode() == PPC::SELECT_QBRC ||
10717              MI.getOpcode() == PPC::SELECT_SPE ||
10718              MI.getOpcode() == PPC::SELECT_SPE4 ||
10719              MI.getOpcode() == PPC::SELECT_VRRC ||
10720              MI.getOpcode() == PPC::SELECT_VSFRC ||
10721              MI.getOpcode() == PPC::SELECT_VSSRC ||
10722              MI.getOpcode() == PPC::SELECT_VSRC) {
10723     // The incoming instruction knows the destination vreg to set, the
10724     // condition code register to branch on, the true/false values to
10725     // select between, and a branch opcode to use.
10726 
10727     //  thisMBB:
10728     //  ...
10729     //   TrueVal = ...
10730     //   cmpTY ccX, r1, r2
10731     //   bCC copy1MBB
10732     //   fallthrough --> copy0MBB
10733     MachineBasicBlock *thisMBB = BB;
10734     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10735     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10736     DebugLoc dl = MI.getDebugLoc();
10737     F->insert(It, copy0MBB);
10738     F->insert(It, sinkMBB);
10739 
10740     // Transfer the remainder of BB and its successor edges to sinkMBB.
10741     sinkMBB->splice(sinkMBB->begin(), BB,
10742                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10743     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10744 
10745     // Next, add the true and fallthrough blocks as its successors.
10746     BB->addSuccessor(copy0MBB);
10747     BB->addSuccessor(sinkMBB);
10748 
10749     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10750         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10751         MI.getOpcode() == PPC::SELECT_F16 ||
10752         MI.getOpcode() == PPC::SELECT_SPE4 ||
10753         MI.getOpcode() == PPC::SELECT_SPE ||
10754         MI.getOpcode() == PPC::SELECT_QFRC ||
10755         MI.getOpcode() == PPC::SELECT_QSRC ||
10756         MI.getOpcode() == PPC::SELECT_QBRC ||
10757         MI.getOpcode() == PPC::SELECT_VRRC ||
10758         MI.getOpcode() == PPC::SELECT_VSFRC ||
10759         MI.getOpcode() == PPC::SELECT_VSSRC ||
10760         MI.getOpcode() == PPC::SELECT_VSRC) {
10761       BuildMI(BB, dl, TII->get(PPC::BC))
10762           .addReg(MI.getOperand(1).getReg())
10763           .addMBB(sinkMBB);
10764     } else {
10765       unsigned SelectPred = MI.getOperand(4).getImm();
10766       BuildMI(BB, dl, TII->get(PPC::BCC))
10767           .addImm(SelectPred)
10768           .addReg(MI.getOperand(1).getReg())
10769           .addMBB(sinkMBB);
10770     }
10771 
10772     //  copy0MBB:
10773     //   %FalseValue = ...
10774     //   # fallthrough to sinkMBB
10775     BB = copy0MBB;
10776 
10777     // Update machine-CFG edges
10778     BB->addSuccessor(sinkMBB);
10779 
10780     //  sinkMBB:
10781     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10782     //  ...
10783     BB = sinkMBB;
10784     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10785         .addReg(MI.getOperand(3).getReg())
10786         .addMBB(copy0MBB)
10787         .addReg(MI.getOperand(2).getReg())
10788         .addMBB(thisMBB);
10789   } else if (MI.getOpcode() == PPC::ReadTB) {
10790     // To read the 64-bit time-base register on a 32-bit target, we read the
10791     // two halves. Should the counter have wrapped while it was being read, we
10792     // need to try again.
10793     // ...
10794     // readLoop:
10795     // mfspr Rx,TBU # load from TBU
10796     // mfspr Ry,TB  # load from TB
10797     // mfspr Rz,TBU # load from TBU
10798     // cmpw crX,Rx,Rz # check if 'old'='new'
10799     // bne readLoop   # branch if they're not equal
10800     // ...
10801 
10802     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10803     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10804     DebugLoc dl = MI.getDebugLoc();
10805     F->insert(It, readMBB);
10806     F->insert(It, sinkMBB);
10807 
10808     // Transfer the remainder of BB and its successor edges to sinkMBB.
10809     sinkMBB->splice(sinkMBB->begin(), BB,
10810                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10811     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10812 
10813     BB->addSuccessor(readMBB);
10814     BB = readMBB;
10815 
10816     MachineRegisterInfo &RegInfo = F->getRegInfo();
10817     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10818     unsigned LoReg = MI.getOperand(0).getReg();
10819     unsigned HiReg = MI.getOperand(1).getReg();
10820 
10821     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10822     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10823     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10824 
10825     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10826 
10827     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10828         .addReg(HiReg)
10829         .addReg(ReadAgainReg);
10830     BuildMI(BB, dl, TII->get(PPC::BCC))
10831         .addImm(PPC::PRED_NE)
10832         .addReg(CmpReg)
10833         .addMBB(readMBB);
10834 
10835     BB->addSuccessor(readMBB);
10836     BB->addSuccessor(sinkMBB);
10837   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10838     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10839   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10840     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10841   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10842     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10843   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10844     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10845 
10846   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10847     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10848   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10849     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10850   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10851     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10852   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10853     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10854 
10855   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10856     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10857   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10858     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10859   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10860     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10861   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10862     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10863 
10864   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10865     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10866   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10867     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10868   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10869     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10870   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10871     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10872 
10873   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10874     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10875   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10876     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10877   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10878     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10879   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10880     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10881 
10882   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10883     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10884   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10885     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10886   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10887     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10888   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10889     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10890 
10891   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10892     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10893   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10894     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10895   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10896     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10897   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10898     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10899 
10900   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10901     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10902   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10903     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10904   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10905     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10906   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10907     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10908 
10909   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10910     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10911   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10912     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10913   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10914     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10915   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10916     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10917 
10918   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10919     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10920   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10921     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10922   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10923     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10924   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10925     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10926 
10927   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10928     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10929   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10930     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10931   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10932     BB = EmitAtomicBinary(MI, BB, 4, 0);
10933   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10934     BB = EmitAtomicBinary(MI, BB, 8, 0);
10935   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10936            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10937            (Subtarget.hasPartwordAtomics() &&
10938             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10939            (Subtarget.hasPartwordAtomics() &&
10940             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10941     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10942 
10943     auto LoadMnemonic = PPC::LDARX;
10944     auto StoreMnemonic = PPC::STDCX;
10945     switch (MI.getOpcode()) {
10946     default:
10947       llvm_unreachable("Compare and swap of unknown size");
10948     case PPC::ATOMIC_CMP_SWAP_I8:
10949       LoadMnemonic = PPC::LBARX;
10950       StoreMnemonic = PPC::STBCX;
10951       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10952       break;
10953     case PPC::ATOMIC_CMP_SWAP_I16:
10954       LoadMnemonic = PPC::LHARX;
10955       StoreMnemonic = PPC::STHCX;
10956       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10957       break;
10958     case PPC::ATOMIC_CMP_SWAP_I32:
10959       LoadMnemonic = PPC::LWARX;
10960       StoreMnemonic = PPC::STWCX;
10961       break;
10962     case PPC::ATOMIC_CMP_SWAP_I64:
10963       LoadMnemonic = PPC::LDARX;
10964       StoreMnemonic = PPC::STDCX;
10965       break;
10966     }
10967     unsigned dest = MI.getOperand(0).getReg();
10968     unsigned ptrA = MI.getOperand(1).getReg();
10969     unsigned ptrB = MI.getOperand(2).getReg();
10970     unsigned oldval = MI.getOperand(3).getReg();
10971     unsigned newval = MI.getOperand(4).getReg();
10972     DebugLoc dl = MI.getDebugLoc();
10973 
10974     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10975     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10976     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10977     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10978     F->insert(It, loop1MBB);
10979     F->insert(It, loop2MBB);
10980     F->insert(It, midMBB);
10981     F->insert(It, exitMBB);
10982     exitMBB->splice(exitMBB->begin(), BB,
10983                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10984     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10985 
10986     //  thisMBB:
10987     //   ...
10988     //   fallthrough --> loopMBB
10989     BB->addSuccessor(loop1MBB);
10990 
10991     // loop1MBB:
10992     //   l[bhwd]arx dest, ptr
10993     //   cmp[wd] dest, oldval
10994     //   bne- midMBB
10995     // loop2MBB:
10996     //   st[bhwd]cx. newval, ptr
10997     //   bne- loopMBB
10998     //   b exitBB
10999     // midMBB:
11000     //   st[bhwd]cx. dest, ptr
11001     // exitBB:
11002     BB = loop1MBB;
11003     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11004     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11005         .addReg(oldval)
11006         .addReg(dest);
11007     BuildMI(BB, dl, TII->get(PPC::BCC))
11008         .addImm(PPC::PRED_NE)
11009         .addReg(PPC::CR0)
11010         .addMBB(midMBB);
11011     BB->addSuccessor(loop2MBB);
11012     BB->addSuccessor(midMBB);
11013 
11014     BB = loop2MBB;
11015     BuildMI(BB, dl, TII->get(StoreMnemonic))
11016         .addReg(newval)
11017         .addReg(ptrA)
11018         .addReg(ptrB);
11019     BuildMI(BB, dl, TII->get(PPC::BCC))
11020         .addImm(PPC::PRED_NE)
11021         .addReg(PPC::CR0)
11022         .addMBB(loop1MBB);
11023     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11024     BB->addSuccessor(loop1MBB);
11025     BB->addSuccessor(exitMBB);
11026 
11027     BB = midMBB;
11028     BuildMI(BB, dl, TII->get(StoreMnemonic))
11029         .addReg(dest)
11030         .addReg(ptrA)
11031         .addReg(ptrB);
11032     BB->addSuccessor(exitMBB);
11033 
11034     //  exitMBB:
11035     //   ...
11036     BB = exitMBB;
11037   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11038              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11039     // We must use 64-bit registers for addresses when targeting 64-bit,
11040     // since we're actually doing arithmetic on them.  Other registers
11041     // can be 32-bit.
11042     bool is64bit = Subtarget.isPPC64();
11043     bool isLittleEndian = Subtarget.isLittleEndian();
11044     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11045 
11046     unsigned dest = MI.getOperand(0).getReg();
11047     unsigned ptrA = MI.getOperand(1).getReg();
11048     unsigned ptrB = MI.getOperand(2).getReg();
11049     unsigned oldval = MI.getOperand(3).getReg();
11050     unsigned newval = MI.getOperand(4).getReg();
11051     DebugLoc dl = MI.getDebugLoc();
11052 
11053     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11054     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11055     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11056     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11057     F->insert(It, loop1MBB);
11058     F->insert(It, loop2MBB);
11059     F->insert(It, midMBB);
11060     F->insert(It, exitMBB);
11061     exitMBB->splice(exitMBB->begin(), BB,
11062                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11063     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11064 
11065     MachineRegisterInfo &RegInfo = F->getRegInfo();
11066     const TargetRegisterClass *RC =
11067         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11068     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11069 
11070     Register PtrReg = RegInfo.createVirtualRegister(RC);
11071     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11072     Register ShiftReg =
11073         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11074     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11075     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11076     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11077     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11078     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11079     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11080     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11081     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11082     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11083     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11084     Register Ptr1Reg;
11085     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11086     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11087     //  thisMBB:
11088     //   ...
11089     //   fallthrough --> loopMBB
11090     BB->addSuccessor(loop1MBB);
11091 
11092     // The 4-byte load must be aligned, while a char or short may be
11093     // anywhere in the word.  Hence all this nasty bookkeeping code.
11094     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11095     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11096     //   xori shift, shift1, 24 [16]
11097     //   rlwinm ptr, ptr1, 0, 0, 29
11098     //   slw newval2, newval, shift
11099     //   slw oldval2, oldval,shift
11100     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11101     //   slw mask, mask2, shift
11102     //   and newval3, newval2, mask
11103     //   and oldval3, oldval2, mask
11104     // loop1MBB:
11105     //   lwarx tmpDest, ptr
11106     //   and tmp, tmpDest, mask
11107     //   cmpw tmp, oldval3
11108     //   bne- midMBB
11109     // loop2MBB:
11110     //   andc tmp2, tmpDest, mask
11111     //   or tmp4, tmp2, newval3
11112     //   stwcx. tmp4, ptr
11113     //   bne- loop1MBB
11114     //   b exitBB
11115     // midMBB:
11116     //   stwcx. tmpDest, ptr
11117     // exitBB:
11118     //   srw dest, tmpDest, shift
11119     if (ptrA != ZeroReg) {
11120       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11121       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11122           .addReg(ptrA)
11123           .addReg(ptrB);
11124     } else {
11125       Ptr1Reg = ptrB;
11126     }
11127 
11128     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11129     // mode.
11130     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11131         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11132         .addImm(3)
11133         .addImm(27)
11134         .addImm(is8bit ? 28 : 27);
11135     if (!isLittleEndian)
11136       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11137           .addReg(Shift1Reg)
11138           .addImm(is8bit ? 24 : 16);
11139     if (is64bit)
11140       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11141           .addReg(Ptr1Reg)
11142           .addImm(0)
11143           .addImm(61);
11144     else
11145       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11146           .addReg(Ptr1Reg)
11147           .addImm(0)
11148           .addImm(0)
11149           .addImm(29);
11150     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11151         .addReg(newval)
11152         .addReg(ShiftReg);
11153     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11154         .addReg(oldval)
11155         .addReg(ShiftReg);
11156     if (is8bit)
11157       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11158     else {
11159       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11160       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11161           .addReg(Mask3Reg)
11162           .addImm(65535);
11163     }
11164     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11165         .addReg(Mask2Reg)
11166         .addReg(ShiftReg);
11167     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11168         .addReg(NewVal2Reg)
11169         .addReg(MaskReg);
11170     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11171         .addReg(OldVal2Reg)
11172         .addReg(MaskReg);
11173 
11174     BB = loop1MBB;
11175     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11176         .addReg(ZeroReg)
11177         .addReg(PtrReg);
11178     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11179         .addReg(TmpDestReg)
11180         .addReg(MaskReg);
11181     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11182         .addReg(TmpReg)
11183         .addReg(OldVal3Reg);
11184     BuildMI(BB, dl, TII->get(PPC::BCC))
11185         .addImm(PPC::PRED_NE)
11186         .addReg(PPC::CR0)
11187         .addMBB(midMBB);
11188     BB->addSuccessor(loop2MBB);
11189     BB->addSuccessor(midMBB);
11190 
11191     BB = loop2MBB;
11192     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11193         .addReg(TmpDestReg)
11194         .addReg(MaskReg);
11195     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11196         .addReg(Tmp2Reg)
11197         .addReg(NewVal3Reg);
11198     BuildMI(BB, dl, TII->get(PPC::STWCX))
11199         .addReg(Tmp4Reg)
11200         .addReg(ZeroReg)
11201         .addReg(PtrReg);
11202     BuildMI(BB, dl, TII->get(PPC::BCC))
11203         .addImm(PPC::PRED_NE)
11204         .addReg(PPC::CR0)
11205         .addMBB(loop1MBB);
11206     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11207     BB->addSuccessor(loop1MBB);
11208     BB->addSuccessor(exitMBB);
11209 
11210     BB = midMBB;
11211     BuildMI(BB, dl, TII->get(PPC::STWCX))
11212         .addReg(TmpDestReg)
11213         .addReg(ZeroReg)
11214         .addReg(PtrReg);
11215     BB->addSuccessor(exitMBB);
11216 
11217     //  exitMBB:
11218     //   ...
11219     BB = exitMBB;
11220     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11221         .addReg(TmpReg)
11222         .addReg(ShiftReg);
11223   } else if (MI.getOpcode() == PPC::FADDrtz) {
11224     // This pseudo performs an FADD with rounding mode temporarily forced
11225     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11226     // is not modeled at the SelectionDAG level.
11227     unsigned Dest = MI.getOperand(0).getReg();
11228     unsigned Src1 = MI.getOperand(1).getReg();
11229     unsigned Src2 = MI.getOperand(2).getReg();
11230     DebugLoc dl = MI.getDebugLoc();
11231 
11232     MachineRegisterInfo &RegInfo = F->getRegInfo();
11233     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11234 
11235     // Save FPSCR value.
11236     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11237 
11238     // Set rounding mode to round-to-zero.
11239     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11240     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11241 
11242     // Perform addition.
11243     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11244 
11245     // Restore FPSCR value.
11246     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11247   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11248              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
11249              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11250              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
11251     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11252                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
11253                           ? PPC::ANDIo8
11254                           : PPC::ANDIo;
11255     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11256                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
11257 
11258     MachineRegisterInfo &RegInfo = F->getRegInfo();
11259     unsigned Dest = RegInfo.createVirtualRegister(
11260         Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11261 
11262     DebugLoc dl = MI.getDebugLoc();
11263     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
11264         .addReg(MI.getOperand(1).getReg())
11265         .addImm(1);
11266     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
11267             MI.getOperand(0).getReg())
11268         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
11269   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11270     DebugLoc Dl = MI.getDebugLoc();
11271     MachineRegisterInfo &RegInfo = F->getRegInfo();
11272     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11273     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11274     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11275             MI.getOperand(0).getReg())
11276         .addReg(CRReg);
11277   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11278     DebugLoc Dl = MI.getDebugLoc();
11279     unsigned Imm = MI.getOperand(1).getImm();
11280     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11281     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11282             MI.getOperand(0).getReg())
11283         .addReg(PPC::CR0EQ);
11284   } else if (MI.getOpcode() == PPC::SETRNDi) {
11285     DebugLoc dl = MI.getDebugLoc();
11286     unsigned OldFPSCRReg = MI.getOperand(0).getReg();
11287 
11288     // Save FPSCR value.
11289     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11290 
11291     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11292     // the following settings:
11293     //   00 Round to nearest
11294     //   01 Round to 0
11295     //   10 Round to +inf
11296     //   11 Round to -inf
11297 
11298     // When the operand is immediate, using the two least significant bits of
11299     // the immediate to set the bits 62:63 of FPSCR.
11300     unsigned Mode = MI.getOperand(1).getImm();
11301     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11302       .addImm(31);
11303 
11304     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11305       .addImm(30);
11306   } else if (MI.getOpcode() == PPC::SETRND) {
11307     DebugLoc dl = MI.getDebugLoc();
11308 
11309     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11310     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11311     // If the target doesn't have DirectMove, we should use stack to do the
11312     // conversion, because the target doesn't have the instructions like mtvsrd
11313     // or mfvsrd to do this conversion directly.
11314     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11315       if (Subtarget.hasDirectMove()) {
11316         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11317           .addReg(SrcReg);
11318       } else {
11319         // Use stack to do the register copy.
11320         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11321         MachineRegisterInfo &RegInfo = F->getRegInfo();
11322         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11323         if (RC == &PPC::F8RCRegClass) {
11324           // Copy register from F8RCRegClass to G8RCRegclass.
11325           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11326                  "Unsupported RegClass.");
11327 
11328           StoreOp = PPC::STFD;
11329           LoadOp = PPC::LD;
11330         } else {
11331           // Copy register from G8RCRegClass to F8RCRegclass.
11332           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11333                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11334                  "Unsupported RegClass.");
11335         }
11336 
11337         MachineFrameInfo &MFI = F->getFrameInfo();
11338         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11339 
11340         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11341           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11342           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11343           MFI.getObjectAlignment(FrameIdx));
11344 
11345         // Store the SrcReg into the stack.
11346         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11347           .addReg(SrcReg)
11348           .addImm(0)
11349           .addFrameIndex(FrameIdx)
11350           .addMemOperand(MMOStore);
11351 
11352         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11353           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11354           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11355           MFI.getObjectAlignment(FrameIdx));
11356 
11357         // Load from the stack where SrcReg is stored, and save to DestReg,
11358         // so we have done the RegClass conversion from RegClass::SrcReg to
11359         // RegClass::DestReg.
11360         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11361           .addImm(0)
11362           .addFrameIndex(FrameIdx)
11363           .addMemOperand(MMOLoad);
11364       }
11365     };
11366 
11367     unsigned OldFPSCRReg = MI.getOperand(0).getReg();
11368 
11369     // Save FPSCR value.
11370     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11371 
11372     // When the operand is gprc register, use two least significant bits of the
11373     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11374     //
11375     // copy OldFPSCRTmpReg, OldFPSCRReg
11376     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11377     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11378     // copy NewFPSCRReg, NewFPSCRTmpReg
11379     // mtfsf 255, NewFPSCRReg
11380     MachineOperand SrcOp = MI.getOperand(1);
11381     MachineRegisterInfo &RegInfo = F->getRegInfo();
11382     unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11383 
11384     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11385 
11386     unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11387     unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11388 
11389     // The first operand of INSERT_SUBREG should be a register which has
11390     // subregisters, we only care about its RegClass, so we should use an
11391     // IMPLICIT_DEF register.
11392     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11393     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11394       .addReg(ImDefReg)
11395       .add(SrcOp)
11396       .addImm(1);
11397 
11398     unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11399     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11400       .addReg(OldFPSCRTmpReg)
11401       .addReg(ExtSrcReg)
11402       .addImm(0)
11403       .addImm(62);
11404 
11405     unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11406     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11407 
11408     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11409     // bits of FPSCR.
11410     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11411       .addImm(255)
11412       .addReg(NewFPSCRReg)
11413       .addImm(0)
11414       .addImm(0);
11415   } else {
11416     llvm_unreachable("Unexpected instr type to insert");
11417   }
11418 
11419   MI.eraseFromParent(); // The pseudo instruction is gone now.
11420   return BB;
11421 }
11422 
11423 //===----------------------------------------------------------------------===//
11424 // Target Optimization Hooks
11425 //===----------------------------------------------------------------------===//
11426 
11427 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11428   // For the estimates, convergence is quadratic, so we essentially double the
11429   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11430   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11431   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11432   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11433   if (VT.getScalarType() == MVT::f64)
11434     RefinementSteps++;
11435   return RefinementSteps;
11436 }
11437 
11438 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11439                                            int Enabled, int &RefinementSteps,
11440                                            bool &UseOneConstNR,
11441                                            bool Reciprocal) const {
11442   EVT VT = Operand.getValueType();
11443   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11444       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11445       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11446       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11447       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11448       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11449     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11450       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11451 
11452     // The Newton-Raphson computation with a single constant does not provide
11453     // enough accuracy on some CPUs.
11454     UseOneConstNR = !Subtarget.needsTwoConstNR();
11455     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11456   }
11457   return SDValue();
11458 }
11459 
11460 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11461                                             int Enabled,
11462                                             int &RefinementSteps) const {
11463   EVT VT = Operand.getValueType();
11464   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11465       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11466       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11467       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11468       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11469       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11470     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11471       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11472     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11473   }
11474   return SDValue();
11475 }
11476 
11477 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11478   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11479   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11480   // enabled for division), this functionality is redundant with the default
11481   // combiner logic (once the division -> reciprocal/multiply transformation
11482   // has taken place). As a result, this matters more for older cores than for
11483   // newer ones.
11484 
11485   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11486   // reciprocal if there are two or more FDIVs (for embedded cores with only
11487   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11488   switch (Subtarget.getDarwinDirective()) {
11489   default:
11490     return 3;
11491   case PPC::DIR_440:
11492   case PPC::DIR_A2:
11493   case PPC::DIR_E500:
11494   case PPC::DIR_E500mc:
11495   case PPC::DIR_E5500:
11496     return 2;
11497   }
11498 }
11499 
11500 // isConsecutiveLSLoc needs to work even if all adds have not yet been
11501 // collapsed, and so we need to look through chains of them.
11502 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11503                                      int64_t& Offset, SelectionDAG &DAG) {
11504   if (DAG.isBaseWithConstantOffset(Loc)) {
11505     Base = Loc.getOperand(0);
11506     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11507 
11508     // The base might itself be a base plus an offset, and if so, accumulate
11509     // that as well.
11510     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11511   }
11512 }
11513 
11514 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11515                             unsigned Bytes, int Dist,
11516                             SelectionDAG &DAG) {
11517   if (VT.getSizeInBits() / 8 != Bytes)
11518     return false;
11519 
11520   SDValue BaseLoc = Base->getBasePtr();
11521   if (Loc.getOpcode() == ISD::FrameIndex) {
11522     if (BaseLoc.getOpcode() != ISD::FrameIndex)
11523       return false;
11524     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11525     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
11526     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11527     int FS  = MFI.getObjectSize(FI);
11528     int BFS = MFI.getObjectSize(BFI);
11529     if (FS != BFS || FS != (int)Bytes) return false;
11530     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11531   }
11532 
11533   SDValue Base1 = Loc, Base2 = BaseLoc;
11534   int64_t Offset1 = 0, Offset2 = 0;
11535   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
11536   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
11537   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
11538     return true;
11539 
11540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11541   const GlobalValue *GV1 = nullptr;
11542   const GlobalValue *GV2 = nullptr;
11543   Offset1 = 0;
11544   Offset2 = 0;
11545   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
11546   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
11547   if (isGA1 && isGA2 && GV1 == GV2)
11548     return Offset1 == (Offset2 + Dist*Bytes);
11549   return false;
11550 }
11551 
11552 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
11553 // not enforce equality of the chain operands.
11554 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
11555                             unsigned Bytes, int Dist,
11556                             SelectionDAG &DAG) {
11557   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
11558     EVT VT = LS->getMemoryVT();
11559     SDValue Loc = LS->getBasePtr();
11560     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
11561   }
11562 
11563   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
11564     EVT VT;
11565     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11566     default: return false;
11567     case Intrinsic::ppc_qpx_qvlfd:
11568     case Intrinsic::ppc_qpx_qvlfda:
11569       VT = MVT::v4f64;
11570       break;
11571     case Intrinsic::ppc_qpx_qvlfs:
11572     case Intrinsic::ppc_qpx_qvlfsa:
11573       VT = MVT::v4f32;
11574       break;
11575     case Intrinsic::ppc_qpx_qvlfcd:
11576     case Intrinsic::ppc_qpx_qvlfcda:
11577       VT = MVT::v2f64;
11578       break;
11579     case Intrinsic::ppc_qpx_qvlfcs:
11580     case Intrinsic::ppc_qpx_qvlfcsa:
11581       VT = MVT::v2f32;
11582       break;
11583     case Intrinsic::ppc_qpx_qvlfiwa:
11584     case Intrinsic::ppc_qpx_qvlfiwz:
11585     case Intrinsic::ppc_altivec_lvx:
11586     case Intrinsic::ppc_altivec_lvxl:
11587     case Intrinsic::ppc_vsx_lxvw4x:
11588     case Intrinsic::ppc_vsx_lxvw4x_be:
11589       VT = MVT::v4i32;
11590       break;
11591     case Intrinsic::ppc_vsx_lxvd2x:
11592     case Intrinsic::ppc_vsx_lxvd2x_be:
11593       VT = MVT::v2f64;
11594       break;
11595     case Intrinsic::ppc_altivec_lvebx:
11596       VT = MVT::i8;
11597       break;
11598     case Intrinsic::ppc_altivec_lvehx:
11599       VT = MVT::i16;
11600       break;
11601     case Intrinsic::ppc_altivec_lvewx:
11602       VT = MVT::i32;
11603       break;
11604     }
11605 
11606     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
11607   }
11608 
11609   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
11610     EVT VT;
11611     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11612     default: return false;
11613     case Intrinsic::ppc_qpx_qvstfd:
11614     case Intrinsic::ppc_qpx_qvstfda:
11615       VT = MVT::v4f64;
11616       break;
11617     case Intrinsic::ppc_qpx_qvstfs:
11618     case Intrinsic::ppc_qpx_qvstfsa:
11619       VT = MVT::v4f32;
11620       break;
11621     case Intrinsic::ppc_qpx_qvstfcd:
11622     case Intrinsic::ppc_qpx_qvstfcda:
11623       VT = MVT::v2f64;
11624       break;
11625     case Intrinsic::ppc_qpx_qvstfcs:
11626     case Intrinsic::ppc_qpx_qvstfcsa:
11627       VT = MVT::v2f32;
11628       break;
11629     case Intrinsic::ppc_qpx_qvstfiw:
11630     case Intrinsic::ppc_qpx_qvstfiwa:
11631     case Intrinsic::ppc_altivec_stvx:
11632     case Intrinsic::ppc_altivec_stvxl:
11633     case Intrinsic::ppc_vsx_stxvw4x:
11634       VT = MVT::v4i32;
11635       break;
11636     case Intrinsic::ppc_vsx_stxvd2x:
11637       VT = MVT::v2f64;
11638       break;
11639     case Intrinsic::ppc_vsx_stxvw4x_be:
11640       VT = MVT::v4i32;
11641       break;
11642     case Intrinsic::ppc_vsx_stxvd2x_be:
11643       VT = MVT::v2f64;
11644       break;
11645     case Intrinsic::ppc_altivec_stvebx:
11646       VT = MVT::i8;
11647       break;
11648     case Intrinsic::ppc_altivec_stvehx:
11649       VT = MVT::i16;
11650       break;
11651     case Intrinsic::ppc_altivec_stvewx:
11652       VT = MVT::i32;
11653       break;
11654     }
11655 
11656     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
11657   }
11658 
11659   return false;
11660 }
11661 
11662 // Return true is there is a nearyby consecutive load to the one provided
11663 // (regardless of alignment). We search up and down the chain, looking though
11664 // token factors and other loads (but nothing else). As a result, a true result
11665 // indicates that it is safe to create a new consecutive load adjacent to the
11666 // load provided.
11667 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
11668   SDValue Chain = LD->getChain();
11669   EVT VT = LD->getMemoryVT();
11670 
11671   SmallSet<SDNode *, 16> LoadRoots;
11672   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
11673   SmallSet<SDNode *, 16> Visited;
11674 
11675   // First, search up the chain, branching to follow all token-factor operands.
11676   // If we find a consecutive load, then we're done, otherwise, record all
11677   // nodes just above the top-level loads and token factors.
11678   while (!Queue.empty()) {
11679     SDNode *ChainNext = Queue.pop_back_val();
11680     if (!Visited.insert(ChainNext).second)
11681       continue;
11682 
11683     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
11684       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11685         return true;
11686 
11687       if (!Visited.count(ChainLD->getChain().getNode()))
11688         Queue.push_back(ChainLD->getChain().getNode());
11689     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
11690       for (const SDUse &O : ChainNext->ops())
11691         if (!Visited.count(O.getNode()))
11692           Queue.push_back(O.getNode());
11693     } else
11694       LoadRoots.insert(ChainNext);
11695   }
11696 
11697   // Second, search down the chain, starting from the top-level nodes recorded
11698   // in the first phase. These top-level nodes are the nodes just above all
11699   // loads and token factors. Starting with their uses, recursively look though
11700   // all loads (just the chain uses) and token factors to find a consecutive
11701   // load.
11702   Visited.clear();
11703   Queue.clear();
11704 
11705   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
11706        IE = LoadRoots.end(); I != IE; ++I) {
11707     Queue.push_back(*I);
11708 
11709     while (!Queue.empty()) {
11710       SDNode *LoadRoot = Queue.pop_back_val();
11711       if (!Visited.insert(LoadRoot).second)
11712         continue;
11713 
11714       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
11715         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11716           return true;
11717 
11718       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
11719            UE = LoadRoot->use_end(); UI != UE; ++UI)
11720         if (((isa<MemSDNode>(*UI) &&
11721             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
11722             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
11723           Queue.push_back(*UI);
11724     }
11725   }
11726 
11727   return false;
11728 }
11729 
11730 /// This function is called when we have proved that a SETCC node can be replaced
11731 /// by subtraction (and other supporting instructions) so that the result of
11732 /// comparison is kept in a GPR instead of CR. This function is purely for
11733 /// codegen purposes and has some flags to guide the codegen process.
11734 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
11735                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
11736   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11737 
11738   // Zero extend the operands to the largest legal integer. Originally, they
11739   // must be of a strictly smaller size.
11740   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
11741                          DAG.getConstant(Size, DL, MVT::i32));
11742   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
11743                          DAG.getConstant(Size, DL, MVT::i32));
11744 
11745   // Swap if needed. Depends on the condition code.
11746   if (Swap)
11747     std::swap(Op0, Op1);
11748 
11749   // Subtract extended integers.
11750   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
11751 
11752   // Move the sign bit to the least significant position and zero out the rest.
11753   // Now the least significant bit carries the result of original comparison.
11754   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
11755                              DAG.getConstant(Size - 1, DL, MVT::i32));
11756   auto Final = Shifted;
11757 
11758   // Complement the result if needed. Based on the condition code.
11759   if (Complement)
11760     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
11761                         DAG.getConstant(1, DL, MVT::i64));
11762 
11763   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
11764 }
11765 
11766 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
11767                                                   DAGCombinerInfo &DCI) const {
11768   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11769 
11770   SelectionDAG &DAG = DCI.DAG;
11771   SDLoc DL(N);
11772 
11773   // Size of integers being compared has a critical role in the following
11774   // analysis, so we prefer to do this when all types are legal.
11775   if (!DCI.isAfterLegalizeDAG())
11776     return SDValue();
11777 
11778   // If all users of SETCC extend its value to a legal integer type
11779   // then we replace SETCC with a subtraction
11780   for (SDNode::use_iterator UI = N->use_begin(),
11781        UE = N->use_end(); UI != UE; ++UI) {
11782     if (UI->getOpcode() != ISD::ZERO_EXTEND)
11783       return SDValue();
11784   }
11785 
11786   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11787   auto OpSize = N->getOperand(0).getValueSizeInBits();
11788 
11789   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
11790 
11791   if (OpSize < Size) {
11792     switch (CC) {
11793     default: break;
11794     case ISD::SETULT:
11795       return generateEquivalentSub(N, Size, false, false, DL, DAG);
11796     case ISD::SETULE:
11797       return generateEquivalentSub(N, Size, true, true, DL, DAG);
11798     case ISD::SETUGT:
11799       return generateEquivalentSub(N, Size, false, true, DL, DAG);
11800     case ISD::SETUGE:
11801       return generateEquivalentSub(N, Size, true, false, DL, DAG);
11802     }
11803   }
11804 
11805   return SDValue();
11806 }
11807 
11808 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
11809                                                   DAGCombinerInfo &DCI) const {
11810   SelectionDAG &DAG = DCI.DAG;
11811   SDLoc dl(N);
11812 
11813   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
11814   // If we're tracking CR bits, we need to be careful that we don't have:
11815   //   trunc(binary-ops(zext(x), zext(y)))
11816   // or
11817   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
11818   // such that we're unnecessarily moving things into GPRs when it would be
11819   // better to keep them in CR bits.
11820 
11821   // Note that trunc here can be an actual i1 trunc, or can be the effective
11822   // truncation that comes from a setcc or select_cc.
11823   if (N->getOpcode() == ISD::TRUNCATE &&
11824       N->getValueType(0) != MVT::i1)
11825     return SDValue();
11826 
11827   if (N->getOperand(0).getValueType() != MVT::i32 &&
11828       N->getOperand(0).getValueType() != MVT::i64)
11829     return SDValue();
11830 
11831   if (N->getOpcode() == ISD::SETCC ||
11832       N->getOpcode() == ISD::SELECT_CC) {
11833     // If we're looking at a comparison, then we need to make sure that the
11834     // high bits (all except for the first) don't matter the result.
11835     ISD::CondCode CC =
11836       cast<CondCodeSDNode>(N->getOperand(
11837         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
11838     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
11839 
11840     if (ISD::isSignedIntSetCC(CC)) {
11841       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
11842           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
11843         return SDValue();
11844     } else if (ISD::isUnsignedIntSetCC(CC)) {
11845       if (!DAG.MaskedValueIsZero(N->getOperand(0),
11846                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
11847           !DAG.MaskedValueIsZero(N->getOperand(1),
11848                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
11849         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
11850                                              : SDValue());
11851     } else {
11852       // This is neither a signed nor an unsigned comparison, just make sure
11853       // that the high bits are equal.
11854       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
11855       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
11856 
11857       // We don't really care about what is known about the first bit (if
11858       // anything), so clear it in all masks prior to comparing them.
11859       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
11860       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
11861 
11862       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
11863         return SDValue();
11864     }
11865   }
11866 
11867   // We now know that the higher-order bits are irrelevant, we just need to
11868   // make sure that all of the intermediate operations are bit operations, and
11869   // all inputs are extensions.
11870   if (N->getOperand(0).getOpcode() != ISD::AND &&
11871       N->getOperand(0).getOpcode() != ISD::OR  &&
11872       N->getOperand(0).getOpcode() != ISD::XOR &&
11873       N->getOperand(0).getOpcode() != ISD::SELECT &&
11874       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
11875       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
11876       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
11877       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
11878       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
11879     return SDValue();
11880 
11881   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
11882       N->getOperand(1).getOpcode() != ISD::AND &&
11883       N->getOperand(1).getOpcode() != ISD::OR  &&
11884       N->getOperand(1).getOpcode() != ISD::XOR &&
11885       N->getOperand(1).getOpcode() != ISD::SELECT &&
11886       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
11887       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
11888       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
11889       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
11890       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
11891     return SDValue();
11892 
11893   SmallVector<SDValue, 4> Inputs;
11894   SmallVector<SDValue, 8> BinOps, PromOps;
11895   SmallPtrSet<SDNode *, 16> Visited;
11896 
11897   for (unsigned i = 0; i < 2; ++i) {
11898     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11899           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11900           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11901           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11902         isa<ConstantSDNode>(N->getOperand(i)))
11903       Inputs.push_back(N->getOperand(i));
11904     else
11905       BinOps.push_back(N->getOperand(i));
11906 
11907     if (N->getOpcode() == ISD::TRUNCATE)
11908       break;
11909   }
11910 
11911   // Visit all inputs, collect all binary operations (and, or, xor and
11912   // select) that are all fed by extensions.
11913   while (!BinOps.empty()) {
11914     SDValue BinOp = BinOps.back();
11915     BinOps.pop_back();
11916 
11917     if (!Visited.insert(BinOp.getNode()).second)
11918       continue;
11919 
11920     PromOps.push_back(BinOp);
11921 
11922     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11923       // The condition of the select is not promoted.
11924       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11925         continue;
11926       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11927         continue;
11928 
11929       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11930             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11931             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11932            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11933           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11934         Inputs.push_back(BinOp.getOperand(i));
11935       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11936                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11937                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11938                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11939                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11940                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11941                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11942                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11943                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11944         BinOps.push_back(BinOp.getOperand(i));
11945       } else {
11946         // We have an input that is not an extension or another binary
11947         // operation; we'll abort this transformation.
11948         return SDValue();
11949       }
11950     }
11951   }
11952 
11953   // Make sure that this is a self-contained cluster of operations (which
11954   // is not quite the same thing as saying that everything has only one
11955   // use).
11956   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11957     if (isa<ConstantSDNode>(Inputs[i]))
11958       continue;
11959 
11960     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11961                               UE = Inputs[i].getNode()->use_end();
11962          UI != UE; ++UI) {
11963       SDNode *User = *UI;
11964       if (User != N && !Visited.count(User))
11965         return SDValue();
11966 
11967       // Make sure that we're not going to promote the non-output-value
11968       // operand(s) or SELECT or SELECT_CC.
11969       // FIXME: Although we could sometimes handle this, and it does occur in
11970       // practice that one of the condition inputs to the select is also one of
11971       // the outputs, we currently can't deal with this.
11972       if (User->getOpcode() == ISD::SELECT) {
11973         if (User->getOperand(0) == Inputs[i])
11974           return SDValue();
11975       } else if (User->getOpcode() == ISD::SELECT_CC) {
11976         if (User->getOperand(0) == Inputs[i] ||
11977             User->getOperand(1) == Inputs[i])
11978           return SDValue();
11979       }
11980     }
11981   }
11982 
11983   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11984     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11985                               UE = PromOps[i].getNode()->use_end();
11986          UI != UE; ++UI) {
11987       SDNode *User = *UI;
11988       if (User != N && !Visited.count(User))
11989         return SDValue();
11990 
11991       // Make sure that we're not going to promote the non-output-value
11992       // operand(s) or SELECT or SELECT_CC.
11993       // FIXME: Although we could sometimes handle this, and it does occur in
11994       // practice that one of the condition inputs to the select is also one of
11995       // the outputs, we currently can't deal with this.
11996       if (User->getOpcode() == ISD::SELECT) {
11997         if (User->getOperand(0) == PromOps[i])
11998           return SDValue();
11999       } else if (User->getOpcode() == ISD::SELECT_CC) {
12000         if (User->getOperand(0) == PromOps[i] ||
12001             User->getOperand(1) == PromOps[i])
12002           return SDValue();
12003       }
12004     }
12005   }
12006 
12007   // Replace all inputs with the extension operand.
12008   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12009     // Constants may have users outside the cluster of to-be-promoted nodes,
12010     // and so we need to replace those as we do the promotions.
12011     if (isa<ConstantSDNode>(Inputs[i]))
12012       continue;
12013     else
12014       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12015   }
12016 
12017   std::list<HandleSDNode> PromOpHandles;
12018   for (auto &PromOp : PromOps)
12019     PromOpHandles.emplace_back(PromOp);
12020 
12021   // Replace all operations (these are all the same, but have a different
12022   // (i1) return type). DAG.getNode will validate that the types of
12023   // a binary operator match, so go through the list in reverse so that
12024   // we've likely promoted both operands first. Any intermediate truncations or
12025   // extensions disappear.
12026   while (!PromOpHandles.empty()) {
12027     SDValue PromOp = PromOpHandles.back().getValue();
12028     PromOpHandles.pop_back();
12029 
12030     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12031         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12032         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12033         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12034       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12035           PromOp.getOperand(0).getValueType() != MVT::i1) {
12036         // The operand is not yet ready (see comment below).
12037         PromOpHandles.emplace_front(PromOp);
12038         continue;
12039       }
12040 
12041       SDValue RepValue = PromOp.getOperand(0);
12042       if (isa<ConstantSDNode>(RepValue))
12043         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12044 
12045       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12046       continue;
12047     }
12048 
12049     unsigned C;
12050     switch (PromOp.getOpcode()) {
12051     default:             C = 0; break;
12052     case ISD::SELECT:    C = 1; break;
12053     case ISD::SELECT_CC: C = 2; break;
12054     }
12055 
12056     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12057          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12058         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12059          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12060       // The to-be-promoted operands of this node have not yet been
12061       // promoted (this should be rare because we're going through the
12062       // list backward, but if one of the operands has several users in
12063       // this cluster of to-be-promoted nodes, it is possible).
12064       PromOpHandles.emplace_front(PromOp);
12065       continue;
12066     }
12067 
12068     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12069                                 PromOp.getNode()->op_end());
12070 
12071     // If there are any constant inputs, make sure they're replaced now.
12072     for (unsigned i = 0; i < 2; ++i)
12073       if (isa<ConstantSDNode>(Ops[C+i]))
12074         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12075 
12076     DAG.ReplaceAllUsesOfValueWith(PromOp,
12077       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12078   }
12079 
12080   // Now we're left with the initial truncation itself.
12081   if (N->getOpcode() == ISD::TRUNCATE)
12082     return N->getOperand(0);
12083 
12084   // Otherwise, this is a comparison. The operands to be compared have just
12085   // changed type (to i1), but everything else is the same.
12086   return SDValue(N, 0);
12087 }
12088 
12089 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12090                                                   DAGCombinerInfo &DCI) const {
12091   SelectionDAG &DAG = DCI.DAG;
12092   SDLoc dl(N);
12093 
12094   // If we're tracking CR bits, we need to be careful that we don't have:
12095   //   zext(binary-ops(trunc(x), trunc(y)))
12096   // or
12097   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12098   // such that we're unnecessarily moving things into CR bits that can more
12099   // efficiently stay in GPRs. Note that if we're not certain that the high
12100   // bits are set as required by the final extension, we still may need to do
12101   // some masking to get the proper behavior.
12102 
12103   // This same functionality is important on PPC64 when dealing with
12104   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12105   // the return values of functions. Because it is so similar, it is handled
12106   // here as well.
12107 
12108   if (N->getValueType(0) != MVT::i32 &&
12109       N->getValueType(0) != MVT::i64)
12110     return SDValue();
12111 
12112   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12113         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12114     return SDValue();
12115 
12116   if (N->getOperand(0).getOpcode() != ISD::AND &&
12117       N->getOperand(0).getOpcode() != ISD::OR  &&
12118       N->getOperand(0).getOpcode() != ISD::XOR &&
12119       N->getOperand(0).getOpcode() != ISD::SELECT &&
12120       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12121     return SDValue();
12122 
12123   SmallVector<SDValue, 4> Inputs;
12124   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12125   SmallPtrSet<SDNode *, 16> Visited;
12126 
12127   // Visit all inputs, collect all binary operations (and, or, xor and
12128   // select) that are all fed by truncations.
12129   while (!BinOps.empty()) {
12130     SDValue BinOp = BinOps.back();
12131     BinOps.pop_back();
12132 
12133     if (!Visited.insert(BinOp.getNode()).second)
12134       continue;
12135 
12136     PromOps.push_back(BinOp);
12137 
12138     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12139       // The condition of the select is not promoted.
12140       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12141         continue;
12142       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12143         continue;
12144 
12145       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12146           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12147         Inputs.push_back(BinOp.getOperand(i));
12148       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12149                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12150                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12151                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12152                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12153         BinOps.push_back(BinOp.getOperand(i));
12154       } else {
12155         // We have an input that is not a truncation or another binary
12156         // operation; we'll abort this transformation.
12157         return SDValue();
12158       }
12159     }
12160   }
12161 
12162   // The operands of a select that must be truncated when the select is
12163   // promoted because the operand is actually part of the to-be-promoted set.
12164   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12165 
12166   // Make sure that this is a self-contained cluster of operations (which
12167   // is not quite the same thing as saying that everything has only one
12168   // use).
12169   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12170     if (isa<ConstantSDNode>(Inputs[i]))
12171       continue;
12172 
12173     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12174                               UE = Inputs[i].getNode()->use_end();
12175          UI != UE; ++UI) {
12176       SDNode *User = *UI;
12177       if (User != N && !Visited.count(User))
12178         return SDValue();
12179 
12180       // If we're going to promote the non-output-value operand(s) or SELECT or
12181       // SELECT_CC, record them for truncation.
12182       if (User->getOpcode() == ISD::SELECT) {
12183         if (User->getOperand(0) == Inputs[i])
12184           SelectTruncOp[0].insert(std::make_pair(User,
12185                                     User->getOperand(0).getValueType()));
12186       } else if (User->getOpcode() == ISD::SELECT_CC) {
12187         if (User->getOperand(0) == Inputs[i])
12188           SelectTruncOp[0].insert(std::make_pair(User,
12189                                     User->getOperand(0).getValueType()));
12190         if (User->getOperand(1) == Inputs[i])
12191           SelectTruncOp[1].insert(std::make_pair(User,
12192                                     User->getOperand(1).getValueType()));
12193       }
12194     }
12195   }
12196 
12197   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12198     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12199                               UE = PromOps[i].getNode()->use_end();
12200          UI != UE; ++UI) {
12201       SDNode *User = *UI;
12202       if (User != N && !Visited.count(User))
12203         return SDValue();
12204 
12205       // If we're going to promote the non-output-value operand(s) or SELECT or
12206       // SELECT_CC, record them for truncation.
12207       if (User->getOpcode() == ISD::SELECT) {
12208         if (User->getOperand(0) == PromOps[i])
12209           SelectTruncOp[0].insert(std::make_pair(User,
12210                                     User->getOperand(0).getValueType()));
12211       } else if (User->getOpcode() == ISD::SELECT_CC) {
12212         if (User->getOperand(0) == PromOps[i])
12213           SelectTruncOp[0].insert(std::make_pair(User,
12214                                     User->getOperand(0).getValueType()));
12215         if (User->getOperand(1) == PromOps[i])
12216           SelectTruncOp[1].insert(std::make_pair(User,
12217                                     User->getOperand(1).getValueType()));
12218       }
12219     }
12220   }
12221 
12222   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12223   bool ReallyNeedsExt = false;
12224   if (N->getOpcode() != ISD::ANY_EXTEND) {
12225     // If all of the inputs are not already sign/zero extended, then
12226     // we'll still need to do that at the end.
12227     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12228       if (isa<ConstantSDNode>(Inputs[i]))
12229         continue;
12230 
12231       unsigned OpBits =
12232         Inputs[i].getOperand(0).getValueSizeInBits();
12233       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12234 
12235       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12236            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12237                                   APInt::getHighBitsSet(OpBits,
12238                                                         OpBits-PromBits))) ||
12239           (N->getOpcode() == ISD::SIGN_EXTEND &&
12240            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12241              (OpBits-(PromBits-1)))) {
12242         ReallyNeedsExt = true;
12243         break;
12244       }
12245     }
12246   }
12247 
12248   // Replace all inputs, either with the truncation operand, or a
12249   // truncation or extension to the final output type.
12250   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12251     // Constant inputs need to be replaced with the to-be-promoted nodes that
12252     // use them because they might have users outside of the cluster of
12253     // promoted nodes.
12254     if (isa<ConstantSDNode>(Inputs[i]))
12255       continue;
12256 
12257     SDValue InSrc = Inputs[i].getOperand(0);
12258     if (Inputs[i].getValueType() == N->getValueType(0))
12259       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12260     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12261       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12262         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12263     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12264       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12265         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12266     else
12267       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12268         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12269   }
12270 
12271   std::list<HandleSDNode> PromOpHandles;
12272   for (auto &PromOp : PromOps)
12273     PromOpHandles.emplace_back(PromOp);
12274 
12275   // Replace all operations (these are all the same, but have a different
12276   // (promoted) return type). DAG.getNode will validate that the types of
12277   // a binary operator match, so go through the list in reverse so that
12278   // we've likely promoted both operands first.
12279   while (!PromOpHandles.empty()) {
12280     SDValue PromOp = PromOpHandles.back().getValue();
12281     PromOpHandles.pop_back();
12282 
12283     unsigned C;
12284     switch (PromOp.getOpcode()) {
12285     default:             C = 0; break;
12286     case ISD::SELECT:    C = 1; break;
12287     case ISD::SELECT_CC: C = 2; break;
12288     }
12289 
12290     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12291          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12292         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12293          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12294       // The to-be-promoted operands of this node have not yet been
12295       // promoted (this should be rare because we're going through the
12296       // list backward, but if one of the operands has several users in
12297       // this cluster of to-be-promoted nodes, it is possible).
12298       PromOpHandles.emplace_front(PromOp);
12299       continue;
12300     }
12301 
12302     // For SELECT and SELECT_CC nodes, we do a similar check for any
12303     // to-be-promoted comparison inputs.
12304     if (PromOp.getOpcode() == ISD::SELECT ||
12305         PromOp.getOpcode() == ISD::SELECT_CC) {
12306       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12307            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12308           (SelectTruncOp[1].count(PromOp.getNode()) &&
12309            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12310         PromOpHandles.emplace_front(PromOp);
12311         continue;
12312       }
12313     }
12314 
12315     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12316                                 PromOp.getNode()->op_end());
12317 
12318     // If this node has constant inputs, then they'll need to be promoted here.
12319     for (unsigned i = 0; i < 2; ++i) {
12320       if (!isa<ConstantSDNode>(Ops[C+i]))
12321         continue;
12322       if (Ops[C+i].getValueType() == N->getValueType(0))
12323         continue;
12324 
12325       if (N->getOpcode() == ISD::SIGN_EXTEND)
12326         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12327       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12328         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12329       else
12330         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12331     }
12332 
12333     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12334     // truncate them again to the original value type.
12335     if (PromOp.getOpcode() == ISD::SELECT ||
12336         PromOp.getOpcode() == ISD::SELECT_CC) {
12337       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12338       if (SI0 != SelectTruncOp[0].end())
12339         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12340       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12341       if (SI1 != SelectTruncOp[1].end())
12342         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12343     }
12344 
12345     DAG.ReplaceAllUsesOfValueWith(PromOp,
12346       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12347   }
12348 
12349   // Now we're left with the initial extension itself.
12350   if (!ReallyNeedsExt)
12351     return N->getOperand(0);
12352 
12353   // To zero extend, just mask off everything except for the first bit (in the
12354   // i1 case).
12355   if (N->getOpcode() == ISD::ZERO_EXTEND)
12356     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12357                        DAG.getConstant(APInt::getLowBitsSet(
12358                                          N->getValueSizeInBits(0), PromBits),
12359                                        dl, N->getValueType(0)));
12360 
12361   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12362          "Invalid extension type");
12363   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12364   SDValue ShiftCst =
12365       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12366   return DAG.getNode(
12367       ISD::SRA, dl, N->getValueType(0),
12368       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12369       ShiftCst);
12370 }
12371 
12372 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12373                                         DAGCombinerInfo &DCI) const {
12374   assert(N->getOpcode() == ISD::SETCC &&
12375          "Should be called with a SETCC node");
12376 
12377   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12378   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12379     SDValue LHS = N->getOperand(0);
12380     SDValue RHS = N->getOperand(1);
12381 
12382     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12383     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12384         LHS.hasOneUse())
12385       std::swap(LHS, RHS);
12386 
12387     // x == 0-y --> x+y == 0
12388     // x != 0-y --> x+y != 0
12389     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12390         RHS.hasOneUse()) {
12391       SDLoc DL(N);
12392       SelectionDAG &DAG = DCI.DAG;
12393       EVT VT = N->getValueType(0);
12394       EVT OpVT = LHS.getValueType();
12395       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12396       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12397     }
12398   }
12399 
12400   return DAGCombineTruncBoolExt(N, DCI);
12401 }
12402 
12403 // Is this an extending load from an f32 to an f64?
12404 static bool isFPExtLoad(SDValue Op) {
12405   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12406     return LD->getExtensionType() == ISD::EXTLOAD &&
12407       Op.getValueType() == MVT::f64;
12408   return false;
12409 }
12410 
12411 /// Reduces the number of fp-to-int conversion when building a vector.
12412 ///
12413 /// If this vector is built out of floating to integer conversions,
12414 /// transform it to a vector built out of floating point values followed by a
12415 /// single floating to integer conversion of the vector.
12416 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12417 /// becomes (fptosi (build_vector ($A, $B, ...)))
12418 SDValue PPCTargetLowering::
12419 combineElementTruncationToVectorTruncation(SDNode *N,
12420                                            DAGCombinerInfo &DCI) const {
12421   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12422          "Should be called with a BUILD_VECTOR node");
12423 
12424   SelectionDAG &DAG = DCI.DAG;
12425   SDLoc dl(N);
12426 
12427   SDValue FirstInput = N->getOperand(0);
12428   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12429          "The input operand must be an fp-to-int conversion.");
12430 
12431   // This combine happens after legalization so the fp_to_[su]i nodes are
12432   // already converted to PPCSISD nodes.
12433   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12434   if (FirstConversion == PPCISD::FCTIDZ ||
12435       FirstConversion == PPCISD::FCTIDUZ ||
12436       FirstConversion == PPCISD::FCTIWZ ||
12437       FirstConversion == PPCISD::FCTIWUZ) {
12438     bool IsSplat = true;
12439     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12440       FirstConversion == PPCISD::FCTIWUZ;
12441     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12442     SmallVector<SDValue, 4> Ops;
12443     EVT TargetVT = N->getValueType(0);
12444     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12445       SDValue NextOp = N->getOperand(i);
12446       if (NextOp.getOpcode() != PPCISD::MFVSR)
12447         return SDValue();
12448       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12449       if (NextConversion != FirstConversion)
12450         return SDValue();
12451       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12452       // This is not valid if the input was originally double precision. It is
12453       // also not profitable to do unless this is an extending load in which
12454       // case doing this combine will allow us to combine consecutive loads.
12455       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12456         return SDValue();
12457       if (N->getOperand(i) != FirstInput)
12458         IsSplat = false;
12459     }
12460 
12461     // If this is a splat, we leave it as-is since there will be only a single
12462     // fp-to-int conversion followed by a splat of the integer. This is better
12463     // for 32-bit and smaller ints and neutral for 64-bit ints.
12464     if (IsSplat)
12465       return SDValue();
12466 
12467     // Now that we know we have the right type of node, get its operands
12468     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12469       SDValue In = N->getOperand(i).getOperand(0);
12470       if (Is32Bit) {
12471         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12472         // here, we know that all inputs are extending loads so this is safe).
12473         if (In.isUndef())
12474           Ops.push_back(DAG.getUNDEF(SrcVT));
12475         else {
12476           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12477                                       MVT::f32, In.getOperand(0),
12478                                       DAG.getIntPtrConstant(1, dl));
12479           Ops.push_back(Trunc);
12480         }
12481       } else
12482         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12483     }
12484 
12485     unsigned Opcode;
12486     if (FirstConversion == PPCISD::FCTIDZ ||
12487         FirstConversion == PPCISD::FCTIWZ)
12488       Opcode = ISD::FP_TO_SINT;
12489     else
12490       Opcode = ISD::FP_TO_UINT;
12491 
12492     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12493     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12494     return DAG.getNode(Opcode, dl, TargetVT, BV);
12495   }
12496   return SDValue();
12497 }
12498 
12499 /// Reduce the number of loads when building a vector.
12500 ///
12501 /// Building a vector out of multiple loads can be converted to a load
12502 /// of the vector type if the loads are consecutive. If the loads are
12503 /// consecutive but in descending order, a shuffle is added at the end
12504 /// to reorder the vector.
12505 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12506   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12507          "Should be called with a BUILD_VECTOR node");
12508 
12509   SDLoc dl(N);
12510 
12511   // Return early for non byte-sized type, as they can't be consecutive.
12512   if (!N->getValueType(0).getVectorElementType().isByteSized())
12513     return SDValue();
12514 
12515   bool InputsAreConsecutiveLoads = true;
12516   bool InputsAreReverseConsecutive = true;
12517   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12518   SDValue FirstInput = N->getOperand(0);
12519   bool IsRoundOfExtLoad = false;
12520 
12521   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12522       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12523     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12524     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12525   }
12526   // Not a build vector of (possibly fp_rounded) loads.
12527   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12528       N->getNumOperands() == 1)
12529     return SDValue();
12530 
12531   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12532     // If any inputs are fp_round(extload), they all must be.
12533     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12534       return SDValue();
12535 
12536     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
12537       N->getOperand(i);
12538     if (NextInput.getOpcode() != ISD::LOAD)
12539       return SDValue();
12540 
12541     SDValue PreviousInput =
12542       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
12543     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
12544     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
12545 
12546     // If any inputs are fp_round(extload), they all must be.
12547     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
12548       return SDValue();
12549 
12550     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
12551       InputsAreConsecutiveLoads = false;
12552     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
12553       InputsAreReverseConsecutive = false;
12554 
12555     // Exit early if the loads are neither consecutive nor reverse consecutive.
12556     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
12557       return SDValue();
12558   }
12559 
12560   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
12561          "The loads cannot be both consecutive and reverse consecutive.");
12562 
12563   SDValue FirstLoadOp =
12564     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
12565   SDValue LastLoadOp =
12566     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
12567                        N->getOperand(N->getNumOperands()-1);
12568 
12569   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
12570   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
12571   if (InputsAreConsecutiveLoads) {
12572     assert(LD1 && "Input needs to be a LoadSDNode.");
12573     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
12574                        LD1->getBasePtr(), LD1->getPointerInfo(),
12575                        LD1->getAlignment());
12576   }
12577   if (InputsAreReverseConsecutive) {
12578     assert(LDL && "Input needs to be a LoadSDNode.");
12579     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
12580                                LDL->getBasePtr(), LDL->getPointerInfo(),
12581                                LDL->getAlignment());
12582     SmallVector<int, 16> Ops;
12583     for (int i = N->getNumOperands() - 1; i >= 0; i--)
12584       Ops.push_back(i);
12585 
12586     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
12587                                 DAG.getUNDEF(N->getValueType(0)), Ops);
12588   }
12589   return SDValue();
12590 }
12591 
12592 // This function adds the required vector_shuffle needed to get
12593 // the elements of the vector extract in the correct position
12594 // as specified by the CorrectElems encoding.
12595 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
12596                                       SDValue Input, uint64_t Elems,
12597                                       uint64_t CorrectElems) {
12598   SDLoc dl(N);
12599 
12600   unsigned NumElems = Input.getValueType().getVectorNumElements();
12601   SmallVector<int, 16> ShuffleMask(NumElems, -1);
12602 
12603   // Knowing the element indices being extracted from the original
12604   // vector and the order in which they're being inserted, just put
12605   // them at element indices required for the instruction.
12606   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12607     if (DAG.getDataLayout().isLittleEndian())
12608       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
12609     else
12610       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
12611     CorrectElems = CorrectElems >> 8;
12612     Elems = Elems >> 8;
12613   }
12614 
12615   SDValue Shuffle =
12616       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
12617                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
12618 
12619   EVT Ty = N->getValueType(0);
12620   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
12621   return BV;
12622 }
12623 
12624 // Look for build vector patterns where input operands come from sign
12625 // extended vector_extract elements of specific indices. If the correct indices
12626 // aren't used, add a vector shuffle to fix up the indices and create a new
12627 // PPCISD:SExtVElems node which selects the vector sign extend instructions
12628 // during instruction selection.
12629 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
12630   // This array encodes the indices that the vector sign extend instructions
12631   // extract from when extending from one type to another for both BE and LE.
12632   // The right nibble of each byte corresponds to the LE incides.
12633   // and the left nibble of each byte corresponds to the BE incides.
12634   // For example: 0x3074B8FC  byte->word
12635   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
12636   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
12637   // For example: 0x000070F8  byte->double word
12638   // For LE: the allowed indices are: 0x0,0x8
12639   // For BE: the allowed indices are: 0x7,0xF
12640   uint64_t TargetElems[] = {
12641       0x3074B8FC, // b->w
12642       0x000070F8, // b->d
12643       0x10325476, // h->w
12644       0x00003074, // h->d
12645       0x00001032, // w->d
12646   };
12647 
12648   uint64_t Elems = 0;
12649   int Index;
12650   SDValue Input;
12651 
12652   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
12653     if (!Op)
12654       return false;
12655     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
12656         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
12657       return false;
12658 
12659     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
12660     // of the right width.
12661     SDValue Extract = Op.getOperand(0);
12662     if (Extract.getOpcode() == ISD::ANY_EXTEND)
12663       Extract = Extract.getOperand(0);
12664     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12665       return false;
12666 
12667     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
12668     if (!ExtOp)
12669       return false;
12670 
12671     Index = ExtOp->getZExtValue();
12672     if (Input && Input != Extract.getOperand(0))
12673       return false;
12674 
12675     if (!Input)
12676       Input = Extract.getOperand(0);
12677 
12678     Elems = Elems << 8;
12679     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
12680     Elems |= Index;
12681 
12682     return true;
12683   };
12684 
12685   // If the build vector operands aren't sign extended vector extracts,
12686   // of the same input vector, then return.
12687   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12688     if (!isSExtOfVecExtract(N->getOperand(i))) {
12689       return SDValue();
12690     }
12691   }
12692 
12693   // If the vector extract indicies are not correct, add the appropriate
12694   // vector_shuffle.
12695   int TgtElemArrayIdx;
12696   int InputSize = Input.getValueType().getScalarSizeInBits();
12697   int OutputSize = N->getValueType(0).getScalarSizeInBits();
12698   if (InputSize + OutputSize == 40)
12699     TgtElemArrayIdx = 0;
12700   else if (InputSize + OutputSize == 72)
12701     TgtElemArrayIdx = 1;
12702   else if (InputSize + OutputSize == 48)
12703     TgtElemArrayIdx = 2;
12704   else if (InputSize + OutputSize == 80)
12705     TgtElemArrayIdx = 3;
12706   else if (InputSize + OutputSize == 96)
12707     TgtElemArrayIdx = 4;
12708   else
12709     return SDValue();
12710 
12711   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
12712   CorrectElems = DAG.getDataLayout().isLittleEndian()
12713                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
12714                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
12715   if (Elems != CorrectElems) {
12716     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
12717   }
12718 
12719   // Regular lowering will catch cases where a shuffle is not needed.
12720   return SDValue();
12721 }
12722 
12723 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
12724                                                  DAGCombinerInfo &DCI) const {
12725   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12726          "Should be called with a BUILD_VECTOR node");
12727 
12728   SelectionDAG &DAG = DCI.DAG;
12729   SDLoc dl(N);
12730 
12731   if (!Subtarget.hasVSX())
12732     return SDValue();
12733 
12734   // The target independent DAG combiner will leave a build_vector of
12735   // float-to-int conversions intact. We can generate MUCH better code for
12736   // a float-to-int conversion of a vector of floats.
12737   SDValue FirstInput = N->getOperand(0);
12738   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
12739     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
12740     if (Reduced)
12741       return Reduced;
12742   }
12743 
12744   // If we're building a vector out of consecutive loads, just load that
12745   // vector type.
12746   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
12747   if (Reduced)
12748     return Reduced;
12749 
12750   // If we're building a vector out of extended elements from another vector
12751   // we have P9 vector integer extend instructions. The code assumes legal
12752   // input types (i.e. it can't handle things like v4i16) so do not run before
12753   // legalization.
12754   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
12755     Reduced = combineBVOfVecSExt(N, DAG);
12756     if (Reduced)
12757       return Reduced;
12758   }
12759 
12760 
12761   if (N->getValueType(0) != MVT::v2f64)
12762     return SDValue();
12763 
12764   // Looking for:
12765   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
12766   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
12767       FirstInput.getOpcode() != ISD::UINT_TO_FP)
12768     return SDValue();
12769   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
12770       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
12771     return SDValue();
12772   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
12773     return SDValue();
12774 
12775   SDValue Ext1 = FirstInput.getOperand(0);
12776   SDValue Ext2 = N->getOperand(1).getOperand(0);
12777   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12778      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12779     return SDValue();
12780 
12781   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
12782   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
12783   if (!Ext1Op || !Ext2Op)
12784     return SDValue();
12785   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
12786       Ext1.getOperand(0) != Ext2.getOperand(0))
12787     return SDValue();
12788 
12789   int FirstElem = Ext1Op->getZExtValue();
12790   int SecondElem = Ext2Op->getZExtValue();
12791   int SubvecIdx;
12792   if (FirstElem == 0 && SecondElem == 1)
12793     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
12794   else if (FirstElem == 2 && SecondElem == 3)
12795     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
12796   else
12797     return SDValue();
12798 
12799   SDValue SrcVec = Ext1.getOperand(0);
12800   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
12801     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
12802   return DAG.getNode(NodeType, dl, MVT::v2f64,
12803                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
12804 }
12805 
12806 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
12807                                               DAGCombinerInfo &DCI) const {
12808   assert((N->getOpcode() == ISD::SINT_TO_FP ||
12809           N->getOpcode() == ISD::UINT_TO_FP) &&
12810          "Need an int -> FP conversion node here");
12811 
12812   if (useSoftFloat() || !Subtarget.has64BitSupport())
12813     return SDValue();
12814 
12815   SelectionDAG &DAG = DCI.DAG;
12816   SDLoc dl(N);
12817   SDValue Op(N, 0);
12818 
12819   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
12820   // from the hardware.
12821   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
12822     return SDValue();
12823   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
12824       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
12825     return SDValue();
12826 
12827   SDValue FirstOperand(Op.getOperand(0));
12828   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
12829     (FirstOperand.getValueType() == MVT::i8 ||
12830      FirstOperand.getValueType() == MVT::i16);
12831   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
12832     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
12833     bool DstDouble = Op.getValueType() == MVT::f64;
12834     unsigned ConvOp = Signed ?
12835       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
12836       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
12837     SDValue WidthConst =
12838       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
12839                             dl, false);
12840     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
12841     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
12842     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
12843                                          DAG.getVTList(MVT::f64, MVT::Other),
12844                                          Ops, MVT::i8, LDN->getMemOperand());
12845 
12846     // For signed conversion, we need to sign-extend the value in the VSR
12847     if (Signed) {
12848       SDValue ExtOps[] = { Ld, WidthConst };
12849       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
12850       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
12851     } else
12852       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
12853   }
12854 
12855 
12856   // For i32 intermediate values, unfortunately, the conversion functions
12857   // leave the upper 32 bits of the value are undefined. Within the set of
12858   // scalar instructions, we have no method for zero- or sign-extending the
12859   // value. Thus, we cannot handle i32 intermediate values here.
12860   if (Op.getOperand(0).getValueType() == MVT::i32)
12861     return SDValue();
12862 
12863   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
12864          "UINT_TO_FP is supported only with FPCVT");
12865 
12866   // If we have FCFIDS, then use it when converting to single-precision.
12867   // Otherwise, convert to double-precision and then round.
12868   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12869                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
12870                                                             : PPCISD::FCFIDS)
12871                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
12872                                                             : PPCISD::FCFID);
12873   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12874                   ? MVT::f32
12875                   : MVT::f64;
12876 
12877   // If we're converting from a float, to an int, and back to a float again,
12878   // then we don't need the store/load pair at all.
12879   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
12880        Subtarget.hasFPCVT()) ||
12881       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
12882     SDValue Src = Op.getOperand(0).getOperand(0);
12883     if (Src.getValueType() == MVT::f32) {
12884       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
12885       DCI.AddToWorklist(Src.getNode());
12886     } else if (Src.getValueType() != MVT::f64) {
12887       // Make sure that we don't pick up a ppc_fp128 source value.
12888       return SDValue();
12889     }
12890 
12891     unsigned FCTOp =
12892       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
12893                                                         PPCISD::FCTIDUZ;
12894 
12895     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
12896     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
12897 
12898     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
12899       FP = DAG.getNode(ISD::FP_ROUND, dl,
12900                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
12901       DCI.AddToWorklist(FP.getNode());
12902     }
12903 
12904     return FP;
12905   }
12906 
12907   return SDValue();
12908 }
12909 
12910 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
12911 // builtins) into loads with swaps.
12912 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
12913                                               DAGCombinerInfo &DCI) const {
12914   SelectionDAG &DAG = DCI.DAG;
12915   SDLoc dl(N);
12916   SDValue Chain;
12917   SDValue Base;
12918   MachineMemOperand *MMO;
12919 
12920   switch (N->getOpcode()) {
12921   default:
12922     llvm_unreachable("Unexpected opcode for little endian VSX load");
12923   case ISD::LOAD: {
12924     LoadSDNode *LD = cast<LoadSDNode>(N);
12925     Chain = LD->getChain();
12926     Base = LD->getBasePtr();
12927     MMO = LD->getMemOperand();
12928     // If the MMO suggests this isn't a load of a full vector, leave
12929     // things alone.  For a built-in, we have to make the change for
12930     // correctness, so if there is a size problem that will be a bug.
12931     if (MMO->getSize() < 16)
12932       return SDValue();
12933     break;
12934   }
12935   case ISD::INTRINSIC_W_CHAIN: {
12936     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12937     Chain = Intrin->getChain();
12938     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
12939     // us what we want. Get operand 2 instead.
12940     Base = Intrin->getOperand(2);
12941     MMO = Intrin->getMemOperand();
12942     break;
12943   }
12944   }
12945 
12946   MVT VecTy = N->getValueType(0).getSimpleVT();
12947 
12948   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
12949   // aligned and the type is a vector with elements up to 4 bytes
12950   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12951       && VecTy.getScalarSizeInBits() <= 32 ) {
12952     return SDValue();
12953   }
12954 
12955   SDValue LoadOps[] = { Chain, Base };
12956   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
12957                                          DAG.getVTList(MVT::v2f64, MVT::Other),
12958                                          LoadOps, MVT::v2f64, MMO);
12959 
12960   DCI.AddToWorklist(Load.getNode());
12961   Chain = Load.getValue(1);
12962   SDValue Swap = DAG.getNode(
12963       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
12964   DCI.AddToWorklist(Swap.getNode());
12965 
12966   // Add a bitcast if the resulting load type doesn't match v2f64.
12967   if (VecTy != MVT::v2f64) {
12968     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12969     DCI.AddToWorklist(N.getNode());
12970     // Package {bitcast value, swap's chain} to match Load's shape.
12971     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12972                        N, Swap.getValue(1));
12973   }
12974 
12975   return Swap;
12976 }
12977 
12978 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12979 // builtins) into stores with swaps.
12980 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
12981                                                DAGCombinerInfo &DCI) const {
12982   SelectionDAG &DAG = DCI.DAG;
12983   SDLoc dl(N);
12984   SDValue Chain;
12985   SDValue Base;
12986   unsigned SrcOpnd;
12987   MachineMemOperand *MMO;
12988 
12989   switch (N->getOpcode()) {
12990   default:
12991     llvm_unreachable("Unexpected opcode for little endian VSX store");
12992   case ISD::STORE: {
12993     StoreSDNode *ST = cast<StoreSDNode>(N);
12994     Chain = ST->getChain();
12995     Base = ST->getBasePtr();
12996     MMO = ST->getMemOperand();
12997     SrcOpnd = 1;
12998     // If the MMO suggests this isn't a store of a full vector, leave
12999     // things alone.  For a built-in, we have to make the change for
13000     // correctness, so if there is a size problem that will be a bug.
13001     if (MMO->getSize() < 16)
13002       return SDValue();
13003     break;
13004   }
13005   case ISD::INTRINSIC_VOID: {
13006     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13007     Chain = Intrin->getChain();
13008     // Intrin->getBasePtr() oddly does not get what we want.
13009     Base = Intrin->getOperand(3);
13010     MMO = Intrin->getMemOperand();
13011     SrcOpnd = 2;
13012     break;
13013   }
13014   }
13015 
13016   SDValue Src = N->getOperand(SrcOpnd);
13017   MVT VecTy = Src.getValueType().getSimpleVT();
13018 
13019   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13020   // aligned and the type is a vector with elements up to 4 bytes
13021   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13022       && VecTy.getScalarSizeInBits() <= 32 ) {
13023     return SDValue();
13024   }
13025 
13026   // All stores are done as v2f64 and possible bit cast.
13027   if (VecTy != MVT::v2f64) {
13028     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13029     DCI.AddToWorklist(Src.getNode());
13030   }
13031 
13032   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13033                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13034   DCI.AddToWorklist(Swap.getNode());
13035   Chain = Swap.getValue(1);
13036   SDValue StoreOps[] = { Chain, Swap, Base };
13037   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13038                                           DAG.getVTList(MVT::Other),
13039                                           StoreOps, VecTy, MMO);
13040   DCI.AddToWorklist(Store.getNode());
13041   return Store;
13042 }
13043 
13044 // Handle DAG combine for STORE (FP_TO_INT F).
13045 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13046                                                DAGCombinerInfo &DCI) const {
13047 
13048   SelectionDAG &DAG = DCI.DAG;
13049   SDLoc dl(N);
13050   unsigned Opcode = N->getOperand(1).getOpcode();
13051 
13052   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13053          && "Not a FP_TO_INT Instruction!");
13054 
13055   SDValue Val = N->getOperand(1).getOperand(0);
13056   EVT Op1VT = N->getOperand(1).getValueType();
13057   EVT ResVT = Val.getValueType();
13058 
13059   // Floating point types smaller than 32 bits are not legal on Power.
13060   if (ResVT.getScalarSizeInBits() < 32)
13061     return SDValue();
13062 
13063   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13064   bool ValidTypeForStoreFltAsInt =
13065         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13066          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13067 
13068   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13069       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13070     return SDValue();
13071 
13072   // Extend f32 values to f64
13073   if (ResVT.getScalarSizeInBits() == 32) {
13074     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13075     DCI.AddToWorklist(Val.getNode());
13076   }
13077 
13078   // Set signed or unsigned conversion opcode.
13079   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13080                           PPCISD::FP_TO_SINT_IN_VSR :
13081                           PPCISD::FP_TO_UINT_IN_VSR;
13082 
13083   Val = DAG.getNode(ConvOpcode,
13084                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13085   DCI.AddToWorklist(Val.getNode());
13086 
13087   // Set number of bytes being converted.
13088   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13089   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13090                     DAG.getIntPtrConstant(ByteSize, dl, false),
13091                     DAG.getValueType(Op1VT) };
13092 
13093   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13094           DAG.getVTList(MVT::Other), Ops,
13095           cast<StoreSDNode>(N)->getMemoryVT(),
13096           cast<StoreSDNode>(N)->getMemOperand());
13097 
13098   DCI.AddToWorklist(Val.getNode());
13099   return Val;
13100 }
13101 
13102 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13103                                              DAGCombinerInfo &DCI) const {
13104   SelectionDAG &DAG = DCI.DAG;
13105   SDLoc dl(N);
13106   switch (N->getOpcode()) {
13107   default: break;
13108   case ISD::ADD:
13109     return combineADD(N, DCI);
13110   case ISD::SHL:
13111     return combineSHL(N, DCI);
13112   case ISD::SRA:
13113     return combineSRA(N, DCI);
13114   case ISD::SRL:
13115     return combineSRL(N, DCI);
13116   case ISD::MUL:
13117     return combineMUL(N, DCI);
13118   case PPCISD::SHL:
13119     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13120         return N->getOperand(0);
13121     break;
13122   case PPCISD::SRL:
13123     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13124         return N->getOperand(0);
13125     break;
13126   case PPCISD::SRA:
13127     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13128       if (C->isNullValue() ||   //  0 >>s V -> 0.
13129           C->isAllOnesValue())    // -1 >>s V -> -1.
13130         return N->getOperand(0);
13131     }
13132     break;
13133   case ISD::SIGN_EXTEND:
13134   case ISD::ZERO_EXTEND:
13135   case ISD::ANY_EXTEND:
13136     return DAGCombineExtBoolTrunc(N, DCI);
13137   case ISD::TRUNCATE:
13138     return combineTRUNCATE(N, DCI);
13139   case ISD::SETCC:
13140     if (SDValue CSCC = combineSetCC(N, DCI))
13141       return CSCC;
13142     LLVM_FALLTHROUGH;
13143   case ISD::SELECT_CC:
13144     return DAGCombineTruncBoolExt(N, DCI);
13145   case ISD::SINT_TO_FP:
13146   case ISD::UINT_TO_FP:
13147     return combineFPToIntToFP(N, DCI);
13148   case ISD::STORE: {
13149 
13150     EVT Op1VT = N->getOperand(1).getValueType();
13151     unsigned Opcode = N->getOperand(1).getOpcode();
13152 
13153     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13154       SDValue Val= combineStoreFPToInt(N, DCI);
13155       if (Val)
13156         return Val;
13157     }
13158 
13159     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13160     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13161         N->getOperand(1).getNode()->hasOneUse() &&
13162         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13163          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13164 
13165       // STBRX can only handle simple types and it makes no sense to store less
13166       // two bytes in byte-reversed order.
13167       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13168       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13169         break;
13170 
13171       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13172       // Do an any-extend to 32-bits if this is a half-word input.
13173       if (BSwapOp.getValueType() == MVT::i16)
13174         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13175 
13176       // If the type of BSWAP operand is wider than stored memory width
13177       // it need to be shifted to the right side before STBRX.
13178       if (Op1VT.bitsGT(mVT)) {
13179         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13180         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13181                               DAG.getConstant(Shift, dl, MVT::i32));
13182         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13183         if (Op1VT == MVT::i64)
13184           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13185       }
13186 
13187       SDValue Ops[] = {
13188         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13189       };
13190       return
13191         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13192                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13193                                 cast<StoreSDNode>(N)->getMemOperand());
13194     }
13195 
13196     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13197     // So it can increase the chance of CSE constant construction.
13198     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13199         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13200       // Need to sign-extended to 64-bits to handle negative values.
13201       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13202       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13203                                     MemVT.getSizeInBits());
13204       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13205 
13206       // DAG.getTruncStore() can't be used here because it doesn't accept
13207       // the general (base + offset) addressing mode.
13208       // So we use UpdateNodeOperands and setTruncatingStore instead.
13209       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13210                              N->getOperand(3));
13211       cast<StoreSDNode>(N)->setTruncatingStore(true);
13212       return SDValue(N, 0);
13213     }
13214 
13215     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13216     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13217     if (Op1VT.isSimple()) {
13218       MVT StoreVT = Op1VT.getSimpleVT();
13219       if (Subtarget.needsSwapsForVSXMemOps() &&
13220           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13221            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13222         return expandVSXStoreForLE(N, DCI);
13223     }
13224     break;
13225   }
13226   case ISD::LOAD: {
13227     LoadSDNode *LD = cast<LoadSDNode>(N);
13228     EVT VT = LD->getValueType(0);
13229 
13230     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13231     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13232     if (VT.isSimple()) {
13233       MVT LoadVT = VT.getSimpleVT();
13234       if (Subtarget.needsSwapsForVSXMemOps() &&
13235           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13236            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13237         return expandVSXLoadForLE(N, DCI);
13238     }
13239 
13240     // We sometimes end up with a 64-bit integer load, from which we extract
13241     // two single-precision floating-point numbers. This happens with
13242     // std::complex<float>, and other similar structures, because of the way we
13243     // canonicalize structure copies. However, if we lack direct moves,
13244     // then the final bitcasts from the extracted integer values to the
13245     // floating-point numbers turn into store/load pairs. Even with direct moves,
13246     // just loading the two floating-point numbers is likely better.
13247     auto ReplaceTwoFloatLoad = [&]() {
13248       if (VT != MVT::i64)
13249         return false;
13250 
13251       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13252           LD->isVolatile())
13253         return false;
13254 
13255       //  We're looking for a sequence like this:
13256       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13257       //      t16: i64 = srl t13, Constant:i32<32>
13258       //    t17: i32 = truncate t16
13259       //  t18: f32 = bitcast t17
13260       //    t19: i32 = truncate t13
13261       //  t20: f32 = bitcast t19
13262 
13263       if (!LD->hasNUsesOfValue(2, 0))
13264         return false;
13265 
13266       auto UI = LD->use_begin();
13267       while (UI.getUse().getResNo() != 0) ++UI;
13268       SDNode *Trunc = *UI++;
13269       while (UI.getUse().getResNo() != 0) ++UI;
13270       SDNode *RightShift = *UI;
13271       if (Trunc->getOpcode() != ISD::TRUNCATE)
13272         std::swap(Trunc, RightShift);
13273 
13274       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13275           Trunc->getValueType(0) != MVT::i32 ||
13276           !Trunc->hasOneUse())
13277         return false;
13278       if (RightShift->getOpcode() != ISD::SRL ||
13279           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13280           RightShift->getConstantOperandVal(1) != 32 ||
13281           !RightShift->hasOneUse())
13282         return false;
13283 
13284       SDNode *Trunc2 = *RightShift->use_begin();
13285       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13286           Trunc2->getValueType(0) != MVT::i32 ||
13287           !Trunc2->hasOneUse())
13288         return false;
13289 
13290       SDNode *Bitcast = *Trunc->use_begin();
13291       SDNode *Bitcast2 = *Trunc2->use_begin();
13292 
13293       if (Bitcast->getOpcode() != ISD::BITCAST ||
13294           Bitcast->getValueType(0) != MVT::f32)
13295         return false;
13296       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13297           Bitcast2->getValueType(0) != MVT::f32)
13298         return false;
13299 
13300       if (Subtarget.isLittleEndian())
13301         std::swap(Bitcast, Bitcast2);
13302 
13303       // Bitcast has the second float (in memory-layout order) and Bitcast2
13304       // has the first one.
13305 
13306       SDValue BasePtr = LD->getBasePtr();
13307       if (LD->isIndexed()) {
13308         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13309                "Non-pre-inc AM on PPC?");
13310         BasePtr =
13311           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13312                       LD->getOffset());
13313       }
13314 
13315       auto MMOFlags =
13316           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13317       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13318                                       LD->getPointerInfo(), LD->getAlignment(),
13319                                       MMOFlags, LD->getAAInfo());
13320       SDValue AddPtr =
13321         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13322                     BasePtr, DAG.getIntPtrConstant(4, dl));
13323       SDValue FloatLoad2 = DAG.getLoad(
13324           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13325           LD->getPointerInfo().getWithOffset(4),
13326           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13327 
13328       if (LD->isIndexed()) {
13329         // Note that DAGCombine should re-form any pre-increment load(s) from
13330         // what is produced here if that makes sense.
13331         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13332       }
13333 
13334       DCI.CombineTo(Bitcast2, FloatLoad);
13335       DCI.CombineTo(Bitcast, FloatLoad2);
13336 
13337       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13338                                     SDValue(FloatLoad2.getNode(), 1));
13339       return true;
13340     };
13341 
13342     if (ReplaceTwoFloatLoad())
13343       return SDValue(N, 0);
13344 
13345     EVT MemVT = LD->getMemoryVT();
13346     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13347     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13348     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13349     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13350     if (LD->isUnindexed() && VT.isVector() &&
13351         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13352           // P8 and later hardware should just use LOAD.
13353           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13354                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13355          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13356           LD->getAlignment() >= ScalarABIAlignment)) &&
13357         LD->getAlignment() < ABIAlignment) {
13358       // This is a type-legal unaligned Altivec or QPX load.
13359       SDValue Chain = LD->getChain();
13360       SDValue Ptr = LD->getBasePtr();
13361       bool isLittleEndian = Subtarget.isLittleEndian();
13362 
13363       // This implements the loading of unaligned vectors as described in
13364       // the venerable Apple Velocity Engine overview. Specifically:
13365       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13366       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13367       //
13368       // The general idea is to expand a sequence of one or more unaligned
13369       // loads into an alignment-based permutation-control instruction (lvsl
13370       // or lvsr), a series of regular vector loads (which always truncate
13371       // their input address to an aligned address), and a series of
13372       // permutations.  The results of these permutations are the requested
13373       // loaded values.  The trick is that the last "extra" load is not taken
13374       // from the address you might suspect (sizeof(vector) bytes after the
13375       // last requested load), but rather sizeof(vector) - 1 bytes after the
13376       // last requested vector. The point of this is to avoid a page fault if
13377       // the base address happened to be aligned. This works because if the
13378       // base address is aligned, then adding less than a full vector length
13379       // will cause the last vector in the sequence to be (re)loaded.
13380       // Otherwise, the next vector will be fetched as you might suspect was
13381       // necessary.
13382 
13383       // We might be able to reuse the permutation generation from
13384       // a different base address offset from this one by an aligned amount.
13385       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13386       // optimization later.
13387       Intrinsic::ID Intr, IntrLD, IntrPerm;
13388       MVT PermCntlTy, PermTy, LDTy;
13389       if (Subtarget.hasAltivec()) {
13390         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13391                                  Intrinsic::ppc_altivec_lvsl;
13392         IntrLD = Intrinsic::ppc_altivec_lvx;
13393         IntrPerm = Intrinsic::ppc_altivec_vperm;
13394         PermCntlTy = MVT::v16i8;
13395         PermTy = MVT::v4i32;
13396         LDTy = MVT::v4i32;
13397       } else {
13398         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13399                                        Intrinsic::ppc_qpx_qvlpcls;
13400         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13401                                        Intrinsic::ppc_qpx_qvlfs;
13402         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13403         PermCntlTy = MVT::v4f64;
13404         PermTy = MVT::v4f64;
13405         LDTy = MemVT.getSimpleVT();
13406       }
13407 
13408       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13409 
13410       // Create the new MMO for the new base load. It is like the original MMO,
13411       // but represents an area in memory almost twice the vector size centered
13412       // on the original address. If the address is unaligned, we might start
13413       // reading up to (sizeof(vector)-1) bytes below the address of the
13414       // original unaligned load.
13415       MachineFunction &MF = DAG.getMachineFunction();
13416       MachineMemOperand *BaseMMO =
13417         MF.getMachineMemOperand(LD->getMemOperand(),
13418                                 -(long)MemVT.getStoreSize()+1,
13419                                 2*MemVT.getStoreSize()-1);
13420 
13421       // Create the new base load.
13422       SDValue LDXIntID =
13423           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13424       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13425       SDValue BaseLoad =
13426         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13427                                 DAG.getVTList(PermTy, MVT::Other),
13428                                 BaseLoadOps, LDTy, BaseMMO);
13429 
13430       // Note that the value of IncOffset (which is provided to the next
13431       // load's pointer info offset value, and thus used to calculate the
13432       // alignment), and the value of IncValue (which is actually used to
13433       // increment the pointer value) are different! This is because we
13434       // require the next load to appear to be aligned, even though it
13435       // is actually offset from the base pointer by a lesser amount.
13436       int IncOffset = VT.getSizeInBits() / 8;
13437       int IncValue = IncOffset;
13438 
13439       // Walk (both up and down) the chain looking for another load at the real
13440       // (aligned) offset (the alignment of the other load does not matter in
13441       // this case). If found, then do not use the offset reduction trick, as
13442       // that will prevent the loads from being later combined (as they would
13443       // otherwise be duplicates).
13444       if (!findConsecutiveLoad(LD, DAG))
13445         --IncValue;
13446 
13447       SDValue Increment =
13448           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13449       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13450 
13451       MachineMemOperand *ExtraMMO =
13452         MF.getMachineMemOperand(LD->getMemOperand(),
13453                                 1, 2*MemVT.getStoreSize()-1);
13454       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13455       SDValue ExtraLoad =
13456         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13457                                 DAG.getVTList(PermTy, MVT::Other),
13458                                 ExtraLoadOps, LDTy, ExtraMMO);
13459 
13460       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13461         BaseLoad.getValue(1), ExtraLoad.getValue(1));
13462 
13463       // Because vperm has a big-endian bias, we must reverse the order
13464       // of the input vectors and complement the permute control vector
13465       // when generating little endian code.  We have already handled the
13466       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13467       // and ExtraLoad here.
13468       SDValue Perm;
13469       if (isLittleEndian)
13470         Perm = BuildIntrinsicOp(IntrPerm,
13471                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
13472       else
13473         Perm = BuildIntrinsicOp(IntrPerm,
13474                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
13475 
13476       if (VT != PermTy)
13477         Perm = Subtarget.hasAltivec() ?
13478                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
13479                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
13480                                DAG.getTargetConstant(1, dl, MVT::i64));
13481                                // second argument is 1 because this rounding
13482                                // is always exact.
13483 
13484       // The output of the permutation is our loaded result, the TokenFactor is
13485       // our new chain.
13486       DCI.CombineTo(N, Perm, TF);
13487       return SDValue(N, 0);
13488     }
13489     }
13490     break;
13491     case ISD::INTRINSIC_WO_CHAIN: {
13492       bool isLittleEndian = Subtarget.isLittleEndian();
13493       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13494       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
13495                                            : Intrinsic::ppc_altivec_lvsl);
13496       if ((IID == Intr ||
13497            IID == Intrinsic::ppc_qpx_qvlpcld  ||
13498            IID == Intrinsic::ppc_qpx_qvlpcls) &&
13499         N->getOperand(1)->getOpcode() == ISD::ADD) {
13500         SDValue Add = N->getOperand(1);
13501 
13502         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
13503                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
13504 
13505         if (DAG.MaskedValueIsZero(Add->getOperand(1),
13506                                   APInt::getAllOnesValue(Bits /* alignment */)
13507                                       .zext(Add.getScalarValueSizeInBits()))) {
13508           SDNode *BasePtr = Add->getOperand(0).getNode();
13509           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13510                                     UE = BasePtr->use_end();
13511                UI != UE; ++UI) {
13512             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13513                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
13514               // We've found another LVSL/LVSR, and this address is an aligned
13515               // multiple of that one. The results will be the same, so use the
13516               // one we've just found instead.
13517 
13518               return SDValue(*UI, 0);
13519             }
13520           }
13521         }
13522 
13523         if (isa<ConstantSDNode>(Add->getOperand(1))) {
13524           SDNode *BasePtr = Add->getOperand(0).getNode();
13525           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13526                UE = BasePtr->use_end(); UI != UE; ++UI) {
13527             if (UI->getOpcode() == ISD::ADD &&
13528                 isa<ConstantSDNode>(UI->getOperand(1)) &&
13529                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
13530                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
13531                 (1ULL << Bits) == 0) {
13532               SDNode *OtherAdd = *UI;
13533               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
13534                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
13535                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13536                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
13537                   return SDValue(*VI, 0);
13538                 }
13539               }
13540             }
13541           }
13542         }
13543       }
13544 
13545       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
13546       // Expose the vabsduw/h/b opportunity for down stream
13547       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
13548           (IID == Intrinsic::ppc_altivec_vmaxsw ||
13549            IID == Intrinsic::ppc_altivec_vmaxsh ||
13550            IID == Intrinsic::ppc_altivec_vmaxsb)) {
13551         SDValue V1 = N->getOperand(1);
13552         SDValue V2 = N->getOperand(2);
13553         if ((V1.getSimpleValueType() == MVT::v4i32 ||
13554              V1.getSimpleValueType() == MVT::v8i16 ||
13555              V1.getSimpleValueType() == MVT::v16i8) &&
13556             V1.getSimpleValueType() == V2.getSimpleValueType()) {
13557           // (0-a, a)
13558           if (V1.getOpcode() == ISD::SUB &&
13559               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
13560               V1.getOperand(1) == V2) {
13561             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
13562           }
13563           // (a, 0-a)
13564           if (V2.getOpcode() == ISD::SUB &&
13565               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
13566               V2.getOperand(1) == V1) {
13567             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13568           }
13569           // (x-y, y-x)
13570           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
13571               V1.getOperand(0) == V2.getOperand(1) &&
13572               V1.getOperand(1) == V2.getOperand(0)) {
13573             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13574           }
13575         }
13576       }
13577     }
13578 
13579     break;
13580   case ISD::INTRINSIC_W_CHAIN:
13581     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13582     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13583     if (Subtarget.needsSwapsForVSXMemOps()) {
13584       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13585       default:
13586         break;
13587       case Intrinsic::ppc_vsx_lxvw4x:
13588       case Intrinsic::ppc_vsx_lxvd2x:
13589         return expandVSXLoadForLE(N, DCI);
13590       }
13591     }
13592     break;
13593   case ISD::INTRINSIC_VOID:
13594     // For little endian, VSX stores require generating xxswapd/stxvd2x.
13595     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13596     if (Subtarget.needsSwapsForVSXMemOps()) {
13597       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13598       default:
13599         break;
13600       case Intrinsic::ppc_vsx_stxvw4x:
13601       case Intrinsic::ppc_vsx_stxvd2x:
13602         return expandVSXStoreForLE(N, DCI);
13603       }
13604     }
13605     break;
13606   case ISD::BSWAP:
13607     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
13608     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
13609         N->getOperand(0).hasOneUse() &&
13610         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
13611          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
13612           N->getValueType(0) == MVT::i64))) {
13613       SDValue Load = N->getOperand(0);
13614       LoadSDNode *LD = cast<LoadSDNode>(Load);
13615       // Create the byte-swapping load.
13616       SDValue Ops[] = {
13617         LD->getChain(),    // Chain
13618         LD->getBasePtr(),  // Ptr
13619         DAG.getValueType(N->getValueType(0)) // VT
13620       };
13621       SDValue BSLoad =
13622         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
13623                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
13624                                               MVT::i64 : MVT::i32, MVT::Other),
13625                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
13626 
13627       // If this is an i16 load, insert the truncate.
13628       SDValue ResVal = BSLoad;
13629       if (N->getValueType(0) == MVT::i16)
13630         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
13631 
13632       // First, combine the bswap away.  This makes the value produced by the
13633       // load dead.
13634       DCI.CombineTo(N, ResVal);
13635 
13636       // Next, combine the load away, we give it a bogus result value but a real
13637       // chain result.  The result value is dead because the bswap is dead.
13638       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
13639 
13640       // Return N so it doesn't get rechecked!
13641       return SDValue(N, 0);
13642     }
13643     break;
13644   case PPCISD::VCMP:
13645     // If a VCMPo node already exists with exactly the same operands as this
13646     // node, use its result instead of this node (VCMPo computes both a CR6 and
13647     // a normal output).
13648     //
13649     if (!N->getOperand(0).hasOneUse() &&
13650         !N->getOperand(1).hasOneUse() &&
13651         !N->getOperand(2).hasOneUse()) {
13652 
13653       // Scan all of the users of the LHS, looking for VCMPo's that match.
13654       SDNode *VCMPoNode = nullptr;
13655 
13656       SDNode *LHSN = N->getOperand(0).getNode();
13657       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
13658            UI != E; ++UI)
13659         if (UI->getOpcode() == PPCISD::VCMPo &&
13660             UI->getOperand(1) == N->getOperand(1) &&
13661             UI->getOperand(2) == N->getOperand(2) &&
13662             UI->getOperand(0) == N->getOperand(0)) {
13663           VCMPoNode = *UI;
13664           break;
13665         }
13666 
13667       // If there is no VCMPo node, or if the flag value has a single use, don't
13668       // transform this.
13669       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
13670         break;
13671 
13672       // Look at the (necessarily single) use of the flag value.  If it has a
13673       // chain, this transformation is more complex.  Note that multiple things
13674       // could use the value result, which we should ignore.
13675       SDNode *FlagUser = nullptr;
13676       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
13677            FlagUser == nullptr; ++UI) {
13678         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
13679         SDNode *User = *UI;
13680         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
13681           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
13682             FlagUser = User;
13683             break;
13684           }
13685         }
13686       }
13687 
13688       // If the user is a MFOCRF instruction, we know this is safe.
13689       // Otherwise we give up for right now.
13690       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
13691         return SDValue(VCMPoNode, 0);
13692     }
13693     break;
13694   case ISD::BRCOND: {
13695     SDValue Cond = N->getOperand(1);
13696     SDValue Target = N->getOperand(2);
13697 
13698     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13699         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
13700           Intrinsic::loop_decrement) {
13701 
13702       // We now need to make the intrinsic dead (it cannot be instruction
13703       // selected).
13704       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
13705       assert(Cond.getNode()->hasOneUse() &&
13706              "Counter decrement has more than one use");
13707 
13708       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
13709                          N->getOperand(0), Target);
13710     }
13711   }
13712   break;
13713   case ISD::BR_CC: {
13714     // If this is a branch on an altivec predicate comparison, lower this so
13715     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
13716     // lowering is done pre-legalize, because the legalizer lowers the predicate
13717     // compare down to code that is difficult to reassemble.
13718     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13719     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
13720 
13721     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
13722     // value. If so, pass-through the AND to get to the intrinsic.
13723     if (LHS.getOpcode() == ISD::AND &&
13724         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13725         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
13726           Intrinsic::loop_decrement &&
13727         isa<ConstantSDNode>(LHS.getOperand(1)) &&
13728         !isNullConstant(LHS.getOperand(1)))
13729       LHS = LHS.getOperand(0);
13730 
13731     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13732         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
13733           Intrinsic::loop_decrement &&
13734         isa<ConstantSDNode>(RHS)) {
13735       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
13736              "Counter decrement comparison is not EQ or NE");
13737 
13738       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13739       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
13740                     (CC == ISD::SETNE && !Val);
13741 
13742       // We now need to make the intrinsic dead (it cannot be instruction
13743       // selected).
13744       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
13745       assert(LHS.getNode()->hasOneUse() &&
13746              "Counter decrement has more than one use");
13747 
13748       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
13749                          N->getOperand(0), N->getOperand(4));
13750     }
13751 
13752     int CompareOpc;
13753     bool isDot;
13754 
13755     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13756         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
13757         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
13758       assert(isDot && "Can't compare against a vector result!");
13759 
13760       // If this is a comparison against something other than 0/1, then we know
13761       // that the condition is never/always true.
13762       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13763       if (Val != 0 && Val != 1) {
13764         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
13765           return N->getOperand(0);
13766         // Always !=, turn it into an unconditional branch.
13767         return DAG.getNode(ISD::BR, dl, MVT::Other,
13768                            N->getOperand(0), N->getOperand(4));
13769       }
13770 
13771       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
13772 
13773       // Create the PPCISD altivec 'dot' comparison node.
13774       SDValue Ops[] = {
13775         LHS.getOperand(2),  // LHS of compare
13776         LHS.getOperand(3),  // RHS of compare
13777         DAG.getConstant(CompareOpc, dl, MVT::i32)
13778       };
13779       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
13780       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
13781 
13782       // Unpack the result based on how the target uses it.
13783       PPC::Predicate CompOpc;
13784       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
13785       default:  // Can't happen, don't crash on invalid number though.
13786       case 0:   // Branch on the value of the EQ bit of CR6.
13787         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
13788         break;
13789       case 1:   // Branch on the inverted value of the EQ bit of CR6.
13790         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
13791         break;
13792       case 2:   // Branch on the value of the LT bit of CR6.
13793         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
13794         break;
13795       case 3:   // Branch on the inverted value of the LT bit of CR6.
13796         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
13797         break;
13798       }
13799 
13800       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
13801                          DAG.getConstant(CompOpc, dl, MVT::i32),
13802                          DAG.getRegister(PPC::CR6, MVT::i32),
13803                          N->getOperand(4), CompNode.getValue(1));
13804     }
13805     break;
13806   }
13807   case ISD::BUILD_VECTOR:
13808     return DAGCombineBuildVector(N, DCI);
13809   case ISD::ABS:
13810     return combineABS(N, DCI);
13811   case ISD::VSELECT:
13812     return combineVSelect(N, DCI);
13813   }
13814 
13815   return SDValue();
13816 }
13817 
13818 SDValue
13819 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
13820                                  SelectionDAG &DAG,
13821                                  SmallVectorImpl<SDNode *> &Created) const {
13822   // fold (sdiv X, pow2)
13823   EVT VT = N->getValueType(0);
13824   if (VT == MVT::i64 && !Subtarget.isPPC64())
13825     return SDValue();
13826   if ((VT != MVT::i32 && VT != MVT::i64) ||
13827       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
13828     return SDValue();
13829 
13830   SDLoc DL(N);
13831   SDValue N0 = N->getOperand(0);
13832 
13833   bool IsNegPow2 = (-Divisor).isPowerOf2();
13834   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
13835   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
13836 
13837   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
13838   Created.push_back(Op.getNode());
13839 
13840   if (IsNegPow2) {
13841     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
13842     Created.push_back(Op.getNode());
13843   }
13844 
13845   return Op;
13846 }
13847 
13848 //===----------------------------------------------------------------------===//
13849 // Inline Assembly Support
13850 //===----------------------------------------------------------------------===//
13851 
13852 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13853                                                       KnownBits &Known,
13854                                                       const APInt &DemandedElts,
13855                                                       const SelectionDAG &DAG,
13856                                                       unsigned Depth) const {
13857   Known.resetAll();
13858   switch (Op.getOpcode()) {
13859   default: break;
13860   case PPCISD::LBRX: {
13861     // lhbrx is known to have the top bits cleared out.
13862     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
13863       Known.Zero = 0xFFFF0000;
13864     break;
13865   }
13866   case ISD::INTRINSIC_WO_CHAIN: {
13867     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
13868     default: break;
13869     case Intrinsic::ppc_altivec_vcmpbfp_p:
13870     case Intrinsic::ppc_altivec_vcmpeqfp_p:
13871     case Intrinsic::ppc_altivec_vcmpequb_p:
13872     case Intrinsic::ppc_altivec_vcmpequh_p:
13873     case Intrinsic::ppc_altivec_vcmpequw_p:
13874     case Intrinsic::ppc_altivec_vcmpequd_p:
13875     case Intrinsic::ppc_altivec_vcmpgefp_p:
13876     case Intrinsic::ppc_altivec_vcmpgtfp_p:
13877     case Intrinsic::ppc_altivec_vcmpgtsb_p:
13878     case Intrinsic::ppc_altivec_vcmpgtsh_p:
13879     case Intrinsic::ppc_altivec_vcmpgtsw_p:
13880     case Intrinsic::ppc_altivec_vcmpgtsd_p:
13881     case Intrinsic::ppc_altivec_vcmpgtub_p:
13882     case Intrinsic::ppc_altivec_vcmpgtuh_p:
13883     case Intrinsic::ppc_altivec_vcmpgtuw_p:
13884     case Intrinsic::ppc_altivec_vcmpgtud_p:
13885       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
13886       break;
13887     }
13888   }
13889   }
13890 }
13891 
13892 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
13893   switch (Subtarget.getDarwinDirective()) {
13894   default: break;
13895   case PPC::DIR_970:
13896   case PPC::DIR_PWR4:
13897   case PPC::DIR_PWR5:
13898   case PPC::DIR_PWR5X:
13899   case PPC::DIR_PWR6:
13900   case PPC::DIR_PWR6X:
13901   case PPC::DIR_PWR7:
13902   case PPC::DIR_PWR8:
13903   case PPC::DIR_PWR9: {
13904     if (!ML)
13905       break;
13906 
13907     if (!DisableInnermostLoopAlign32) {
13908       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
13909       // so that we can decrease cache misses and branch-prediction misses.
13910       // Actual alignment of the loop will depend on the hotness check and other
13911       // logic in alignBlocks.
13912       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
13913         return 5;
13914     }
13915 
13916     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13917 
13918     // For small loops (between 5 and 8 instructions), align to a 32-byte
13919     // boundary so that the entire loop fits in one instruction-cache line.
13920     uint64_t LoopSize = 0;
13921     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
13922       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
13923         LoopSize += TII->getInstSizeInBytes(*J);
13924         if (LoopSize > 32)
13925           break;
13926       }
13927 
13928     if (LoopSize > 16 && LoopSize <= 32)
13929       return 5;
13930 
13931     break;
13932   }
13933   }
13934 
13935   return TargetLowering::getPrefLoopAlignment(ML);
13936 }
13937 
13938 /// getConstraintType - Given a constraint, return the type of
13939 /// constraint it is for this target.
13940 PPCTargetLowering::ConstraintType
13941 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
13942   if (Constraint.size() == 1) {
13943     switch (Constraint[0]) {
13944     default: break;
13945     case 'b':
13946     case 'r':
13947     case 'f':
13948     case 'd':
13949     case 'v':
13950     case 'y':
13951       return C_RegisterClass;
13952     case 'Z':
13953       // FIXME: While Z does indicate a memory constraint, it specifically
13954       // indicates an r+r address (used in conjunction with the 'y' modifier
13955       // in the replacement string). Currently, we're forcing the base
13956       // register to be r0 in the asm printer (which is interpreted as zero)
13957       // and forming the complete address in the second register. This is
13958       // suboptimal.
13959       return C_Memory;
13960     }
13961   } else if (Constraint == "wc") { // individual CR bits.
13962     return C_RegisterClass;
13963   } else if (Constraint == "wa" || Constraint == "wd" ||
13964              Constraint == "wf" || Constraint == "ws" ||
13965              Constraint == "wi") {
13966     return C_RegisterClass; // VSX registers.
13967   }
13968   return TargetLowering::getConstraintType(Constraint);
13969 }
13970 
13971 /// Examine constraint type and operand type and determine a weight value.
13972 /// This object must already have been set up with the operand type
13973 /// and the current alternative constraint selected.
13974 TargetLowering::ConstraintWeight
13975 PPCTargetLowering::getSingleConstraintMatchWeight(
13976     AsmOperandInfo &info, const char *constraint) const {
13977   ConstraintWeight weight = CW_Invalid;
13978   Value *CallOperandVal = info.CallOperandVal;
13979     // If we don't have a value, we can't do a match,
13980     // but allow it at the lowest weight.
13981   if (!CallOperandVal)
13982     return CW_Default;
13983   Type *type = CallOperandVal->getType();
13984 
13985   // Look at the constraint type.
13986   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
13987     return CW_Register; // an individual CR bit.
13988   else if ((StringRef(constraint) == "wa" ||
13989             StringRef(constraint) == "wd" ||
13990             StringRef(constraint) == "wf") &&
13991            type->isVectorTy())
13992     return CW_Register;
13993   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
13994     return CW_Register;
13995   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
13996     return CW_Register; // just hold 64-bit integers data.
13997 
13998   switch (*constraint) {
13999   default:
14000     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14001     break;
14002   case 'b':
14003     if (type->isIntegerTy())
14004       weight = CW_Register;
14005     break;
14006   case 'f':
14007     if (type->isFloatTy())
14008       weight = CW_Register;
14009     break;
14010   case 'd':
14011     if (type->isDoubleTy())
14012       weight = CW_Register;
14013     break;
14014   case 'v':
14015     if (type->isVectorTy())
14016       weight = CW_Register;
14017     break;
14018   case 'y':
14019     weight = CW_Register;
14020     break;
14021   case 'Z':
14022     weight = CW_Memory;
14023     break;
14024   }
14025   return weight;
14026 }
14027 
14028 std::pair<unsigned, const TargetRegisterClass *>
14029 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14030                                                 StringRef Constraint,
14031                                                 MVT VT) const {
14032   if (Constraint.size() == 1) {
14033     // GCC RS6000 Constraint Letters
14034     switch (Constraint[0]) {
14035     case 'b':   // R1-R31
14036       if (VT == MVT::i64 && Subtarget.isPPC64())
14037         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14038       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14039     case 'r':   // R0-R31
14040       if (VT == MVT::i64 && Subtarget.isPPC64())
14041         return std::make_pair(0U, &PPC::G8RCRegClass);
14042       return std::make_pair(0U, &PPC::GPRCRegClass);
14043     // 'd' and 'f' constraints are both defined to be "the floating point
14044     // registers", where one is for 32-bit and the other for 64-bit. We don't
14045     // really care overly much here so just give them all the same reg classes.
14046     case 'd':
14047     case 'f':
14048       if (Subtarget.hasSPE()) {
14049         if (VT == MVT::f32 || VT == MVT::i32)
14050           return std::make_pair(0U, &PPC::SPE4RCRegClass);
14051         if (VT == MVT::f64 || VT == MVT::i64)
14052           return std::make_pair(0U, &PPC::SPERCRegClass);
14053       } else {
14054         if (VT == MVT::f32 || VT == MVT::i32)
14055           return std::make_pair(0U, &PPC::F4RCRegClass);
14056         if (VT == MVT::f64 || VT == MVT::i64)
14057           return std::make_pair(0U, &PPC::F8RCRegClass);
14058         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14059           return std::make_pair(0U, &PPC::QFRCRegClass);
14060         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14061           return std::make_pair(0U, &PPC::QSRCRegClass);
14062       }
14063       break;
14064     case 'v':
14065       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14066         return std::make_pair(0U, &PPC::QFRCRegClass);
14067       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14068         return std::make_pair(0U, &PPC::QSRCRegClass);
14069       if (Subtarget.hasAltivec())
14070         return std::make_pair(0U, &PPC::VRRCRegClass);
14071       break;
14072     case 'y':   // crrc
14073       return std::make_pair(0U, &PPC::CRRCRegClass);
14074     }
14075   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14076     // An individual CR bit.
14077     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14078   } else if ((Constraint == "wa" || Constraint == "wd" ||
14079              Constraint == "wf" || Constraint == "wi") &&
14080              Subtarget.hasVSX()) {
14081     return std::make_pair(0U, &PPC::VSRCRegClass);
14082   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
14083     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14084       return std::make_pair(0U, &PPC::VSSRCRegClass);
14085     else
14086       return std::make_pair(0U, &PPC::VSFRCRegClass);
14087   }
14088 
14089   std::pair<unsigned, const TargetRegisterClass *> R =
14090       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14091 
14092   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14093   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14094   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14095   // register.
14096   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14097   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14098   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14099       PPC::GPRCRegClass.contains(R.first))
14100     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14101                             PPC::sub_32, &PPC::G8RCRegClass),
14102                           &PPC::G8RCRegClass);
14103 
14104   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14105   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14106     R.first = PPC::CR0;
14107     R.second = &PPC::CRRCRegClass;
14108   }
14109 
14110   return R;
14111 }
14112 
14113 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14114 /// vector.  If it is invalid, don't add anything to Ops.
14115 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14116                                                      std::string &Constraint,
14117                                                      std::vector<SDValue>&Ops,
14118                                                      SelectionDAG &DAG) const {
14119   SDValue Result;
14120 
14121   // Only support length 1 constraints.
14122   if (Constraint.length() > 1) return;
14123 
14124   char Letter = Constraint[0];
14125   switch (Letter) {
14126   default: break;
14127   case 'I':
14128   case 'J':
14129   case 'K':
14130   case 'L':
14131   case 'M':
14132   case 'N':
14133   case 'O':
14134   case 'P': {
14135     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14136     if (!CST) return; // Must be an immediate to match.
14137     SDLoc dl(Op);
14138     int64_t Value = CST->getSExtValue();
14139     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14140                          // numbers are printed as such.
14141     switch (Letter) {
14142     default: llvm_unreachable("Unknown constraint letter!");
14143     case 'I':  // "I" is a signed 16-bit constant.
14144       if (isInt<16>(Value))
14145         Result = DAG.getTargetConstant(Value, dl, TCVT);
14146       break;
14147     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14148       if (isShiftedUInt<16, 16>(Value))
14149         Result = DAG.getTargetConstant(Value, dl, TCVT);
14150       break;
14151     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14152       if (isShiftedInt<16, 16>(Value))
14153         Result = DAG.getTargetConstant(Value, dl, TCVT);
14154       break;
14155     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14156       if (isUInt<16>(Value))
14157         Result = DAG.getTargetConstant(Value, dl, TCVT);
14158       break;
14159     case 'M':  // "M" is a constant that is greater than 31.
14160       if (Value > 31)
14161         Result = DAG.getTargetConstant(Value, dl, TCVT);
14162       break;
14163     case 'N':  // "N" is a positive constant that is an exact power of two.
14164       if (Value > 0 && isPowerOf2_64(Value))
14165         Result = DAG.getTargetConstant(Value, dl, TCVT);
14166       break;
14167     case 'O':  // "O" is the constant zero.
14168       if (Value == 0)
14169         Result = DAG.getTargetConstant(Value, dl, TCVT);
14170       break;
14171     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14172       if (isInt<16>(-Value))
14173         Result = DAG.getTargetConstant(Value, dl, TCVT);
14174       break;
14175     }
14176     break;
14177   }
14178   }
14179 
14180   if (Result.getNode()) {
14181     Ops.push_back(Result);
14182     return;
14183   }
14184 
14185   // Handle standard constraint letters.
14186   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14187 }
14188 
14189 // isLegalAddressingMode - Return true if the addressing mode represented
14190 // by AM is legal for this target, for a load/store of the specified type.
14191 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14192                                               const AddrMode &AM, Type *Ty,
14193                                               unsigned AS, Instruction *I) const {
14194   // PPC does not allow r+i addressing modes for vectors!
14195   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14196     return false;
14197 
14198   // PPC allows a sign-extended 16-bit immediate field.
14199   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14200     return false;
14201 
14202   // No global is ever allowed as a base.
14203   if (AM.BaseGV)
14204     return false;
14205 
14206   // PPC only support r+r,
14207   switch (AM.Scale) {
14208   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14209     break;
14210   case 1:
14211     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14212       return false;
14213     // Otherwise we have r+r or r+i.
14214     break;
14215   case 2:
14216     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14217       return false;
14218     // Allow 2*r as r+r.
14219     break;
14220   default:
14221     // No other scales are supported.
14222     return false;
14223   }
14224 
14225   return true;
14226 }
14227 
14228 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14229                                            SelectionDAG &DAG) const {
14230   MachineFunction &MF = DAG.getMachineFunction();
14231   MachineFrameInfo &MFI = MF.getFrameInfo();
14232   MFI.setReturnAddressIsTaken(true);
14233 
14234   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14235     return SDValue();
14236 
14237   SDLoc dl(Op);
14238   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14239 
14240   // Make sure the function does not optimize away the store of the RA to
14241   // the stack.
14242   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14243   FuncInfo->setLRStoreRequired();
14244   bool isPPC64 = Subtarget.isPPC64();
14245   auto PtrVT = getPointerTy(MF.getDataLayout());
14246 
14247   if (Depth > 0) {
14248     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14249     SDValue Offset =
14250         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14251                         isPPC64 ? MVT::i64 : MVT::i32);
14252     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14253                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14254                        MachinePointerInfo());
14255   }
14256 
14257   // Just load the return address off the stack.
14258   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14259   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14260                      MachinePointerInfo());
14261 }
14262 
14263 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14264                                           SelectionDAG &DAG) const {
14265   SDLoc dl(Op);
14266   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14267 
14268   MachineFunction &MF = DAG.getMachineFunction();
14269   MachineFrameInfo &MFI = MF.getFrameInfo();
14270   MFI.setFrameAddressIsTaken(true);
14271 
14272   EVT PtrVT = getPointerTy(MF.getDataLayout());
14273   bool isPPC64 = PtrVT == MVT::i64;
14274 
14275   // Naked functions never have a frame pointer, and so we use r1. For all
14276   // other functions, this decision must be delayed until during PEI.
14277   unsigned FrameReg;
14278   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14279     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14280   else
14281     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14282 
14283   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14284                                          PtrVT);
14285   while (Depth--)
14286     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14287                             FrameAddr, MachinePointerInfo());
14288   return FrameAddr;
14289 }
14290 
14291 // FIXME? Maybe this could be a TableGen attribute on some registers and
14292 // this table could be generated automatically from RegInfo.
14293 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
14294                                               SelectionDAG &DAG) const {
14295   bool isPPC64 = Subtarget.isPPC64();
14296   bool isDarwinABI = Subtarget.isDarwinABI();
14297 
14298   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
14299       (!isPPC64 && VT != MVT::i32))
14300     report_fatal_error("Invalid register global variable type");
14301 
14302   bool is64Bit = isPPC64 && VT == MVT::i64;
14303   unsigned Reg = StringSwitch<unsigned>(RegName)
14304                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14305                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
14306                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
14307                                   (is64Bit ? PPC::X13 : PPC::R13))
14308                    .Default(0);
14309 
14310   if (Reg)
14311     return Reg;
14312   report_fatal_error("Invalid register name global variable");
14313 }
14314 
14315 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14316   // 32-bit SVR4 ABI access everything as got-indirect.
14317   if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
14318     return true;
14319 
14320   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14321   // If it is small or large code model, module locals are accessed
14322   // indirectly by loading their address from .toc/.got. The difference
14323   // is that for large code model we have ADDISTocHa + LDtocL and for
14324   // small code model we simply have LDtoc.
14325   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14326     return true;
14327 
14328   // JumpTable and BlockAddress are accessed as got-indirect.
14329   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14330     return true;
14331 
14332   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
14333     const GlobalValue *GV = G->getGlobal();
14334     unsigned char GVFlags = Subtarget.classifyGlobalReference(GV);
14335     // The NLP flag indicates that a global access has to use an
14336     // extra indirection.
14337     if (GVFlags & PPCII::MO_NLP_FLAG)
14338       return true;
14339   }
14340 
14341   return false;
14342 }
14343 
14344 bool
14345 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14346   // The PowerPC target isn't yet aware of offsets.
14347   return false;
14348 }
14349 
14350 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14351                                            const CallInst &I,
14352                                            MachineFunction &MF,
14353                                            unsigned Intrinsic) const {
14354   switch (Intrinsic) {
14355   case Intrinsic::ppc_qpx_qvlfd:
14356   case Intrinsic::ppc_qpx_qvlfs:
14357   case Intrinsic::ppc_qpx_qvlfcd:
14358   case Intrinsic::ppc_qpx_qvlfcs:
14359   case Intrinsic::ppc_qpx_qvlfiwa:
14360   case Intrinsic::ppc_qpx_qvlfiwz:
14361   case Intrinsic::ppc_altivec_lvx:
14362   case Intrinsic::ppc_altivec_lvxl:
14363   case Intrinsic::ppc_altivec_lvebx:
14364   case Intrinsic::ppc_altivec_lvehx:
14365   case Intrinsic::ppc_altivec_lvewx:
14366   case Intrinsic::ppc_vsx_lxvd2x:
14367   case Intrinsic::ppc_vsx_lxvw4x: {
14368     EVT VT;
14369     switch (Intrinsic) {
14370     case Intrinsic::ppc_altivec_lvebx:
14371       VT = MVT::i8;
14372       break;
14373     case Intrinsic::ppc_altivec_lvehx:
14374       VT = MVT::i16;
14375       break;
14376     case Intrinsic::ppc_altivec_lvewx:
14377       VT = MVT::i32;
14378       break;
14379     case Intrinsic::ppc_vsx_lxvd2x:
14380       VT = MVT::v2f64;
14381       break;
14382     case Intrinsic::ppc_qpx_qvlfd:
14383       VT = MVT::v4f64;
14384       break;
14385     case Intrinsic::ppc_qpx_qvlfs:
14386       VT = MVT::v4f32;
14387       break;
14388     case Intrinsic::ppc_qpx_qvlfcd:
14389       VT = MVT::v2f64;
14390       break;
14391     case Intrinsic::ppc_qpx_qvlfcs:
14392       VT = MVT::v2f32;
14393       break;
14394     default:
14395       VT = MVT::v4i32;
14396       break;
14397     }
14398 
14399     Info.opc = ISD::INTRINSIC_W_CHAIN;
14400     Info.memVT = VT;
14401     Info.ptrVal = I.getArgOperand(0);
14402     Info.offset = -VT.getStoreSize()+1;
14403     Info.size = 2*VT.getStoreSize()-1;
14404     Info.align = 1;
14405     Info.flags = MachineMemOperand::MOLoad;
14406     return true;
14407   }
14408   case Intrinsic::ppc_qpx_qvlfda:
14409   case Intrinsic::ppc_qpx_qvlfsa:
14410   case Intrinsic::ppc_qpx_qvlfcda:
14411   case Intrinsic::ppc_qpx_qvlfcsa:
14412   case Intrinsic::ppc_qpx_qvlfiwaa:
14413   case Intrinsic::ppc_qpx_qvlfiwza: {
14414     EVT VT;
14415     switch (Intrinsic) {
14416     case Intrinsic::ppc_qpx_qvlfda:
14417       VT = MVT::v4f64;
14418       break;
14419     case Intrinsic::ppc_qpx_qvlfsa:
14420       VT = MVT::v4f32;
14421       break;
14422     case Intrinsic::ppc_qpx_qvlfcda:
14423       VT = MVT::v2f64;
14424       break;
14425     case Intrinsic::ppc_qpx_qvlfcsa:
14426       VT = MVT::v2f32;
14427       break;
14428     default:
14429       VT = MVT::v4i32;
14430       break;
14431     }
14432 
14433     Info.opc = ISD::INTRINSIC_W_CHAIN;
14434     Info.memVT = VT;
14435     Info.ptrVal = I.getArgOperand(0);
14436     Info.offset = 0;
14437     Info.size = VT.getStoreSize();
14438     Info.align = 1;
14439     Info.flags = MachineMemOperand::MOLoad;
14440     return true;
14441   }
14442   case Intrinsic::ppc_qpx_qvstfd:
14443   case Intrinsic::ppc_qpx_qvstfs:
14444   case Intrinsic::ppc_qpx_qvstfcd:
14445   case Intrinsic::ppc_qpx_qvstfcs:
14446   case Intrinsic::ppc_qpx_qvstfiw:
14447   case Intrinsic::ppc_altivec_stvx:
14448   case Intrinsic::ppc_altivec_stvxl:
14449   case Intrinsic::ppc_altivec_stvebx:
14450   case Intrinsic::ppc_altivec_stvehx:
14451   case Intrinsic::ppc_altivec_stvewx:
14452   case Intrinsic::ppc_vsx_stxvd2x:
14453   case Intrinsic::ppc_vsx_stxvw4x: {
14454     EVT VT;
14455     switch (Intrinsic) {
14456     case Intrinsic::ppc_altivec_stvebx:
14457       VT = MVT::i8;
14458       break;
14459     case Intrinsic::ppc_altivec_stvehx:
14460       VT = MVT::i16;
14461       break;
14462     case Intrinsic::ppc_altivec_stvewx:
14463       VT = MVT::i32;
14464       break;
14465     case Intrinsic::ppc_vsx_stxvd2x:
14466       VT = MVT::v2f64;
14467       break;
14468     case Intrinsic::ppc_qpx_qvstfd:
14469       VT = MVT::v4f64;
14470       break;
14471     case Intrinsic::ppc_qpx_qvstfs:
14472       VT = MVT::v4f32;
14473       break;
14474     case Intrinsic::ppc_qpx_qvstfcd:
14475       VT = MVT::v2f64;
14476       break;
14477     case Intrinsic::ppc_qpx_qvstfcs:
14478       VT = MVT::v2f32;
14479       break;
14480     default:
14481       VT = MVT::v4i32;
14482       break;
14483     }
14484 
14485     Info.opc = ISD::INTRINSIC_VOID;
14486     Info.memVT = VT;
14487     Info.ptrVal = I.getArgOperand(1);
14488     Info.offset = -VT.getStoreSize()+1;
14489     Info.size = 2*VT.getStoreSize()-1;
14490     Info.align = 1;
14491     Info.flags = MachineMemOperand::MOStore;
14492     return true;
14493   }
14494   case Intrinsic::ppc_qpx_qvstfda:
14495   case Intrinsic::ppc_qpx_qvstfsa:
14496   case Intrinsic::ppc_qpx_qvstfcda:
14497   case Intrinsic::ppc_qpx_qvstfcsa:
14498   case Intrinsic::ppc_qpx_qvstfiwa: {
14499     EVT VT;
14500     switch (Intrinsic) {
14501     case Intrinsic::ppc_qpx_qvstfda:
14502       VT = MVT::v4f64;
14503       break;
14504     case Intrinsic::ppc_qpx_qvstfsa:
14505       VT = MVT::v4f32;
14506       break;
14507     case Intrinsic::ppc_qpx_qvstfcda:
14508       VT = MVT::v2f64;
14509       break;
14510     case Intrinsic::ppc_qpx_qvstfcsa:
14511       VT = MVT::v2f32;
14512       break;
14513     default:
14514       VT = MVT::v4i32;
14515       break;
14516     }
14517 
14518     Info.opc = ISD::INTRINSIC_VOID;
14519     Info.memVT = VT;
14520     Info.ptrVal = I.getArgOperand(1);
14521     Info.offset = 0;
14522     Info.size = VT.getStoreSize();
14523     Info.align = 1;
14524     Info.flags = MachineMemOperand::MOStore;
14525     return true;
14526   }
14527   default:
14528     break;
14529   }
14530 
14531   return false;
14532 }
14533 
14534 /// getOptimalMemOpType - Returns the target specific optimal type for load
14535 /// and store operations as a result of memset, memcpy, and memmove
14536 /// lowering. If DstAlign is zero that means it's safe to destination
14537 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
14538 /// means there isn't a need to check it against alignment requirement,
14539 /// probably because the source does not need to be loaded. If 'IsMemset' is
14540 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
14541 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
14542 /// source is constant so it does not need to be loaded.
14543 /// It returns EVT::Other if the type should be determined using generic
14544 /// target-independent logic.
14545 EVT PPCTargetLowering::getOptimalMemOpType(
14546     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14547     bool ZeroMemset, bool MemcpyStrSrc,
14548     const AttributeList &FuncAttributes) const {
14549   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
14550     // When expanding a memset, require at least two QPX instructions to cover
14551     // the cost of loading the value to be stored from the constant pool.
14552     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
14553        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
14554         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14555       return MVT::v4f64;
14556     }
14557 
14558     // We should use Altivec/VSX loads and stores when available. For unaligned
14559     // addresses, unaligned VSX loads are only fast starting with the P8.
14560     if (Subtarget.hasAltivec() && Size >= 16 &&
14561         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
14562          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
14563       return MVT::v4i32;
14564   }
14565 
14566   if (Subtarget.isPPC64()) {
14567     return MVT::i64;
14568   }
14569 
14570   return MVT::i32;
14571 }
14572 
14573 /// Returns true if it is beneficial to convert a load of a constant
14574 /// to just the constant itself.
14575 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14576                                                           Type *Ty) const {
14577   assert(Ty->isIntegerTy());
14578 
14579   unsigned BitSize = Ty->getPrimitiveSizeInBits();
14580   return !(BitSize == 0 || BitSize > 64);
14581 }
14582 
14583 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14584   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14585     return false;
14586   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14587   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14588   return NumBits1 == 64 && NumBits2 == 32;
14589 }
14590 
14591 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14592   if (!VT1.isInteger() || !VT2.isInteger())
14593     return false;
14594   unsigned NumBits1 = VT1.getSizeInBits();
14595   unsigned NumBits2 = VT2.getSizeInBits();
14596   return NumBits1 == 64 && NumBits2 == 32;
14597 }
14598 
14599 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14600   // Generally speaking, zexts are not free, but they are free when they can be
14601   // folded with other operations.
14602   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
14603     EVT MemVT = LD->getMemoryVT();
14604     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
14605          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
14606         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
14607          LD->getExtensionType() == ISD::ZEXTLOAD))
14608       return true;
14609   }
14610 
14611   // FIXME: Add other cases...
14612   //  - 32-bit shifts with a zext to i64
14613   //  - zext after ctlz, bswap, etc.
14614   //  - zext after and by a constant mask
14615 
14616   return TargetLowering::isZExtFree(Val, VT2);
14617 }
14618 
14619 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
14620   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
14621          "invalid fpext types");
14622   // Extending to float128 is not free.
14623   if (DestVT == MVT::f128)
14624     return false;
14625   return true;
14626 }
14627 
14628 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14629   return isInt<16>(Imm) || isUInt<16>(Imm);
14630 }
14631 
14632 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14633   return isInt<16>(Imm) || isUInt<16>(Imm);
14634 }
14635 
14636 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
14637                                                        unsigned,
14638                                                        unsigned,
14639                                                        MachineMemOperand::Flags,
14640                                                        bool *Fast) const {
14641   if (DisablePPCUnaligned)
14642     return false;
14643 
14644   // PowerPC supports unaligned memory access for simple non-vector types.
14645   // Although accessing unaligned addresses is not as efficient as accessing
14646   // aligned addresses, it is generally more efficient than manual expansion,
14647   // and generally only traps for software emulation when crossing page
14648   // boundaries.
14649 
14650   if (!VT.isSimple())
14651     return false;
14652 
14653   if (VT.getSimpleVT().isVector()) {
14654     if (Subtarget.hasVSX()) {
14655       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
14656           VT != MVT::v4f32 && VT != MVT::v4i32)
14657         return false;
14658     } else {
14659       return false;
14660     }
14661   }
14662 
14663   if (VT == MVT::ppcf128)
14664     return false;
14665 
14666   if (Fast)
14667     *Fast = true;
14668 
14669   return true;
14670 }
14671 
14672 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14673   VT = VT.getScalarType();
14674 
14675   if (!VT.isSimple())
14676     return false;
14677 
14678   switch (VT.getSimpleVT().SimpleTy) {
14679   case MVT::f32:
14680   case MVT::f64:
14681     return true;
14682   case MVT::f128:
14683     return (EnableQuadPrecision && Subtarget.hasP9Vector());
14684   default:
14685     break;
14686   }
14687 
14688   return false;
14689 }
14690 
14691 const MCPhysReg *
14692 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
14693   // LR is a callee-save register, but we must treat it as clobbered by any call
14694   // site. Hence we include LR in the scratch registers, which are in turn added
14695   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
14696   // to CTR, which is used by any indirect call.
14697   static const MCPhysReg ScratchRegs[] = {
14698     PPC::X12, PPC::LR8, PPC::CTR8, 0
14699   };
14700 
14701   return ScratchRegs;
14702 }
14703 
14704 unsigned PPCTargetLowering::getExceptionPointerRegister(
14705     const Constant *PersonalityFn) const {
14706   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
14707 }
14708 
14709 unsigned PPCTargetLowering::getExceptionSelectorRegister(
14710     const Constant *PersonalityFn) const {
14711   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
14712 }
14713 
14714 bool
14715 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
14716                      EVT VT , unsigned DefinedValues) const {
14717   if (VT == MVT::v2i64)
14718     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
14719 
14720   if (Subtarget.hasVSX() || Subtarget.hasQPX())
14721     return true;
14722 
14723   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
14724 }
14725 
14726 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
14727   if (DisableILPPref || Subtarget.enableMachineScheduler())
14728     return TargetLowering::getSchedulingPreference(N);
14729 
14730   return Sched::ILP;
14731 }
14732 
14733 // Create a fast isel object.
14734 FastISel *
14735 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
14736                                   const TargetLibraryInfo *LibInfo) const {
14737   return PPC::createFastISel(FuncInfo, LibInfo);
14738 }
14739 
14740 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14741   if (Subtarget.isDarwinABI()) return;
14742   if (!Subtarget.isPPC64()) return;
14743 
14744   // Update IsSplitCSR in PPCFunctionInfo
14745   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
14746   PFI->setIsSplitCSR(true);
14747 }
14748 
14749 void PPCTargetLowering::insertCopiesSplitCSR(
14750   MachineBasicBlock *Entry,
14751   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14752   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
14753   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14754   if (!IStart)
14755     return;
14756 
14757   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14758   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14759   MachineBasicBlock::iterator MBBI = Entry->begin();
14760   for (const MCPhysReg *I = IStart; *I; ++I) {
14761     const TargetRegisterClass *RC = nullptr;
14762     if (PPC::G8RCRegClass.contains(*I))
14763       RC = &PPC::G8RCRegClass;
14764     else if (PPC::F8RCRegClass.contains(*I))
14765       RC = &PPC::F8RCRegClass;
14766     else if (PPC::CRRCRegClass.contains(*I))
14767       RC = &PPC::CRRCRegClass;
14768     else if (PPC::VRRCRegClass.contains(*I))
14769       RC = &PPC::VRRCRegClass;
14770     else
14771       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14772 
14773     unsigned NewVR = MRI->createVirtualRegister(RC);
14774     // Create copy from CSR to a virtual register.
14775     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14776     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14777     // nounwind. If we want to generalize this later, we may need to emit
14778     // CFI pseudo-instructions.
14779     assert(Entry->getParent()->getFunction().hasFnAttribute(
14780              Attribute::NoUnwind) &&
14781            "Function should be nounwind in insertCopiesSplitCSR!");
14782     Entry->addLiveIn(*I);
14783     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14784       .addReg(*I);
14785 
14786     // Insert the copy-back instructions right before the terminator.
14787     for (auto *Exit : Exits)
14788       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14789               TII->get(TargetOpcode::COPY), *I)
14790         .addReg(NewVR);
14791   }
14792 }
14793 
14794 // Override to enable LOAD_STACK_GUARD lowering on Linux.
14795 bool PPCTargetLowering::useLoadStackGuardNode() const {
14796   if (!Subtarget.isTargetLinux())
14797     return TargetLowering::useLoadStackGuardNode();
14798   return true;
14799 }
14800 
14801 // Override to disable global variable loading on Linux.
14802 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
14803   if (!Subtarget.isTargetLinux())
14804     return TargetLowering::insertSSPDeclarations(M);
14805 }
14806 
14807 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
14808                                      bool ForCodeSize) const {
14809   if (!VT.isSimple() || !Subtarget.hasVSX())
14810     return false;
14811 
14812   switch(VT.getSimpleVT().SimpleTy) {
14813   default:
14814     // For FP types that are currently not supported by PPC backend, return
14815     // false. Examples: f16, f80.
14816     return false;
14817   case MVT::f32:
14818   case MVT::f64:
14819   case MVT::ppcf128:
14820     return Imm.isPosZero();
14821   }
14822 }
14823 
14824 // For vector shift operation op, fold
14825 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
14826 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
14827                                   SelectionDAG &DAG) {
14828   SDValue N0 = N->getOperand(0);
14829   SDValue N1 = N->getOperand(1);
14830   EVT VT = N0.getValueType();
14831   unsigned OpSizeInBits = VT.getScalarSizeInBits();
14832   unsigned Opcode = N->getOpcode();
14833   unsigned TargetOpcode;
14834 
14835   switch (Opcode) {
14836   default:
14837     llvm_unreachable("Unexpected shift operation");
14838   case ISD::SHL:
14839     TargetOpcode = PPCISD::SHL;
14840     break;
14841   case ISD::SRL:
14842     TargetOpcode = PPCISD::SRL;
14843     break;
14844   case ISD::SRA:
14845     TargetOpcode = PPCISD::SRA;
14846     break;
14847   }
14848 
14849   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
14850       N1->getOpcode() == ISD::AND)
14851     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
14852       if (Mask->getZExtValue() == OpSizeInBits - 1)
14853         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
14854 
14855   return SDValue();
14856 }
14857 
14858 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
14859   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14860     return Value;
14861 
14862   SDValue N0 = N->getOperand(0);
14863   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
14864   if (!Subtarget.isISA3_0() ||
14865       N0.getOpcode() != ISD::SIGN_EXTEND ||
14866       N0.getOperand(0).getValueType() != MVT::i32 ||
14867       CN1 == nullptr || N->getValueType(0) != MVT::i64)
14868     return SDValue();
14869 
14870   // We can't save an operation here if the value is already extended, and
14871   // the existing shift is easier to combine.
14872   SDValue ExtsSrc = N0.getOperand(0);
14873   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
14874       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
14875     return SDValue();
14876 
14877   SDLoc DL(N0);
14878   SDValue ShiftBy = SDValue(CN1, 0);
14879   // We want the shift amount to be i32 on the extswli, but the shift could
14880   // have an i64.
14881   if (ShiftBy.getValueType() == MVT::i64)
14882     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
14883 
14884   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
14885                          ShiftBy);
14886 }
14887 
14888 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
14889   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14890     return Value;
14891 
14892   return SDValue();
14893 }
14894 
14895 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
14896   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14897     return Value;
14898 
14899   return SDValue();
14900 }
14901 
14902 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
14903 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
14904 // When C is zero, the equation (addi Z, -C) can be simplified to Z
14905 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
14906 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
14907                                  const PPCSubtarget &Subtarget) {
14908   if (!Subtarget.isPPC64())
14909     return SDValue();
14910 
14911   SDValue LHS = N->getOperand(0);
14912   SDValue RHS = N->getOperand(1);
14913 
14914   auto isZextOfCompareWithConstant = [](SDValue Op) {
14915     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
14916         Op.getValueType() != MVT::i64)
14917       return false;
14918 
14919     SDValue Cmp = Op.getOperand(0);
14920     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
14921         Cmp.getOperand(0).getValueType() != MVT::i64)
14922       return false;
14923 
14924     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
14925       int64_t NegConstant = 0 - Constant->getSExtValue();
14926       // Due to the limitations of the addi instruction,
14927       // -C is required to be [-32768, 32767].
14928       return isInt<16>(NegConstant);
14929     }
14930 
14931     return false;
14932   };
14933 
14934   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
14935   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
14936 
14937   // If there is a pattern, canonicalize a zext operand to the RHS.
14938   if (LHSHasPattern && !RHSHasPattern)
14939     std::swap(LHS, RHS);
14940   else if (!LHSHasPattern && !RHSHasPattern)
14941     return SDValue();
14942 
14943   SDLoc DL(N);
14944   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
14945   SDValue Cmp = RHS.getOperand(0);
14946   SDValue Z = Cmp.getOperand(0);
14947   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
14948 
14949   assert(Constant && "Constant Should not be a null pointer.");
14950   int64_t NegConstant = 0 - Constant->getSExtValue();
14951 
14952   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
14953   default: break;
14954   case ISD::SETNE: {
14955     //                                 when C == 0
14956     //                             --> addze X, (addic Z, -1).carry
14957     //                            /
14958     // add X, (zext(setne Z, C))--
14959     //                            \    when -32768 <= -C <= 32767 && C != 0
14960     //                             --> addze X, (addic (addi Z, -C), -1).carry
14961     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
14962                               DAG.getConstant(NegConstant, DL, MVT::i64));
14963     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
14964     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
14965                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
14966     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
14967                        SDValue(Addc.getNode(), 1));
14968     }
14969   case ISD::SETEQ: {
14970     //                                 when C == 0
14971     //                             --> addze X, (subfic Z, 0).carry
14972     //                            /
14973     // add X, (zext(sete  Z, C))--
14974     //                            \    when -32768 <= -C <= 32767 && C != 0
14975     //                             --> addze X, (subfic (addi Z, -C), 0).carry
14976     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
14977                               DAG.getConstant(NegConstant, DL, MVT::i64));
14978     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
14979     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
14980                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
14981     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
14982                        SDValue(Subc.getNode(), 1));
14983     }
14984   }
14985 
14986   return SDValue();
14987 }
14988 
14989 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
14990   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
14991     return Value;
14992 
14993   return SDValue();
14994 }
14995 
14996 // Detect TRUNCATE operations on bitcasts of float128 values.
14997 // What we are looking for here is the situtation where we extract a subset
14998 // of bits from a 128 bit float.
14999 // This can be of two forms:
15000 // 1) BITCAST of f128 feeding TRUNCATE
15001 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15002 // The reason this is required is because we do not have a legal i128 type
15003 // and so we want to prevent having to store the f128 and then reload part
15004 // of it.
15005 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15006                                            DAGCombinerInfo &DCI) const {
15007   // If we are using CRBits then try that first.
15008   if (Subtarget.useCRBits()) {
15009     // Check if CRBits did anything and return that if it did.
15010     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15011       return CRTruncValue;
15012   }
15013 
15014   SDLoc dl(N);
15015   SDValue Op0 = N->getOperand(0);
15016 
15017   // Looking for a truncate of i128 to i64.
15018   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15019     return SDValue();
15020 
15021   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15022 
15023   // SRL feeding TRUNCATE.
15024   if (Op0.getOpcode() == ISD::SRL) {
15025     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15026     // The right shift has to be by 64 bits.
15027     if (!ConstNode || ConstNode->getZExtValue() != 64)
15028       return SDValue();
15029 
15030     // Switch the element number to extract.
15031     EltToExtract = EltToExtract ? 0 : 1;
15032     // Update Op0 past the SRL.
15033     Op0 = Op0.getOperand(0);
15034   }
15035 
15036   // BITCAST feeding a TRUNCATE possibly via SRL.
15037   if (Op0.getOpcode() == ISD::BITCAST &&
15038       Op0.getValueType() == MVT::i128 &&
15039       Op0.getOperand(0).getValueType() == MVT::f128) {
15040     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15041     return DCI.DAG.getNode(
15042         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15043         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15044   }
15045   return SDValue();
15046 }
15047 
15048 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15049   SelectionDAG &DAG = DCI.DAG;
15050 
15051   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15052   if (!ConstOpOrElement)
15053     return SDValue();
15054 
15055   // An imul is usually smaller than the alternative sequence for legal type.
15056   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15057       isOperationLegal(ISD::MUL, N->getValueType(0)))
15058     return SDValue();
15059 
15060   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15061     switch (this->Subtarget.getDarwinDirective()) {
15062     default:
15063       // TODO: enhance the condition for subtarget before pwr8
15064       return false;
15065     case PPC::DIR_PWR8:
15066       //  type        mul     add    shl
15067       // scalar        4       1      1
15068       // vector        7       2      2
15069       return true;
15070     case PPC::DIR_PWR9:
15071       //  type        mul     add    shl
15072       // scalar        5       2      2
15073       // vector        7       2      2
15074 
15075       // The cycle RATIO of related operations are showed as a table above.
15076       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15077       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15078       // are 4, it is always profitable; but for 3 instrs patterns
15079       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15080       // So we should only do it for vector type.
15081       return IsAddOne && IsNeg ? VT.isVector() : true;
15082     }
15083   };
15084 
15085   EVT VT = N->getValueType(0);
15086   SDLoc DL(N);
15087 
15088   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15089   bool IsNeg = MulAmt.isNegative();
15090   APInt MulAmtAbs = MulAmt.abs();
15091 
15092   if ((MulAmtAbs - 1).isPowerOf2()) {
15093     // (mul x, 2^N + 1) => (add (shl x, N), x)
15094     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15095 
15096     if (!IsProfitable(IsNeg, true, VT))
15097       return SDValue();
15098 
15099     SDValue Op0 = N->getOperand(0);
15100     SDValue Op1 =
15101         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15102                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15103     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15104 
15105     if (!IsNeg)
15106       return Res;
15107 
15108     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15109   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15110     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15111     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15112 
15113     if (!IsProfitable(IsNeg, false, VT))
15114       return SDValue();
15115 
15116     SDValue Op0 = N->getOperand(0);
15117     SDValue Op1 =
15118         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15119                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15120 
15121     if (!IsNeg)
15122       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15123     else
15124       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15125 
15126   } else {
15127     return SDValue();
15128   }
15129 }
15130 
15131 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15132   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15133   if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64())
15134     return false;
15135 
15136   // If not a tail call then no need to proceed.
15137   if (!CI->isTailCall())
15138     return false;
15139 
15140   // If tail calls are disabled for the caller then we are done.
15141   const Function *Caller = CI->getParent()->getParent();
15142   auto Attr = Caller->getFnAttribute("disable-tail-calls");
15143   if (Attr.getValueAsString() == "true")
15144     return false;
15145 
15146   // If sibling calls have been disabled and tail-calls aren't guaranteed
15147   // there is no reason to duplicate.
15148   auto &TM = getTargetMachine();
15149   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15150     return false;
15151 
15152   // Can't tail call a function called indirectly, or if it has variadic args.
15153   const Function *Callee = CI->getCalledFunction();
15154   if (!Callee || Callee->isVarArg())
15155     return false;
15156 
15157   // Make sure the callee and caller calling conventions are eligible for tco.
15158   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15159                                            CI->getCallingConv()))
15160       return false;
15161 
15162   // If the function is local then we have a good chance at tail-calling it
15163   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15164 }
15165 
15166 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15167   if (!Subtarget.hasVSX())
15168     return false;
15169   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15170     return true;
15171   return VT == MVT::f32 || VT == MVT::f64 ||
15172     VT == MVT::v4f32 || VT == MVT::v2f64;
15173 }
15174 
15175 bool PPCTargetLowering::
15176 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15177   const Value *Mask = AndI.getOperand(1);
15178   // If the mask is suitable for andi. or andis. we should sink the and.
15179   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15180     // Can't handle constants wider than 64-bits.
15181     if (CI->getBitWidth() > 64)
15182       return false;
15183     int64_t ConstVal = CI->getZExtValue();
15184     return isUInt<16>(ConstVal) ||
15185       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15186   }
15187 
15188   // For non-constant masks, we can always use the record-form and.
15189   return true;
15190 }
15191 
15192 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15193 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15194 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15195 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15196 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15197 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15198   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15199   assert(Subtarget.hasP9Altivec() &&
15200          "Only combine this when P9 altivec supported!");
15201   EVT VT = N->getValueType(0);
15202   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15203     return SDValue();
15204 
15205   SelectionDAG &DAG = DCI.DAG;
15206   SDLoc dl(N);
15207   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15208     // Even for signed integers, if it's known to be positive (as signed
15209     // integer) due to zero-extended inputs.
15210     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15211     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15212     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15213          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15214         (SubOpcd1 == ISD::ZERO_EXTEND ||
15215          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15216       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15217                          N->getOperand(0)->getOperand(0),
15218                          N->getOperand(0)->getOperand(1),
15219                          DAG.getTargetConstant(0, dl, MVT::i32));
15220     }
15221 
15222     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15223     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15224         N->getOperand(0).hasOneUse()) {
15225       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15226                          N->getOperand(0)->getOperand(0),
15227                          N->getOperand(0)->getOperand(1),
15228                          DAG.getTargetConstant(1, dl, MVT::i32));
15229     }
15230   }
15231 
15232   return SDValue();
15233 }
15234 
15235 // For type v4i32/v8ii16/v16i8, transform
15236 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15237 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15238 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15239 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15240 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15241                                           DAGCombinerInfo &DCI) const {
15242   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15243   assert(Subtarget.hasP9Altivec() &&
15244          "Only combine this when P9 altivec supported!");
15245 
15246   SelectionDAG &DAG = DCI.DAG;
15247   SDLoc dl(N);
15248   SDValue Cond = N->getOperand(0);
15249   SDValue TrueOpnd = N->getOperand(1);
15250   SDValue FalseOpnd = N->getOperand(2);
15251   EVT VT = N->getOperand(1).getValueType();
15252 
15253   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15254       FalseOpnd.getOpcode() != ISD::SUB)
15255     return SDValue();
15256 
15257   // ABSD only available for type v4i32/v8i16/v16i8
15258   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15259     return SDValue();
15260 
15261   // At least to save one more dependent computation
15262   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15263     return SDValue();
15264 
15265   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15266 
15267   // Can only handle unsigned comparison here
15268   switch (CC) {
15269   default:
15270     return SDValue();
15271   case ISD::SETUGT:
15272   case ISD::SETUGE:
15273     break;
15274   case ISD::SETULT:
15275   case ISD::SETULE:
15276     std::swap(TrueOpnd, FalseOpnd);
15277     break;
15278   }
15279 
15280   SDValue CmpOpnd1 = Cond.getOperand(0);
15281   SDValue CmpOpnd2 = Cond.getOperand(1);
15282 
15283   // SETCC CmpOpnd1 CmpOpnd2 cond
15284   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15285   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15286   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15287       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15288       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15289       FalseOpnd.getOperand(1) == CmpOpnd1) {
15290     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15291                        CmpOpnd1, CmpOpnd2,
15292                        DAG.getTargetConstant(0, dl, MVT::i32));
15293   }
15294 
15295   return SDValue();
15296 }
15297