1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSectionXCOFF.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
124 STATISTIC(NumTailCalls, "Number of tail calls");
125 STATISTIC(NumSiblingCalls, "Number of sibling calls");
126 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
127 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
128 
129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
130 
131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
132 
133 // FIXME: Remove this once the bug has been fixed!
134 extern cl::opt<bool> ANDIGlueBug;
135 
136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
137                                      const PPCSubtarget &STI)
138     : TargetLowering(TM), Subtarget(STI) {
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 ? Align(8) : Align(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::GPRCRegClass);
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   if (Subtarget.isISA3_0()) {
170     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
171     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
172     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
173     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
174   } else {
175     // No extending loads from f16 or HW conversions back and forth.
176     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
177     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
178     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
179     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
180     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
181     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
182     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
183     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
184   }
185 
186   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
187 
188   // PowerPC has pre-inc load and store's.
189   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
190   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
191   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
192   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
193   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
194   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
195   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
196   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
197   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
198   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
199   if (!Subtarget.hasSPE()) {
200     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
201     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
202     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
203     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
204   }
205 
206   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
207   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
208   for (MVT VT : ScalarIntVTs) {
209     setOperationAction(ISD::ADDC, VT, Legal);
210     setOperationAction(ISD::ADDE, VT, Legal);
211     setOperationAction(ISD::SUBC, VT, Legal);
212     setOperationAction(ISD::SUBE, VT, Legal);
213   }
214 
215   if (Subtarget.useCRBits()) {
216     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
217 
218     if (isPPC64 || Subtarget.hasFPCVT()) {
219       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
220       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
221                          isPPC64 ? MVT::i64 : MVT::i32);
222       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
223       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
224                         isPPC64 ? MVT::i64 : MVT::i32);
225     } else {
226       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
227       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
228     }
229 
230     // PowerPC does not support direct load/store of condition registers.
231     setOperationAction(ISD::LOAD, MVT::i1, Custom);
232     setOperationAction(ISD::STORE, MVT::i1, Custom);
233 
234     // FIXME: Remove this once the ANDI glue bug is fixed:
235     if (ANDIGlueBug)
236       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
237 
238     for (MVT VT : MVT::integer_valuetypes()) {
239       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
240       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
241       setTruncStoreAction(VT, MVT::i1, Expand);
242     }
243 
244     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
245   }
246 
247   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
248   // PPC (the libcall is not available).
249   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
250   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
251 
252   // We do not currently implement these libm ops for PowerPC.
253   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
254   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
255   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
256   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
257   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
258   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
259 
260   // PowerPC has no SREM/UREM instructions unless we are on P9
261   // On P9 we may use a hardware instruction to compute the remainder.
262   // When the result of both the remainder and the division is required it is
263   // more efficient to compute the remainder from the result of the division
264   // rather than use the remainder instruction. The instructions are legalized
265   // directly because the DivRemPairsPass performs the transformation at the IR
266   // level.
267   if (Subtarget.isISA3_0()) {
268     setOperationAction(ISD::SREM, MVT::i32, Legal);
269     setOperationAction(ISD::UREM, MVT::i32, Legal);
270     setOperationAction(ISD::SREM, MVT::i64, Legal);
271     setOperationAction(ISD::UREM, MVT::i64, Legal);
272   } else {
273     setOperationAction(ISD::SREM, MVT::i32, Expand);
274     setOperationAction(ISD::UREM, MVT::i32, Expand);
275     setOperationAction(ISD::SREM, MVT::i64, Expand);
276     setOperationAction(ISD::UREM, MVT::i64, Expand);
277   }
278 
279   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
280   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
281   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
282   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
283   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
284   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
285   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
287   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
288 
289   // Handle constrained floating-point operations of scalar.
290   // TODO: Handle SPE specific operation.
291   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
292   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
293   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
294   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
295   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
296   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
297 
298   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
299   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
300   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
301   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
302   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
303   if (Subtarget.hasVSX())
304     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal);
305 
306   if (Subtarget.hasFSQRT()) {
307     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
308     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
309   }
310 
311   if (Subtarget.hasFPRND()) {
312     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
313     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
314     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
315     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
316 
317     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
318     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
319     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
320     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
321   }
322 
323   // We don't support sin/cos/sqrt/fmod/pow
324   setOperationAction(ISD::FSIN , MVT::f64, Expand);
325   setOperationAction(ISD::FCOS , MVT::f64, Expand);
326   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
327   setOperationAction(ISD::FREM , MVT::f64, Expand);
328   setOperationAction(ISD::FPOW , MVT::f64, Expand);
329   setOperationAction(ISD::FSIN , MVT::f32, Expand);
330   setOperationAction(ISD::FCOS , MVT::f32, Expand);
331   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
332   setOperationAction(ISD::FREM , MVT::f32, Expand);
333   setOperationAction(ISD::FPOW , MVT::f32, Expand);
334   if (Subtarget.hasSPE()) {
335     setOperationAction(ISD::FMA  , MVT::f64, Expand);
336     setOperationAction(ISD::FMA  , MVT::f32, Expand);
337   } else {
338     setOperationAction(ISD::FMA  , MVT::f64, Legal);
339     setOperationAction(ISD::FMA  , MVT::f32, Legal);
340   }
341 
342   if (Subtarget.hasSPE())
343     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
344 
345   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
346 
347   // If we're enabling GP optimizations, use hardware square root
348   if (!Subtarget.hasFSQRT() &&
349       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
350         Subtarget.hasFRE()))
351     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
352 
353   if (!Subtarget.hasFSQRT() &&
354       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
355         Subtarget.hasFRES()))
356     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
357 
358   if (Subtarget.hasFCPSGN()) {
359     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
360     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
361   } else {
362     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
363     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
364   }
365 
366   if (Subtarget.hasFPRND()) {
367     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
368     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
369     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
370     setOperationAction(ISD::FROUND, MVT::f64, Legal);
371 
372     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
373     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
374     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
375     setOperationAction(ISD::FROUND, MVT::f32, Legal);
376   }
377 
378   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
379   // to speed up scalar BSWAP64.
380   // CTPOP or CTTZ were introduced in P8/P9 respectively
381   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
382   if (Subtarget.hasP9Vector())
383     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
384   else
385     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
386   if (Subtarget.isISA3_0()) {
387     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
388     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
389   } else {
390     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
391     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
392   }
393 
394   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
395     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
396     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
397   } else {
398     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
399     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
400   }
401 
402   // PowerPC does not have ROTR
403   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
404   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
405 
406   if (!Subtarget.useCRBits()) {
407     // PowerPC does not have Select
408     setOperationAction(ISD::SELECT, MVT::i32, Expand);
409     setOperationAction(ISD::SELECT, MVT::i64, Expand);
410     setOperationAction(ISD::SELECT, MVT::f32, Expand);
411     setOperationAction(ISD::SELECT, MVT::f64, Expand);
412   }
413 
414   // PowerPC wants to turn select_cc of FP into fsel when possible.
415   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
416   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
417 
418   // PowerPC wants to optimize integer setcc a bit
419   if (!Subtarget.useCRBits())
420     setOperationAction(ISD::SETCC, MVT::i32, Custom);
421 
422   // PowerPC does not have BRCOND which requires SetCC
423   if (!Subtarget.useCRBits())
424     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
425 
426   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
427 
428   if (Subtarget.hasSPE()) {
429     // SPE has built-in conversions
430     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
431     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
432     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
433     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
434     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
435     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
436   } else {
437     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
438     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
439 
440     // PowerPC does not have [U|S]INT_TO_FP
441     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
442     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
443   }
444 
445   if (Subtarget.hasDirectMove() && isPPC64) {
446     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
447     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
448     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
449     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
450     if (TM.Options.UnsafeFPMath) {
451       setOperationAction(ISD::LRINT, MVT::f64, Legal);
452       setOperationAction(ISD::LRINT, MVT::f32, Legal);
453       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
454       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
455       setOperationAction(ISD::LROUND, MVT::f64, Legal);
456       setOperationAction(ISD::LROUND, MVT::f32, Legal);
457       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
458       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
459     }
460   } else {
461     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
462     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
463     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
464     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
465   }
466 
467   // We cannot sextinreg(i1).  Expand to shifts.
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
469 
470   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
471   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
472   // support continuation, user-level threading, and etc.. As a result, no
473   // other SjLj exception interfaces are implemented and please don't build
474   // your own exception handling based on them.
475   // LLVM/Clang supports zero-cost DWARF exception handling.
476   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
477   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
478 
479   // We want to legalize GlobalAddress and ConstantPool nodes into the
480   // appropriate instructions to materialize the address.
481   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
482   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
483   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
484   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
485   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
486   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
487   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
488   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
489   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
490   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
491 
492   // TRAP is legal.
493   setOperationAction(ISD::TRAP, MVT::Other, Legal);
494 
495   // TRAMPOLINE is custom lowered.
496   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
497   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
498 
499   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
500   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
501 
502   if (Subtarget.is64BitELFABI()) {
503     // VAARG always uses double-word chunks, so promote anything smaller.
504     setOperationAction(ISD::VAARG, MVT::i1, Promote);
505     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
506     setOperationAction(ISD::VAARG, MVT::i8, Promote);
507     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
508     setOperationAction(ISD::VAARG, MVT::i16, Promote);
509     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
510     setOperationAction(ISD::VAARG, MVT::i32, Promote);
511     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
512     setOperationAction(ISD::VAARG, MVT::Other, Expand);
513   } else if (Subtarget.is32BitELFABI()) {
514     // VAARG is custom lowered with the 32-bit SVR4 ABI.
515     setOperationAction(ISD::VAARG, MVT::Other, Custom);
516     setOperationAction(ISD::VAARG, MVT::i64, Custom);
517   } else
518     setOperationAction(ISD::VAARG, MVT::Other, Expand);
519 
520   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
521   if (Subtarget.is32BitELFABI())
522     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
523   else
524     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
525 
526   // Use the default implementation.
527   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
528   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
529   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
530   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
531   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
532   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
533   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
534   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
535   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
536 
537   // We want to custom lower some of our intrinsics.
538   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
539 
540   // To handle counter-based loop conditions.
541   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
542 
543   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
544   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
545   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
546   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
547 
548   // Comparisons that require checking two conditions.
549   if (Subtarget.hasSPE()) {
550     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
551     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
552     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
553     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
554   }
555   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
556   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
557   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
558   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
559   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
560   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
561   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
562   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
563   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
564   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
565   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
566   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
567 
568   if (Subtarget.has64BitSupport()) {
569     // They also have instructions for converting between i64 and fp.
570     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
571     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
572     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
573     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
574     // This is just the low 32 bits of a (signed) fp->i64 conversion.
575     // We cannot do this with Promote because i64 is not a legal type.
576     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
577 
578     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
579       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
580   } else {
581     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
582     if (Subtarget.hasSPE()) {
583       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
584       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
585     } else
586       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
587   }
588 
589   // With the instructions enabled under FPCVT, we can do everything.
590   if (Subtarget.hasFPCVT()) {
591     if (Subtarget.has64BitSupport()) {
592       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
593       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
594       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
595       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
596     }
597 
598     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
599     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
600     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
601     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
602   }
603 
604   if (Subtarget.use64BitRegs()) {
605     // 64-bit PowerPC implementations can support i64 types directly
606     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
607     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
608     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
609     // 64-bit PowerPC wants to expand i128 shifts itself.
610     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
611     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
612     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
613   } else {
614     // 32-bit PowerPC wants to expand i64 shifts itself.
615     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
616     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
617     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
618   }
619 
620   if (Subtarget.hasVSX()) {
621     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
622     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
623     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
624     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
625   }
626 
627   if (Subtarget.hasAltivec()) {
628     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
629       setOperationAction(ISD::SADDSAT, VT, Legal);
630       setOperationAction(ISD::SSUBSAT, VT, Legal);
631       setOperationAction(ISD::UADDSAT, VT, Legal);
632       setOperationAction(ISD::USUBSAT, VT, Legal);
633     }
634     // First set operation action for all vector types to expand. Then we
635     // will selectively turn on ones that can be effectively codegen'd.
636     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
637       // add/sub are legal for all supported vector VT's.
638       setOperationAction(ISD::ADD, VT, Legal);
639       setOperationAction(ISD::SUB, VT, Legal);
640 
641       // For v2i64, these are only valid with P8Vector. This is corrected after
642       // the loop.
643       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
644         setOperationAction(ISD::SMAX, VT, Legal);
645         setOperationAction(ISD::SMIN, VT, Legal);
646         setOperationAction(ISD::UMAX, VT, Legal);
647         setOperationAction(ISD::UMIN, VT, Legal);
648       }
649       else {
650         setOperationAction(ISD::SMAX, VT, Expand);
651         setOperationAction(ISD::SMIN, VT, Expand);
652         setOperationAction(ISD::UMAX, VT, Expand);
653         setOperationAction(ISD::UMIN, VT, Expand);
654       }
655 
656       if (Subtarget.hasVSX()) {
657         setOperationAction(ISD::FMAXNUM, VT, Legal);
658         setOperationAction(ISD::FMINNUM, VT, Legal);
659       }
660 
661       // Vector instructions introduced in P8
662       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
663         setOperationAction(ISD::CTPOP, VT, Legal);
664         setOperationAction(ISD::CTLZ, VT, Legal);
665       }
666       else {
667         setOperationAction(ISD::CTPOP, VT, Expand);
668         setOperationAction(ISD::CTLZ, VT, Expand);
669       }
670 
671       // Vector instructions introduced in P9
672       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
673         setOperationAction(ISD::CTTZ, VT, Legal);
674       else
675         setOperationAction(ISD::CTTZ, VT, Expand);
676 
677       // We promote all shuffles to v16i8.
678       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
679       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
680 
681       // We promote all non-typed operations to v4i32.
682       setOperationAction(ISD::AND   , VT, Promote);
683       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
684       setOperationAction(ISD::OR    , VT, Promote);
685       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
686       setOperationAction(ISD::XOR   , VT, Promote);
687       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
688       setOperationAction(ISD::LOAD  , VT, Promote);
689       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
690       setOperationAction(ISD::SELECT, VT, Promote);
691       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
692       setOperationAction(ISD::VSELECT, VT, Legal);
693       setOperationAction(ISD::SELECT_CC, VT, Promote);
694       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
695       setOperationAction(ISD::STORE, VT, Promote);
696       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
697 
698       // No other operations are legal.
699       setOperationAction(ISD::MUL , VT, Expand);
700       setOperationAction(ISD::SDIV, VT, Expand);
701       setOperationAction(ISD::SREM, VT, Expand);
702       setOperationAction(ISD::UDIV, VT, Expand);
703       setOperationAction(ISD::UREM, VT, Expand);
704       setOperationAction(ISD::FDIV, VT, Expand);
705       setOperationAction(ISD::FREM, VT, Expand);
706       setOperationAction(ISD::FNEG, VT, Expand);
707       setOperationAction(ISD::FSQRT, VT, Expand);
708       setOperationAction(ISD::FLOG, VT, Expand);
709       setOperationAction(ISD::FLOG10, VT, Expand);
710       setOperationAction(ISD::FLOG2, VT, Expand);
711       setOperationAction(ISD::FEXP, VT, Expand);
712       setOperationAction(ISD::FEXP2, VT, Expand);
713       setOperationAction(ISD::FSIN, VT, Expand);
714       setOperationAction(ISD::FCOS, VT, Expand);
715       setOperationAction(ISD::FABS, VT, Expand);
716       setOperationAction(ISD::FFLOOR, VT, Expand);
717       setOperationAction(ISD::FCEIL,  VT, Expand);
718       setOperationAction(ISD::FTRUNC, VT, Expand);
719       setOperationAction(ISD::FRINT,  VT, Expand);
720       setOperationAction(ISD::FNEARBYINT, VT, Expand);
721       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
722       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
723       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
724       setOperationAction(ISD::MULHU, VT, Expand);
725       setOperationAction(ISD::MULHS, VT, Expand);
726       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
727       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
728       setOperationAction(ISD::UDIVREM, VT, Expand);
729       setOperationAction(ISD::SDIVREM, VT, Expand);
730       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
731       setOperationAction(ISD::FPOW, VT, Expand);
732       setOperationAction(ISD::BSWAP, VT, Expand);
733       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
734       setOperationAction(ISD::ROTL, VT, Expand);
735       setOperationAction(ISD::ROTR, VT, Expand);
736 
737       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
738         setTruncStoreAction(VT, InnerVT, Expand);
739         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
740         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
741         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
742       }
743     }
744     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
745     if (!Subtarget.hasP8Vector()) {
746       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
747       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
748       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
749       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
750     }
751 
752     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
753       setOperationAction(ISD::ABS, VT, Custom);
754 
755     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
756     // with merges, splats, etc.
757     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
758 
759     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
760     // are cheap, so handle them before they get expanded to scalar.
761     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
762     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
763     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
764     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
765     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
766 
767     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
768     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
769     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
770     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
771     setOperationAction(ISD::SELECT, MVT::v4i32,
772                        Subtarget.useCRBits() ? Legal : Expand);
773     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
774     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
775     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
776     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
777     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
778     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
779     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
780     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
781     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
782 
783     // Without hasP8Altivec set, v2i64 SMAX isn't available.
784     // But ABS custom lowering requires SMAX support.
785     if (!Subtarget.hasP8Altivec())
786       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
787 
788     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
789     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
790     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
791     if (Subtarget.hasAltivec())
792       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
793         setOperationAction(ISD::ROTL, VT, Legal);
794     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
795     if (Subtarget.hasP8Altivec())
796       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
797 
798     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
799     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
800     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
801     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
802 
803     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
804     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
805 
806     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
807       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
808       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
809     }
810 
811     if (Subtarget.hasP8Altivec())
812       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
813     else
814       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
815 
816     if (Subtarget.isISA3_1()) {
817       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
818       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
819       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
820       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
821       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
822       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
823       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
824       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
825       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
826       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
827       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
828       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
829       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
830     }
831 
832     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
833     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
834 
835     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
836     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
837 
838     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
839     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
840     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
841     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
842 
843     // Altivec does not contain unordered floating-point compare instructions
844     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
845     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
846     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
847     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
848 
849     if (Subtarget.hasVSX()) {
850       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
851       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
852       if (Subtarget.hasP8Vector()) {
853         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
854         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
855       }
856       if (Subtarget.hasDirectMove() && isPPC64) {
857         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
858         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
859         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
860         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
861         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
862         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
863         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
864         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
865       }
866       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
867 
868       // The nearbyint variants are not allowed to raise the inexact exception
869       // so we can only code-gen them with unsafe math.
870       if (TM.Options.UnsafeFPMath) {
871         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
872         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
873       }
874 
875       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
876       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
877       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
878       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
879       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
880       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
881       setOperationAction(ISD::FROUND, MVT::f64, Legal);
882       setOperationAction(ISD::FRINT, MVT::f64, Legal);
883 
884       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
885       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
886       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
887       setOperationAction(ISD::FROUND, MVT::f32, Legal);
888       setOperationAction(ISD::FRINT, MVT::f32, Legal);
889 
890       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
891       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
892 
893       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
894       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
895 
896       // Share the Altivec comparison restrictions.
897       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
898       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
899       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
900       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
901 
902       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
903       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
904 
905       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
906 
907       if (Subtarget.hasP8Vector())
908         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
909 
910       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
911 
912       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
913       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
914       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
915 
916       if (Subtarget.hasP8Altivec()) {
917         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
918         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
919         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
920 
921         // 128 bit shifts can be accomplished via 3 instructions for SHL and
922         // SRL, but not for SRA because of the instructions available:
923         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
924         // doing
925         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
926         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
927         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
928 
929         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
930       }
931       else {
932         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
933         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
934         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
935 
936         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
937 
938         // VSX v2i64 only supports non-arithmetic operations.
939         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
940         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
941       }
942 
943       setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
944 
945       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
946       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
947       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
948       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
949 
950       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
951 
952       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
953       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
954       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
955       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
956 
957       // Custom handling for partial vectors of integers converted to
958       // floating point. We already have optimal handling for v2i32 through
959       // the DAG combine, so those aren't necessary.
960       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
961       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
962       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
963       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
964       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
965       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
966       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
967       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
968 
969       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
970       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
971       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
972       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
973       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
974       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
975 
976       if (Subtarget.hasDirectMove())
977         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
978       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
979 
980       // Handle constrained floating-point operations of vector.
981       // The predictor is `hasVSX` because altivec instruction has
982       // no exception but VSX vector instruction has.
983       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
984       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
985       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
986       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
987       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
988       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
989       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
990       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
991       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
992       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
993       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
994       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
995       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
996 
997       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
998       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
999       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1000       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1001       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1002       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1003       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1004       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1005       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
1006       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1007       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1008       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1009       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1010 
1011       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1012     }
1013 
1014     if (Subtarget.hasP8Altivec()) {
1015       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1016       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1017     }
1018 
1019     if (Subtarget.hasP9Vector()) {
1020       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1021       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1022 
1023       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1024       // SRL, but not for SRA because of the instructions available:
1025       // VS{RL} and VS{RL}O.
1026       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1027       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1028       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1029 
1030       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1031       setOperationAction(ISD::FADD, MVT::f128, Legal);
1032       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1033       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1034       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1035       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1036       // No extending loads to f128 on PPC.
1037       for (MVT FPT : MVT::fp_valuetypes())
1038         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1039       setOperationAction(ISD::FMA, MVT::f128, Legal);
1040       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1041       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1042       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1043       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1044       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1045       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1046 
1047       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1048       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1049       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1050       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1051       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1052       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1053 
1054       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1055       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1056       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1057       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1058       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1059       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1060       // No implementation for these ops for PowerPC.
1061       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1062       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1063       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1064       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1065       setOperationAction(ISD::FREM, MVT::f128, Expand);
1066 
1067       // Handle constrained floating-point operations of fp128
1068       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1069       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1070       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1071       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1072       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1073       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1074       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1075       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1076       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1077       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1078       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1079       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1080       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1081       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1082       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1083       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1084       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1085       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1086       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1087       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1088     }
1089 
1090     if (Subtarget.hasP9Altivec()) {
1091       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1092       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1093 
1094       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1095       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1096       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1097       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1098       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1099       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1100       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1101     }
1102   }
1103 
1104   if (Subtarget.has64BitSupport())
1105     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1106 
1107   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1108 
1109   if (!isPPC64) {
1110     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1111     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1112   }
1113 
1114   setBooleanContents(ZeroOrOneBooleanContent);
1115 
1116   if (Subtarget.hasAltivec()) {
1117     // Altivec instructions set fields to all zeros or all ones.
1118     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1119   }
1120 
1121   if (!isPPC64) {
1122     // These libcalls are not available in 32-bit.
1123     setLibcallName(RTLIB::SHL_I128, nullptr);
1124     setLibcallName(RTLIB::SRL_I128, nullptr);
1125     setLibcallName(RTLIB::SRA_I128, nullptr);
1126   }
1127 
1128   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1129 
1130   // We have target-specific dag combine patterns for the following nodes:
1131   setTargetDAGCombine(ISD::ADD);
1132   setTargetDAGCombine(ISD::SHL);
1133   setTargetDAGCombine(ISD::SRA);
1134   setTargetDAGCombine(ISD::SRL);
1135   setTargetDAGCombine(ISD::MUL);
1136   setTargetDAGCombine(ISD::FMA);
1137   setTargetDAGCombine(ISD::SINT_TO_FP);
1138   setTargetDAGCombine(ISD::BUILD_VECTOR);
1139   if (Subtarget.hasFPCVT())
1140     setTargetDAGCombine(ISD::UINT_TO_FP);
1141   setTargetDAGCombine(ISD::LOAD);
1142   setTargetDAGCombine(ISD::STORE);
1143   setTargetDAGCombine(ISD::BR_CC);
1144   if (Subtarget.useCRBits())
1145     setTargetDAGCombine(ISD::BRCOND);
1146   setTargetDAGCombine(ISD::BSWAP);
1147   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1148   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1149   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1150 
1151   setTargetDAGCombine(ISD::SIGN_EXTEND);
1152   setTargetDAGCombine(ISD::ZERO_EXTEND);
1153   setTargetDAGCombine(ISD::ANY_EXTEND);
1154 
1155   setTargetDAGCombine(ISD::TRUNCATE);
1156   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1157 
1158 
1159   if (Subtarget.useCRBits()) {
1160     setTargetDAGCombine(ISD::TRUNCATE);
1161     setTargetDAGCombine(ISD::SETCC);
1162     setTargetDAGCombine(ISD::SELECT_CC);
1163   }
1164 
1165   // Use reciprocal estimates.
1166   if (TM.Options.UnsafeFPMath) {
1167     setTargetDAGCombine(ISD::FDIV);
1168     setTargetDAGCombine(ISD::FSQRT);
1169   }
1170 
1171   if (Subtarget.hasP9Altivec()) {
1172     setTargetDAGCombine(ISD::ABS);
1173     setTargetDAGCombine(ISD::VSELECT);
1174   }
1175 
1176   setLibcallName(RTLIB::LOG_F128, "logf128");
1177   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1178   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1179   setLibcallName(RTLIB::EXP_F128, "expf128");
1180   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1181   setLibcallName(RTLIB::SIN_F128, "sinf128");
1182   setLibcallName(RTLIB::COS_F128, "cosf128");
1183   setLibcallName(RTLIB::POW_F128, "powf128");
1184   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1185   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1186   setLibcallName(RTLIB::POWI_F128, "__powikf2");
1187   setLibcallName(RTLIB::REM_F128, "fmodf128");
1188 
1189   // With 32 condition bits, we don't need to sink (and duplicate) compares
1190   // aggressively in CodeGenPrep.
1191   if (Subtarget.useCRBits()) {
1192     setHasMultipleConditionRegisters();
1193     setJumpIsExpensive();
1194   }
1195 
1196   setMinFunctionAlignment(Align(4));
1197 
1198   switch (Subtarget.getCPUDirective()) {
1199   default: break;
1200   case PPC::DIR_970:
1201   case PPC::DIR_A2:
1202   case PPC::DIR_E500:
1203   case PPC::DIR_E500mc:
1204   case PPC::DIR_E5500:
1205   case PPC::DIR_PWR4:
1206   case PPC::DIR_PWR5:
1207   case PPC::DIR_PWR5X:
1208   case PPC::DIR_PWR6:
1209   case PPC::DIR_PWR6X:
1210   case PPC::DIR_PWR7:
1211   case PPC::DIR_PWR8:
1212   case PPC::DIR_PWR9:
1213   case PPC::DIR_PWR10:
1214   case PPC::DIR_PWR_FUTURE:
1215     setPrefLoopAlignment(Align(16));
1216     setPrefFunctionAlignment(Align(16));
1217     break;
1218   }
1219 
1220   if (Subtarget.enableMachineScheduler())
1221     setSchedulingPreference(Sched::Source);
1222   else
1223     setSchedulingPreference(Sched::Hybrid);
1224 
1225   computeRegisterProperties(STI.getRegisterInfo());
1226 
1227   // The Freescale cores do better with aggressive inlining of memcpy and
1228   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1229   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1230       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1231     MaxStoresPerMemset = 32;
1232     MaxStoresPerMemsetOptSize = 16;
1233     MaxStoresPerMemcpy = 32;
1234     MaxStoresPerMemcpyOptSize = 8;
1235     MaxStoresPerMemmove = 32;
1236     MaxStoresPerMemmoveOptSize = 8;
1237   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1238     // The A2 also benefits from (very) aggressive inlining of memcpy and
1239     // friends. The overhead of a the function call, even when warm, can be
1240     // over one hundred cycles.
1241     MaxStoresPerMemset = 128;
1242     MaxStoresPerMemcpy = 128;
1243     MaxStoresPerMemmove = 128;
1244     MaxLoadsPerMemcmp = 128;
1245   } else {
1246     MaxLoadsPerMemcmp = 8;
1247     MaxLoadsPerMemcmpOptSize = 4;
1248   }
1249 
1250   // Let the subtarget (CPU) decide if a predictable select is more expensive
1251   // than the corresponding branch. This information is used in CGP to decide
1252   // when to convert selects into branches.
1253   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1254 }
1255 
1256 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1257 /// the desired ByVal argument alignment.
1258 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1259   if (MaxAlign == MaxMaxAlign)
1260     return;
1261   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1262     if (MaxMaxAlign >= 32 &&
1263         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1264       MaxAlign = Align(32);
1265     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1266              MaxAlign < 16)
1267       MaxAlign = Align(16);
1268   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1269     Align EltAlign;
1270     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1271     if (EltAlign > MaxAlign)
1272       MaxAlign = EltAlign;
1273   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1274     for (auto *EltTy : STy->elements()) {
1275       Align EltAlign;
1276       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1277       if (EltAlign > MaxAlign)
1278         MaxAlign = EltAlign;
1279       if (MaxAlign == MaxMaxAlign)
1280         break;
1281     }
1282   }
1283 }
1284 
1285 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1286 /// function arguments in the caller parameter area.
1287 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1288                                                   const DataLayout &DL) const {
1289   // 16byte and wider vectors are passed on 16byte boundary.
1290   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1291   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1292   if (Subtarget.hasAltivec())
1293     getMaxByValAlign(Ty, Alignment, Align(16));
1294   return Alignment.value();
1295 }
1296 
1297 bool PPCTargetLowering::useSoftFloat() const {
1298   return Subtarget.useSoftFloat();
1299 }
1300 
1301 bool PPCTargetLowering::hasSPE() const {
1302   return Subtarget.hasSPE();
1303 }
1304 
1305 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1306   return VT.isScalarInteger();
1307 }
1308 
1309 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1310 /// type is cheaper than a multiply followed by a shift.
1311 /// This is true for words and doublewords on 64-bit PowerPC.
1312 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1313   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1314                               isOperationLegal(ISD::MULHU, Type)))
1315     return true;
1316   return TargetLowering::isMulhCheaperThanMulShift(Type);
1317 }
1318 
1319 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1320   switch ((PPCISD::NodeType)Opcode) {
1321   case PPCISD::FIRST_NUMBER:    break;
1322   case PPCISD::FSEL:            return "PPCISD::FSEL";
1323   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1324   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1325   case PPCISD::FCFID:           return "PPCISD::FCFID";
1326   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1327   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1328   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1329   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1330   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1331   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1332   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1333   case PPCISD::FP_TO_UINT_IN_VSR:
1334                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1335   case PPCISD::FP_TO_SINT_IN_VSR:
1336                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1337   case PPCISD::FRE:             return "PPCISD::FRE";
1338   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1339   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1340   case PPCISD::VPERM:           return "PPCISD::VPERM";
1341   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1342   case PPCISD::XXSPLTI_SP_TO_DP:
1343     return "PPCISD::XXSPLTI_SP_TO_DP";
1344   case PPCISD::XXSPLTI32DX:
1345     return "PPCISD::XXSPLTI32DX";
1346   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1347   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1348   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1349   case PPCISD::CMPB:            return "PPCISD::CMPB";
1350   case PPCISD::Hi:              return "PPCISD::Hi";
1351   case PPCISD::Lo:              return "PPCISD::Lo";
1352   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1353   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1354   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1355   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1356   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1357   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1358   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1359   case PPCISD::SRL:             return "PPCISD::SRL";
1360   case PPCISD::SRA:             return "PPCISD::SRA";
1361   case PPCISD::SHL:             return "PPCISD::SHL";
1362   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1363   case PPCISD::CALL:            return "PPCISD::CALL";
1364   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1365   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1366   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1367   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1368   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1369   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1370   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1371   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1372   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1373   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1374   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1375   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1376   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1377   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1378   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1379   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1380     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1381   case PPCISD::ANDI_rec_1_EQ_BIT:
1382     return "PPCISD::ANDI_rec_1_EQ_BIT";
1383   case PPCISD::ANDI_rec_1_GT_BIT:
1384     return "PPCISD::ANDI_rec_1_GT_BIT";
1385   case PPCISD::VCMP:            return "PPCISD::VCMP";
1386   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1387   case PPCISD::LBRX:            return "PPCISD::LBRX";
1388   case PPCISD::STBRX:           return "PPCISD::STBRX";
1389   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1390   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1391   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1392   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1393   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1394   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1395   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1396   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1397   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1398   case PPCISD::ST_VSR_SCAL_INT:
1399                                 return "PPCISD::ST_VSR_SCAL_INT";
1400   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1401   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1402   case PPCISD::BDZ:             return "PPCISD::BDZ";
1403   case PPCISD::MFFS:            return "PPCISD::MFFS";
1404   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1405   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1406   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1407   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1408   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1409   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1410   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1411   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1412   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1413   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1414   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1415   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1416   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1417   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1418   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1419   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1420   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1421   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1422   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1423   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1424   case PPCISD::SC:              return "PPCISD::SC";
1425   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1426   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1427   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1428   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1429   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1430   case PPCISD::VABSD:           return "PPCISD::VABSD";
1431   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1432   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1433   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1434   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1435   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1436   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1437   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1438   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1439   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1440   }
1441   return nullptr;
1442 }
1443 
1444 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1445                                           EVT VT) const {
1446   if (!VT.isVector())
1447     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1448 
1449   return VT.changeVectorElementTypeToInteger();
1450 }
1451 
1452 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1453   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1454   return true;
1455 }
1456 
1457 //===----------------------------------------------------------------------===//
1458 // Node matching predicates, for use by the tblgen matching code.
1459 //===----------------------------------------------------------------------===//
1460 
1461 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1462 static bool isFloatingPointZero(SDValue Op) {
1463   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1464     return CFP->getValueAPF().isZero();
1465   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1466     // Maybe this has already been legalized into the constant pool?
1467     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1468       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1469         return CFP->getValueAPF().isZero();
1470   }
1471   return false;
1472 }
1473 
1474 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1475 /// true if Op is undef or if it matches the specified value.
1476 static bool isConstantOrUndef(int Op, int Val) {
1477   return Op < 0 || Op == Val;
1478 }
1479 
1480 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1481 /// VPKUHUM instruction.
1482 /// The ShuffleKind distinguishes between big-endian operations with
1483 /// two different inputs (0), either-endian operations with two identical
1484 /// inputs (1), and little-endian operations with two different inputs (2).
1485 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1486 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1487                                SelectionDAG &DAG) {
1488   bool IsLE = DAG.getDataLayout().isLittleEndian();
1489   if (ShuffleKind == 0) {
1490     if (IsLE)
1491       return false;
1492     for (unsigned i = 0; i != 16; ++i)
1493       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1494         return false;
1495   } else if (ShuffleKind == 2) {
1496     if (!IsLE)
1497       return false;
1498     for (unsigned i = 0; i != 16; ++i)
1499       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1500         return false;
1501   } else if (ShuffleKind == 1) {
1502     unsigned j = IsLE ? 0 : 1;
1503     for (unsigned i = 0; i != 8; ++i)
1504       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1505           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1506         return false;
1507   }
1508   return true;
1509 }
1510 
1511 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1512 /// VPKUWUM instruction.
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::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1518                                SelectionDAG &DAG) {
1519   bool IsLE = DAG.getDataLayout().isLittleEndian();
1520   if (ShuffleKind == 0) {
1521     if (IsLE)
1522       return false;
1523     for (unsigned i = 0; i != 16; i += 2)
1524       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1525           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1526         return false;
1527   } else if (ShuffleKind == 2) {
1528     if (!IsLE)
1529       return false;
1530     for (unsigned i = 0; i != 16; i += 2)
1531       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1532           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1533         return false;
1534   } else if (ShuffleKind == 1) {
1535     unsigned j = IsLE ? 0 : 2;
1536     for (unsigned i = 0; i != 8; i += 2)
1537       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1538           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1539           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1540           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1541         return false;
1542   }
1543   return true;
1544 }
1545 
1546 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1547 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1548 /// current subtarget.
1549 ///
1550 /// The ShuffleKind distinguishes between big-endian operations with
1551 /// two different inputs (0), either-endian operations with two identical
1552 /// inputs (1), and little-endian operations with two different inputs (2).
1553 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1554 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1555                                SelectionDAG &DAG) {
1556   const PPCSubtarget& Subtarget =
1557       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1558   if (!Subtarget.hasP8Vector())
1559     return false;
1560 
1561   bool IsLE = DAG.getDataLayout().isLittleEndian();
1562   if (ShuffleKind == 0) {
1563     if (IsLE)
1564       return false;
1565     for (unsigned i = 0; i != 16; i += 4)
1566       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1567           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1568           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1569           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1570         return false;
1571   } else if (ShuffleKind == 2) {
1572     if (!IsLE)
1573       return false;
1574     for (unsigned i = 0; i != 16; i += 4)
1575       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1576           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1577           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1578           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1579         return false;
1580   } else if (ShuffleKind == 1) {
1581     unsigned j = IsLE ? 0 : 4;
1582     for (unsigned i = 0; i != 8; i += 4)
1583       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1584           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1585           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1586           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1587           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1588           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1589           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1590           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1591         return false;
1592   }
1593   return true;
1594 }
1595 
1596 /// isVMerge - Common function, used to match vmrg* shuffles.
1597 ///
1598 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1599                      unsigned LHSStart, unsigned RHSStart) {
1600   if (N->getValueType(0) != MVT::v16i8)
1601     return false;
1602   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1603          "Unsupported merge size!");
1604 
1605   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1606     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1607       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1608                              LHSStart+j+i*UnitSize) ||
1609           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1610                              RHSStart+j+i*UnitSize))
1611         return false;
1612     }
1613   return true;
1614 }
1615 
1616 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1617 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1618 /// The ShuffleKind distinguishes between big-endian merges with two
1619 /// different inputs (0), either-endian merges with two identical inputs (1),
1620 /// and little-endian merges with two different inputs (2).  For the latter,
1621 /// the input operands are swapped (see PPCInstrAltivec.td).
1622 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1623                              unsigned ShuffleKind, SelectionDAG &DAG) {
1624   if (DAG.getDataLayout().isLittleEndian()) {
1625     if (ShuffleKind == 1) // unary
1626       return isVMerge(N, UnitSize, 0, 0);
1627     else if (ShuffleKind == 2) // swapped
1628       return isVMerge(N, UnitSize, 0, 16);
1629     else
1630       return false;
1631   } else {
1632     if (ShuffleKind == 1) // unary
1633       return isVMerge(N, UnitSize, 8, 8);
1634     else if (ShuffleKind == 0) // normal
1635       return isVMerge(N, UnitSize, 8, 24);
1636     else
1637       return false;
1638   }
1639 }
1640 
1641 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1642 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1643 /// The ShuffleKind distinguishes between big-endian merges with two
1644 /// different inputs (0), either-endian merges with two identical inputs (1),
1645 /// and little-endian merges with two different inputs (2).  For the latter,
1646 /// the input operands are swapped (see PPCInstrAltivec.td).
1647 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1648                              unsigned ShuffleKind, SelectionDAG &DAG) {
1649   if (DAG.getDataLayout().isLittleEndian()) {
1650     if (ShuffleKind == 1) // unary
1651       return isVMerge(N, UnitSize, 8, 8);
1652     else if (ShuffleKind == 2) // swapped
1653       return isVMerge(N, UnitSize, 8, 24);
1654     else
1655       return false;
1656   } else {
1657     if (ShuffleKind == 1) // unary
1658       return isVMerge(N, UnitSize, 0, 0);
1659     else if (ShuffleKind == 0) // normal
1660       return isVMerge(N, UnitSize, 0, 16);
1661     else
1662       return false;
1663   }
1664 }
1665 
1666 /**
1667  * Common function used to match vmrgew and vmrgow shuffles
1668  *
1669  * The indexOffset determines whether to look for even or odd words in
1670  * the shuffle mask. This is based on the of the endianness of the target
1671  * machine.
1672  *   - Little Endian:
1673  *     - Use offset of 0 to check for odd elements
1674  *     - Use offset of 4 to check for even elements
1675  *   - Big Endian:
1676  *     - Use offset of 0 to check for even elements
1677  *     - Use offset of 4 to check for odd elements
1678  * A detailed description of the vector element ordering for little endian and
1679  * big endian can be found at
1680  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1681  * Targeting your applications - what little endian and big endian IBM XL C/C++
1682  * compiler differences mean to you
1683  *
1684  * The mask to the shuffle vector instruction specifies the indices of the
1685  * elements from the two input vectors to place in the result. The elements are
1686  * numbered in array-access order, starting with the first vector. These vectors
1687  * are always of type v16i8, thus each vector will contain 16 elements of size
1688  * 8. More info on the shuffle vector can be found in the
1689  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1690  * Language Reference.
1691  *
1692  * The RHSStartValue indicates whether the same input vectors are used (unary)
1693  * or two different input vectors are used, based on the following:
1694  *   - If the instruction uses the same vector for both inputs, the range of the
1695  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1696  *     be 0.
1697  *   - If the instruction has two different vectors then the range of the
1698  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1699  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1700  *     to 31 specify elements in the second vector).
1701  *
1702  * \param[in] N The shuffle vector SD Node to analyze
1703  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1704  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1705  * vector to the shuffle_vector instruction
1706  * \return true iff this shuffle vector represents an even or odd word merge
1707  */
1708 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1709                      unsigned RHSStartValue) {
1710   if (N->getValueType(0) != MVT::v16i8)
1711     return false;
1712 
1713   for (unsigned i = 0; i < 2; ++i)
1714     for (unsigned j = 0; j < 4; ++j)
1715       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1716                              i*RHSStartValue+j+IndexOffset) ||
1717           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1718                              i*RHSStartValue+j+IndexOffset+8))
1719         return false;
1720   return true;
1721 }
1722 
1723 /**
1724  * Determine if the specified shuffle mask is suitable for the vmrgew or
1725  * vmrgow instructions.
1726  *
1727  * \param[in] N The shuffle vector SD Node to analyze
1728  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1729  * \param[in] ShuffleKind Identify the type of merge:
1730  *   - 0 = big-endian merge with two different inputs;
1731  *   - 1 = either-endian merge with two identical inputs;
1732  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1733  *     little-endian merges).
1734  * \param[in] DAG The current SelectionDAG
1735  * \return true iff this shuffle mask
1736  */
1737 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1738                               unsigned ShuffleKind, SelectionDAG &DAG) {
1739   if (DAG.getDataLayout().isLittleEndian()) {
1740     unsigned indexOffset = CheckEven ? 4 : 0;
1741     if (ShuffleKind == 1) // Unary
1742       return isVMerge(N, indexOffset, 0);
1743     else if (ShuffleKind == 2) // swapped
1744       return isVMerge(N, indexOffset, 16);
1745     else
1746       return false;
1747   }
1748   else {
1749     unsigned indexOffset = CheckEven ? 0 : 4;
1750     if (ShuffleKind == 1) // Unary
1751       return isVMerge(N, indexOffset, 0);
1752     else if (ShuffleKind == 0) // Normal
1753       return isVMerge(N, indexOffset, 16);
1754     else
1755       return false;
1756   }
1757   return false;
1758 }
1759 
1760 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1761 /// amount, otherwise return -1.
1762 /// The ShuffleKind distinguishes between big-endian operations with two
1763 /// different inputs (0), either-endian operations with two identical inputs
1764 /// (1), and little-endian operations with two different inputs (2).  For the
1765 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1766 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1767                              SelectionDAG &DAG) {
1768   if (N->getValueType(0) != MVT::v16i8)
1769     return -1;
1770 
1771   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1772 
1773   // Find the first non-undef value in the shuffle mask.
1774   unsigned i;
1775   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1776     /*search*/;
1777 
1778   if (i == 16) return -1;  // all undef.
1779 
1780   // Otherwise, check to see if the rest of the elements are consecutively
1781   // numbered from this value.
1782   unsigned ShiftAmt = SVOp->getMaskElt(i);
1783   if (ShiftAmt < i) return -1;
1784 
1785   ShiftAmt -= i;
1786   bool isLE = DAG.getDataLayout().isLittleEndian();
1787 
1788   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1789     // Check the rest of the elements to see if they are consecutive.
1790     for (++i; i != 16; ++i)
1791       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1792         return -1;
1793   } else if (ShuffleKind == 1) {
1794     // Check the rest of the elements to see if they are consecutive.
1795     for (++i; i != 16; ++i)
1796       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1797         return -1;
1798   } else
1799     return -1;
1800 
1801   if (isLE)
1802     ShiftAmt = 16 - ShiftAmt;
1803 
1804   return ShiftAmt;
1805 }
1806 
1807 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1808 /// specifies a splat of a single element that is suitable for input to
1809 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1810 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1811   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1812          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1813 
1814   // The consecutive indices need to specify an element, not part of two
1815   // different elements.  So abandon ship early if this isn't the case.
1816   if (N->getMaskElt(0) % EltSize != 0)
1817     return false;
1818 
1819   // This is a splat operation if each element of the permute is the same, and
1820   // if the value doesn't reference the second vector.
1821   unsigned ElementBase = N->getMaskElt(0);
1822 
1823   // FIXME: Handle UNDEF elements too!
1824   if (ElementBase >= 16)
1825     return false;
1826 
1827   // Check that the indices are consecutive, in the case of a multi-byte element
1828   // splatted with a v16i8 mask.
1829   for (unsigned i = 1; i != EltSize; ++i)
1830     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1831       return false;
1832 
1833   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1834     if (N->getMaskElt(i) < 0) continue;
1835     for (unsigned j = 0; j != EltSize; ++j)
1836       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1837         return false;
1838   }
1839   return true;
1840 }
1841 
1842 /// Check that the mask is shuffling N byte elements. Within each N byte
1843 /// element of the mask, the indices could be either in increasing or
1844 /// decreasing order as long as they are consecutive.
1845 /// \param[in] N the shuffle vector SD Node to analyze
1846 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1847 /// Word/DoubleWord/QuadWord).
1848 /// \param[in] StepLen the delta indices number among the N byte element, if
1849 /// the mask is in increasing/decreasing order then it is 1/-1.
1850 /// \return true iff the mask is shuffling N byte elements.
1851 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1852                                    int StepLen) {
1853   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1854          "Unexpected element width.");
1855   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1856 
1857   unsigned NumOfElem = 16 / Width;
1858   unsigned MaskVal[16]; //  Width is never greater than 16
1859   for (unsigned i = 0; i < NumOfElem; ++i) {
1860     MaskVal[0] = N->getMaskElt(i * Width);
1861     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1862       return false;
1863     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1864       return false;
1865     }
1866 
1867     for (unsigned int j = 1; j < Width; ++j) {
1868       MaskVal[j] = N->getMaskElt(i * Width + j);
1869       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1870         return false;
1871       }
1872     }
1873   }
1874 
1875   return true;
1876 }
1877 
1878 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1879                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1880   if (!isNByteElemShuffleMask(N, 4, 1))
1881     return false;
1882 
1883   // Now we look at mask elements 0,4,8,12
1884   unsigned M0 = N->getMaskElt(0) / 4;
1885   unsigned M1 = N->getMaskElt(4) / 4;
1886   unsigned M2 = N->getMaskElt(8) / 4;
1887   unsigned M3 = N->getMaskElt(12) / 4;
1888   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1889   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1890 
1891   // Below, let H and L be arbitrary elements of the shuffle mask
1892   // where H is in the range [4,7] and L is in the range [0,3].
1893   // H, 1, 2, 3 or L, 5, 6, 7
1894   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1895       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1896     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1897     InsertAtByte = IsLE ? 12 : 0;
1898     Swap = M0 < 4;
1899     return true;
1900   }
1901   // 0, H, 2, 3 or 4, L, 6, 7
1902   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1903       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1904     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1905     InsertAtByte = IsLE ? 8 : 4;
1906     Swap = M1 < 4;
1907     return true;
1908   }
1909   // 0, 1, H, 3 or 4, 5, L, 7
1910   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1911       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1912     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1913     InsertAtByte = IsLE ? 4 : 8;
1914     Swap = M2 < 4;
1915     return true;
1916   }
1917   // 0, 1, 2, H or 4, 5, 6, L
1918   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1919       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1920     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1921     InsertAtByte = IsLE ? 0 : 12;
1922     Swap = M3 < 4;
1923     return true;
1924   }
1925 
1926   // If both vector operands for the shuffle are the same vector, the mask will
1927   // contain only elements from the first one and the second one will be undef.
1928   if (N->getOperand(1).isUndef()) {
1929     ShiftElts = 0;
1930     Swap = true;
1931     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1932     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1933       InsertAtByte = IsLE ? 12 : 0;
1934       return true;
1935     }
1936     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1937       InsertAtByte = IsLE ? 8 : 4;
1938       return true;
1939     }
1940     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1941       InsertAtByte = IsLE ? 4 : 8;
1942       return true;
1943     }
1944     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1945       InsertAtByte = IsLE ? 0 : 12;
1946       return true;
1947     }
1948   }
1949 
1950   return false;
1951 }
1952 
1953 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1954                                bool &Swap, bool IsLE) {
1955   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1956   // Ensure each byte index of the word is consecutive.
1957   if (!isNByteElemShuffleMask(N, 4, 1))
1958     return false;
1959 
1960   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1961   unsigned M0 = N->getMaskElt(0) / 4;
1962   unsigned M1 = N->getMaskElt(4) / 4;
1963   unsigned M2 = N->getMaskElt(8) / 4;
1964   unsigned M3 = N->getMaskElt(12) / 4;
1965 
1966   // If both vector operands for the shuffle are the same vector, the mask will
1967   // contain only elements from the first one and the second one will be undef.
1968   if (N->getOperand(1).isUndef()) {
1969     assert(M0 < 4 && "Indexing into an undef vector?");
1970     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1971       return false;
1972 
1973     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1974     Swap = false;
1975     return true;
1976   }
1977 
1978   // Ensure each word index of the ShuffleVector Mask is consecutive.
1979   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1980     return false;
1981 
1982   if (IsLE) {
1983     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1984       // Input vectors don't need to be swapped if the leading element
1985       // of the result is one of the 3 left elements of the second vector
1986       // (or if there is no shift to be done at all).
1987       Swap = false;
1988       ShiftElts = (8 - M0) % 8;
1989     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1990       // Input vectors need to be swapped if the leading element
1991       // of the result is one of the 3 left elements of the first vector
1992       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1993       Swap = true;
1994       ShiftElts = (4 - M0) % 4;
1995     }
1996 
1997     return true;
1998   } else {                                          // BE
1999     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2000       // Input vectors don't need to be swapped if the leading element
2001       // of the result is one of the 4 elements of the first vector.
2002       Swap = false;
2003       ShiftElts = M0;
2004     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2005       // Input vectors need to be swapped if the leading element
2006       // of the result is one of the 4 elements of the right vector.
2007       Swap = true;
2008       ShiftElts = M0 - 4;
2009     }
2010 
2011     return true;
2012   }
2013 }
2014 
2015 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2016   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2017 
2018   if (!isNByteElemShuffleMask(N, Width, -1))
2019     return false;
2020 
2021   for (int i = 0; i < 16; i += Width)
2022     if (N->getMaskElt(i) != i + Width - 1)
2023       return false;
2024 
2025   return true;
2026 }
2027 
2028 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2029   return isXXBRShuffleMaskHelper(N, 2);
2030 }
2031 
2032 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2033   return isXXBRShuffleMaskHelper(N, 4);
2034 }
2035 
2036 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2037   return isXXBRShuffleMaskHelper(N, 8);
2038 }
2039 
2040 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2041   return isXXBRShuffleMaskHelper(N, 16);
2042 }
2043 
2044 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2045 /// if the inputs to the instruction should be swapped and set \p DM to the
2046 /// value for the immediate.
2047 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2048 /// AND element 0 of the result comes from the first input (LE) or second input
2049 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2050 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2051 /// mask.
2052 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2053                                bool &Swap, bool IsLE) {
2054   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2055 
2056   // Ensure each byte index of the double word is consecutive.
2057   if (!isNByteElemShuffleMask(N, 8, 1))
2058     return false;
2059 
2060   unsigned M0 = N->getMaskElt(0) / 8;
2061   unsigned M1 = N->getMaskElt(8) / 8;
2062   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2063 
2064   // If both vector operands for the shuffle are the same vector, the mask will
2065   // contain only elements from the first one and the second one will be undef.
2066   if (N->getOperand(1).isUndef()) {
2067     if ((M0 | M1) < 2) {
2068       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2069       Swap = false;
2070       return true;
2071     } else
2072       return false;
2073   }
2074 
2075   if (IsLE) {
2076     if (M0 > 1 && M1 < 2) {
2077       Swap = false;
2078     } else if (M0 < 2 && M1 > 1) {
2079       M0 = (M0 + 2) % 4;
2080       M1 = (M1 + 2) % 4;
2081       Swap = true;
2082     } else
2083       return false;
2084 
2085     // Note: if control flow comes here that means Swap is already set above
2086     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2087     return true;
2088   } else { // BE
2089     if (M0 < 2 && M1 > 1) {
2090       Swap = false;
2091     } else if (M0 > 1 && M1 < 2) {
2092       M0 = (M0 + 2) % 4;
2093       M1 = (M1 + 2) % 4;
2094       Swap = true;
2095     } else
2096       return false;
2097 
2098     // Note: if control flow comes here that means Swap is already set above
2099     DM = (M0 << 1) + (M1 & 1);
2100     return true;
2101   }
2102 }
2103 
2104 
2105 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2106 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2107 /// elements are counted from the left of the vector register).
2108 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2109                                          SelectionDAG &DAG) {
2110   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2111   assert(isSplatShuffleMask(SVOp, EltSize));
2112   if (DAG.getDataLayout().isLittleEndian())
2113     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2114   else
2115     return SVOp->getMaskElt(0) / EltSize;
2116 }
2117 
2118 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2119 /// by using a vspltis[bhw] instruction of the specified element size, return
2120 /// the constant being splatted.  The ByteSize field indicates the number of
2121 /// bytes of each element [124] -> [bhw].
2122 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2123   SDValue OpVal(nullptr, 0);
2124 
2125   // If ByteSize of the splat is bigger than the element size of the
2126   // build_vector, then we have a case where we are checking for a splat where
2127   // multiple elements of the buildvector are folded together into a single
2128   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2129   unsigned EltSize = 16/N->getNumOperands();
2130   if (EltSize < ByteSize) {
2131     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2132     SDValue UniquedVals[4];
2133     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2134 
2135     // See if all of the elements in the buildvector agree across.
2136     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2137       if (N->getOperand(i).isUndef()) continue;
2138       // If the element isn't a constant, bail fully out.
2139       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2140 
2141       if (!UniquedVals[i&(Multiple-1)].getNode())
2142         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2143       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2144         return SDValue();  // no match.
2145     }
2146 
2147     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2148     // either constant or undef values that are identical for each chunk.  See
2149     // if these chunks can form into a larger vspltis*.
2150 
2151     // Check to see if all of the leading entries are either 0 or -1.  If
2152     // neither, then this won't fit into the immediate field.
2153     bool LeadingZero = true;
2154     bool LeadingOnes = true;
2155     for (unsigned i = 0; i != Multiple-1; ++i) {
2156       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2157 
2158       LeadingZero &= isNullConstant(UniquedVals[i]);
2159       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2160     }
2161     // Finally, check the least significant entry.
2162     if (LeadingZero) {
2163       if (!UniquedVals[Multiple-1].getNode())
2164         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2165       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2166       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2167         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2168     }
2169     if (LeadingOnes) {
2170       if (!UniquedVals[Multiple-1].getNode())
2171         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2172       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2173       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2174         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2175     }
2176 
2177     return SDValue();
2178   }
2179 
2180   // Check to see if this buildvec has a single non-undef value in its elements.
2181   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2182     if (N->getOperand(i).isUndef()) continue;
2183     if (!OpVal.getNode())
2184       OpVal = N->getOperand(i);
2185     else if (OpVal != N->getOperand(i))
2186       return SDValue();
2187   }
2188 
2189   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2190 
2191   unsigned ValSizeInBytes = EltSize;
2192   uint64_t Value = 0;
2193   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2194     Value = CN->getZExtValue();
2195   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2196     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2197     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2198   }
2199 
2200   // If the splat value is larger than the element value, then we can never do
2201   // this splat.  The only case that we could fit the replicated bits into our
2202   // immediate field for would be zero, and we prefer to use vxor for it.
2203   if (ValSizeInBytes < ByteSize) return SDValue();
2204 
2205   // If the element value is larger than the splat value, check if it consists
2206   // of a repeated bit pattern of size ByteSize.
2207   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2208     return SDValue();
2209 
2210   // Properly sign extend the value.
2211   int MaskVal = SignExtend32(Value, ByteSize * 8);
2212 
2213   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2214   if (MaskVal == 0) return SDValue();
2215 
2216   // Finally, if this value fits in a 5 bit sext field, return it
2217   if (SignExtend32<5>(MaskVal) == MaskVal)
2218     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2219   return SDValue();
2220 }
2221 
2222 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2223 /// amount, otherwise return -1.
2224 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2225   EVT VT = N->getValueType(0);
2226   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2227     return -1;
2228 
2229   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2230 
2231   // Find the first non-undef value in the shuffle mask.
2232   unsigned i;
2233   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2234     /*search*/;
2235 
2236   if (i == 4) return -1;  // all undef.
2237 
2238   // Otherwise, check to see if the rest of the elements are consecutively
2239   // numbered from this value.
2240   unsigned ShiftAmt = SVOp->getMaskElt(i);
2241   if (ShiftAmt < i) return -1;
2242   ShiftAmt -= i;
2243 
2244   // Check the rest of the elements to see if they are consecutive.
2245   for (++i; i != 4; ++i)
2246     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2247       return -1;
2248 
2249   return ShiftAmt;
2250 }
2251 
2252 //===----------------------------------------------------------------------===//
2253 //  Addressing Mode Selection
2254 //===----------------------------------------------------------------------===//
2255 
2256 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2257 /// or 64-bit immediate, and if the value can be accurately represented as a
2258 /// sign extension from a 16-bit value.  If so, this returns true and the
2259 /// immediate.
2260 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2261   if (!isa<ConstantSDNode>(N))
2262     return false;
2263 
2264   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2265   if (N->getValueType(0) == MVT::i32)
2266     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2267   else
2268     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2269 }
2270 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2271   return isIntS16Immediate(Op.getNode(), Imm);
2272 }
2273 
2274 
2275 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2276 /// be represented as an indexed [r+r] operation.
2277 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2278                                                SDValue &Index,
2279                                                SelectionDAG &DAG) const {
2280   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2281       UI != E; ++UI) {
2282     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2283       if (Memop->getMemoryVT() == MVT::f64) {
2284           Base = N.getOperand(0);
2285           Index = N.getOperand(1);
2286           return true;
2287       }
2288     }
2289   }
2290   return false;
2291 }
2292 
2293 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2294 /// can be represented as an indexed [r+r] operation.  Returns false if it
2295 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2296 /// non-zero and N can be represented by a base register plus a signed 16-bit
2297 /// displacement, make a more precise judgement by checking (displacement % \p
2298 /// EncodingAlignment).
2299 bool PPCTargetLowering::SelectAddressRegReg(
2300     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2301     MaybeAlign EncodingAlignment) const {
2302   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2303   // a [pc+imm].
2304   if (SelectAddressPCRel(N, Base))
2305     return false;
2306 
2307   int16_t Imm = 0;
2308   if (N.getOpcode() == ISD::ADD) {
2309     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2310     // SPE load/store can only handle 8-bit offsets.
2311     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2312         return true;
2313     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2314         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2315       return false; // r+i
2316     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2317       return false;    // r+i
2318 
2319     Base = N.getOperand(0);
2320     Index = N.getOperand(1);
2321     return true;
2322   } else if (N.getOpcode() == ISD::OR) {
2323     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2324         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2325       return false; // r+i can fold it if we can.
2326 
2327     // If this is an or of disjoint bitfields, we can codegen this as an add
2328     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2329     // disjoint.
2330     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2331 
2332     if (LHSKnown.Zero.getBoolValue()) {
2333       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2334       // If all of the bits are known zero on the LHS or RHS, the add won't
2335       // carry.
2336       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2337         Base = N.getOperand(0);
2338         Index = N.getOperand(1);
2339         return true;
2340       }
2341     }
2342   }
2343 
2344   return false;
2345 }
2346 
2347 // If we happen to be doing an i64 load or store into a stack slot that has
2348 // less than a 4-byte alignment, then the frame-index elimination may need to
2349 // use an indexed load or store instruction (because the offset may not be a
2350 // multiple of 4). The extra register needed to hold the offset comes from the
2351 // register scavenger, and it is possible that the scavenger will need to use
2352 // an emergency spill slot. As a result, we need to make sure that a spill slot
2353 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2354 // stack slot.
2355 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2356   // FIXME: This does not handle the LWA case.
2357   if (VT != MVT::i64)
2358     return;
2359 
2360   // NOTE: We'll exclude negative FIs here, which come from argument
2361   // lowering, because there are no known test cases triggering this problem
2362   // using packed structures (or similar). We can remove this exclusion if
2363   // we find such a test case. The reason why this is so test-case driven is
2364   // because this entire 'fixup' is only to prevent crashes (from the
2365   // register scavenger) on not-really-valid inputs. For example, if we have:
2366   //   %a = alloca i1
2367   //   %b = bitcast i1* %a to i64*
2368   //   store i64* a, i64 b
2369   // then the store should really be marked as 'align 1', but is not. If it
2370   // were marked as 'align 1' then the indexed form would have been
2371   // instruction-selected initially, and the problem this 'fixup' is preventing
2372   // won't happen regardless.
2373   if (FrameIdx < 0)
2374     return;
2375 
2376   MachineFunction &MF = DAG.getMachineFunction();
2377   MachineFrameInfo &MFI = MF.getFrameInfo();
2378 
2379   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2380     return;
2381 
2382   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2383   FuncInfo->setHasNonRISpills();
2384 }
2385 
2386 /// Returns true if the address N can be represented by a base register plus
2387 /// a signed 16-bit displacement [r+imm], and if it is not better
2388 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2389 /// displacements that are multiples of that value.
2390 bool PPCTargetLowering::SelectAddressRegImm(
2391     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2392     MaybeAlign EncodingAlignment) const {
2393   // FIXME dl should come from parent load or store, not from address
2394   SDLoc dl(N);
2395 
2396   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2397   // a [pc+imm].
2398   if (SelectAddressPCRel(N, Base))
2399     return false;
2400 
2401   // If this can be more profitably realized as r+r, fail.
2402   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2403     return false;
2404 
2405   if (N.getOpcode() == ISD::ADD) {
2406     int16_t imm = 0;
2407     if (isIntS16Immediate(N.getOperand(1), imm) &&
2408         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2409       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2410       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2411         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2412         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2413       } else {
2414         Base = N.getOperand(0);
2415       }
2416       return true; // [r+i]
2417     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2418       // Match LOAD (ADD (X, Lo(G))).
2419       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2420              && "Cannot handle constant offsets yet!");
2421       Disp = N.getOperand(1).getOperand(0);  // The global address.
2422       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2423              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2424              Disp.getOpcode() == ISD::TargetConstantPool ||
2425              Disp.getOpcode() == ISD::TargetJumpTable);
2426       Base = N.getOperand(0);
2427       return true;  // [&g+r]
2428     }
2429   } else if (N.getOpcode() == ISD::OR) {
2430     int16_t imm = 0;
2431     if (isIntS16Immediate(N.getOperand(1), imm) &&
2432         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2433       // If this is an or of disjoint bitfields, we can codegen this as an add
2434       // (for better address arithmetic) if the LHS and RHS of the OR are
2435       // provably disjoint.
2436       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2437 
2438       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2439         // If all of the bits are known zero on the LHS or RHS, the add won't
2440         // carry.
2441         if (FrameIndexSDNode *FI =
2442               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2443           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2444           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2445         } else {
2446           Base = N.getOperand(0);
2447         }
2448         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2449         return true;
2450       }
2451     }
2452   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2453     // Loading from a constant address.
2454 
2455     // If this address fits entirely in a 16-bit sext immediate field, codegen
2456     // this as "d, 0"
2457     int16_t Imm;
2458     if (isIntS16Immediate(CN, Imm) &&
2459         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2460       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2461       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2462                              CN->getValueType(0));
2463       return true;
2464     }
2465 
2466     // Handle 32-bit sext immediates with LIS + addr mode.
2467     if ((CN->getValueType(0) == MVT::i32 ||
2468          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2469         (!EncodingAlignment ||
2470          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2471       int Addr = (int)CN->getZExtValue();
2472 
2473       // Otherwise, break this down into an LIS + disp.
2474       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2475 
2476       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2477                                    MVT::i32);
2478       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2479       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2480       return true;
2481     }
2482   }
2483 
2484   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2485   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2486     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2487     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2488   } else
2489     Base = N;
2490   return true;      // [r+0]
2491 }
2492 
2493 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2494 /// represented as an indexed [r+r] operation.
2495 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2496                                                 SDValue &Index,
2497                                                 SelectionDAG &DAG) const {
2498   // Check to see if we can easily represent this as an [r+r] address.  This
2499   // will fail if it thinks that the address is more profitably represented as
2500   // reg+imm, e.g. where imm = 0.
2501   if (SelectAddressRegReg(N, Base, Index, DAG))
2502     return true;
2503 
2504   // If the address is the result of an add, we will utilize the fact that the
2505   // address calculation includes an implicit add.  However, we can reduce
2506   // register pressure if we do not materialize a constant just for use as the
2507   // index register.  We only get rid of the add if it is not an add of a
2508   // value and a 16-bit signed constant and both have a single use.
2509   int16_t imm = 0;
2510   if (N.getOpcode() == ISD::ADD &&
2511       (!isIntS16Immediate(N.getOperand(1), imm) ||
2512        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2513     Base = N.getOperand(0);
2514     Index = N.getOperand(1);
2515     return true;
2516   }
2517 
2518   // Otherwise, do it the hard way, using R0 as the base register.
2519   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2520                          N.getValueType());
2521   Index = N;
2522   return true;
2523 }
2524 
2525 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2526   Ty *PCRelCand = dyn_cast<Ty>(N);
2527   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2528 }
2529 
2530 /// Returns true if this address is a PC Relative address.
2531 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2532 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2533 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2534   // This is a materialize PC Relative node. Always select this as PC Relative.
2535   Base = N;
2536   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2537     return true;
2538   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2539       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2540       isValidPCRelNode<JumpTableSDNode>(N) ||
2541       isValidPCRelNode<BlockAddressSDNode>(N))
2542     return true;
2543   return false;
2544 }
2545 
2546 /// Returns true if we should use a direct load into vector instruction
2547 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2548 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2549 
2550   // If there are any other uses other than scalar to vector, then we should
2551   // keep it as a scalar load -> direct move pattern to prevent multiple
2552   // loads.
2553   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2554   if (!LD)
2555     return false;
2556 
2557   EVT MemVT = LD->getMemoryVT();
2558   if (!MemVT.isSimple())
2559     return false;
2560   switch(MemVT.getSimpleVT().SimpleTy) {
2561   case MVT::i64:
2562     break;
2563   case MVT::i32:
2564     if (!ST.hasP8Vector())
2565       return false;
2566     break;
2567   case MVT::i16:
2568   case MVT::i8:
2569     if (!ST.hasP9Vector())
2570       return false;
2571     break;
2572   default:
2573     return false;
2574   }
2575 
2576   SDValue LoadedVal(N, 0);
2577   if (!LoadedVal.hasOneUse())
2578     return false;
2579 
2580   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2581        UI != UE; ++UI)
2582     if (UI.getUse().get().getResNo() == 0 &&
2583         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2584         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2585       return false;
2586 
2587   return true;
2588 }
2589 
2590 /// getPreIndexedAddressParts - returns true by value, base pointer and
2591 /// offset pointer and addressing mode by reference if the node's address
2592 /// can be legally represented as pre-indexed load / store address.
2593 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2594                                                   SDValue &Offset,
2595                                                   ISD::MemIndexedMode &AM,
2596                                                   SelectionDAG &DAG) const {
2597   if (DisablePPCPreinc) return false;
2598 
2599   bool isLoad = true;
2600   SDValue Ptr;
2601   EVT VT;
2602   unsigned Alignment;
2603   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2604     Ptr = LD->getBasePtr();
2605     VT = LD->getMemoryVT();
2606     Alignment = LD->getAlignment();
2607   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2608     Ptr = ST->getBasePtr();
2609     VT  = ST->getMemoryVT();
2610     Alignment = ST->getAlignment();
2611     isLoad = false;
2612   } else
2613     return false;
2614 
2615   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2616   // instructions because we can fold these into a more efficient instruction
2617   // instead, (such as LXSD).
2618   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2619     return false;
2620   }
2621 
2622   // PowerPC doesn't have preinc load/store instructions for vectors
2623   if (VT.isVector())
2624     return false;
2625 
2626   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2627     // Common code will reject creating a pre-inc form if the base pointer
2628     // is a frame index, or if N is a store and the base pointer is either
2629     // the same as or a predecessor of the value being stored.  Check for
2630     // those situations here, and try with swapped Base/Offset instead.
2631     bool Swap = false;
2632 
2633     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2634       Swap = true;
2635     else if (!isLoad) {
2636       SDValue Val = cast<StoreSDNode>(N)->getValue();
2637       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2638         Swap = true;
2639     }
2640 
2641     if (Swap)
2642       std::swap(Base, Offset);
2643 
2644     AM = ISD::PRE_INC;
2645     return true;
2646   }
2647 
2648   // LDU/STU can only handle immediates that are a multiple of 4.
2649   if (VT != MVT::i64) {
2650     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2651       return false;
2652   } else {
2653     // LDU/STU need an address with at least 4-byte alignment.
2654     if (Alignment < 4)
2655       return false;
2656 
2657     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2658       return false;
2659   }
2660 
2661   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2662     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2663     // sext i32 to i64 when addr mode is r+i.
2664     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2665         LD->getExtensionType() == ISD::SEXTLOAD &&
2666         isa<ConstantSDNode>(Offset))
2667       return false;
2668   }
2669 
2670   AM = ISD::PRE_INC;
2671   return true;
2672 }
2673 
2674 //===----------------------------------------------------------------------===//
2675 //  LowerOperation implementation
2676 //===----------------------------------------------------------------------===//
2677 
2678 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2679 /// and LoOpFlags to the target MO flags.
2680 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2681                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2682                                const GlobalValue *GV = nullptr) {
2683   HiOpFlags = PPCII::MO_HA;
2684   LoOpFlags = PPCII::MO_LO;
2685 
2686   // Don't use the pic base if not in PIC relocation model.
2687   if (IsPIC) {
2688     HiOpFlags |= PPCII::MO_PIC_FLAG;
2689     LoOpFlags |= PPCII::MO_PIC_FLAG;
2690   }
2691 }
2692 
2693 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2694                              SelectionDAG &DAG) {
2695   SDLoc DL(HiPart);
2696   EVT PtrVT = HiPart.getValueType();
2697   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2698 
2699   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2700   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2701 
2702   // With PIC, the first instruction is actually "GR+hi(&G)".
2703   if (isPIC)
2704     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2705                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2706 
2707   // Generate non-pic code that has direct accesses to the constant pool.
2708   // The address of the global is just (hi(&g)+lo(&g)).
2709   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2710 }
2711 
2712 static void setUsesTOCBasePtr(MachineFunction &MF) {
2713   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2714   FuncInfo->setUsesTOCBasePtr();
2715 }
2716 
2717 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2718   setUsesTOCBasePtr(DAG.getMachineFunction());
2719 }
2720 
2721 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2722                                        SDValue GA) const {
2723   const bool Is64Bit = Subtarget.isPPC64();
2724   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2725   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2726                         : Subtarget.isAIXABI()
2727                               ? DAG.getRegister(PPC::R2, VT)
2728                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2729   SDValue Ops[] = { GA, Reg };
2730   return DAG.getMemIntrinsicNode(
2731       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2732       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2733       MachineMemOperand::MOLoad);
2734 }
2735 
2736 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2737                                              SelectionDAG &DAG) const {
2738   EVT PtrVT = Op.getValueType();
2739   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2740   const Constant *C = CP->getConstVal();
2741 
2742   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2743   // The actual address of the GlobalValue is stored in the TOC.
2744   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2745     if (Subtarget.isUsingPCRelativeCalls()) {
2746       SDLoc DL(CP);
2747       EVT Ty = getPointerTy(DAG.getDataLayout());
2748       SDValue ConstPool = DAG.getTargetConstantPool(
2749           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2750       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2751     }
2752     setUsesTOCBasePtr(DAG);
2753     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2754     return getTOCEntry(DAG, SDLoc(CP), GA);
2755   }
2756 
2757   unsigned MOHiFlag, MOLoFlag;
2758   bool IsPIC = isPositionIndependent();
2759   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2760 
2761   if (IsPIC && Subtarget.isSVR4ABI()) {
2762     SDValue GA =
2763         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2764     return getTOCEntry(DAG, SDLoc(CP), GA);
2765   }
2766 
2767   SDValue CPIHi =
2768       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2769   SDValue CPILo =
2770       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2771   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2772 }
2773 
2774 // For 64-bit PowerPC, prefer the more compact relative encodings.
2775 // This trades 32 bits per jump table entry for one or two instructions
2776 // on the jump site.
2777 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2778   if (isJumpTableRelative())
2779     return MachineJumpTableInfo::EK_LabelDifference32;
2780 
2781   return TargetLowering::getJumpTableEncoding();
2782 }
2783 
2784 bool PPCTargetLowering::isJumpTableRelative() const {
2785   if (UseAbsoluteJumpTables)
2786     return false;
2787   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2788     return true;
2789   return TargetLowering::isJumpTableRelative();
2790 }
2791 
2792 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2793                                                     SelectionDAG &DAG) const {
2794   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2795     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2796 
2797   switch (getTargetMachine().getCodeModel()) {
2798   case CodeModel::Small:
2799   case CodeModel::Medium:
2800     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2801   default:
2802     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2803                        getPointerTy(DAG.getDataLayout()));
2804   }
2805 }
2806 
2807 const MCExpr *
2808 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2809                                                 unsigned JTI,
2810                                                 MCContext &Ctx) const {
2811   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2812     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2813 
2814   switch (getTargetMachine().getCodeModel()) {
2815   case CodeModel::Small:
2816   case CodeModel::Medium:
2817     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2818   default:
2819     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2820   }
2821 }
2822 
2823 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2824   EVT PtrVT = Op.getValueType();
2825   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2826 
2827   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2828   if (Subtarget.isUsingPCRelativeCalls()) {
2829     SDLoc DL(JT);
2830     EVT Ty = getPointerTy(DAG.getDataLayout());
2831     SDValue GA =
2832         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2833     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2834     return MatAddr;
2835   }
2836 
2837   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2838   // The actual address of the GlobalValue is stored in the TOC.
2839   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2840     setUsesTOCBasePtr(DAG);
2841     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2842     return getTOCEntry(DAG, SDLoc(JT), GA);
2843   }
2844 
2845   unsigned MOHiFlag, MOLoFlag;
2846   bool IsPIC = isPositionIndependent();
2847   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2848 
2849   if (IsPIC && Subtarget.isSVR4ABI()) {
2850     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2851                                         PPCII::MO_PIC_FLAG);
2852     return getTOCEntry(DAG, SDLoc(GA), GA);
2853   }
2854 
2855   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2856   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2857   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2858 }
2859 
2860 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2861                                              SelectionDAG &DAG) const {
2862   EVT PtrVT = Op.getValueType();
2863   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2864   const BlockAddress *BA = BASDN->getBlockAddress();
2865 
2866   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2867   if (Subtarget.isUsingPCRelativeCalls()) {
2868     SDLoc DL(BASDN);
2869     EVT Ty = getPointerTy(DAG.getDataLayout());
2870     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2871                                            PPCII::MO_PCREL_FLAG);
2872     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2873     return MatAddr;
2874   }
2875 
2876   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2877   // The actual BlockAddress is stored in the TOC.
2878   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2879     setUsesTOCBasePtr(DAG);
2880     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2881     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2882   }
2883 
2884   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2885   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2886     return getTOCEntry(
2887         DAG, SDLoc(BASDN),
2888         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2889 
2890   unsigned MOHiFlag, MOLoFlag;
2891   bool IsPIC = isPositionIndependent();
2892   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2893   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2894   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2895   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2896 }
2897 
2898 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2899                                               SelectionDAG &DAG) const {
2900   // FIXME: TLS addresses currently use medium model code sequences,
2901   // which is the most useful form.  Eventually support for small and
2902   // large models could be added if users need it, at the cost of
2903   // additional complexity.
2904   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2905   if (DAG.getTarget().useEmulatedTLS())
2906     return LowerToTLSEmulatedModel(GA, DAG);
2907 
2908   SDLoc dl(GA);
2909   const GlobalValue *GV = GA->getGlobal();
2910   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2911   bool is64bit = Subtarget.isPPC64();
2912   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2913   PICLevel::Level picLevel = M->getPICLevel();
2914 
2915   const TargetMachine &TM = getTargetMachine();
2916   TLSModel::Model Model = TM.getTLSModel(GV);
2917 
2918   if (Model == TLSModel::LocalExec) {
2919     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2920                                                PPCII::MO_TPREL_HA);
2921     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2922                                                PPCII::MO_TPREL_LO);
2923     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2924                              : DAG.getRegister(PPC::R2, MVT::i32);
2925 
2926     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2927     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2928   }
2929 
2930   if (Model == TLSModel::InitialExec) {
2931     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2932     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2933                                                 PPCII::MO_TLS);
2934     SDValue GOTPtr;
2935     if (is64bit) {
2936       setUsesTOCBasePtr(DAG);
2937       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2938       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2939                            PtrVT, GOTReg, TGA);
2940     } else {
2941       if (!TM.isPositionIndependent())
2942         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2943       else if (picLevel == PICLevel::SmallPIC)
2944         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2945       else
2946         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2947     }
2948     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2949                                    PtrVT, TGA, GOTPtr);
2950     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2951   }
2952 
2953   if (Model == TLSModel::GeneralDynamic) {
2954     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2955     SDValue GOTPtr;
2956     if (is64bit) {
2957       setUsesTOCBasePtr(DAG);
2958       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2959       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2960                                    GOTReg, TGA);
2961     } else {
2962       if (picLevel == PICLevel::SmallPIC)
2963         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2964       else
2965         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2966     }
2967     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2968                        GOTPtr, TGA, TGA);
2969   }
2970 
2971   if (Model == TLSModel::LocalDynamic) {
2972     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2973     SDValue GOTPtr;
2974     if (is64bit) {
2975       setUsesTOCBasePtr(DAG);
2976       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2977       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2978                            GOTReg, TGA);
2979     } else {
2980       if (picLevel == PICLevel::SmallPIC)
2981         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2982       else
2983         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2984     }
2985     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2986                                   PtrVT, GOTPtr, TGA, TGA);
2987     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2988                                       PtrVT, TLSAddr, TGA);
2989     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2990   }
2991 
2992   llvm_unreachable("Unknown TLS model!");
2993 }
2994 
2995 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2996                                               SelectionDAG &DAG) const {
2997   EVT PtrVT = Op.getValueType();
2998   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2999   SDLoc DL(GSDN);
3000   const GlobalValue *GV = GSDN->getGlobal();
3001 
3002   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3003   // The actual address of the GlobalValue is stored in the TOC.
3004   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3005     if (Subtarget.isUsingPCRelativeCalls()) {
3006       EVT Ty = getPointerTy(DAG.getDataLayout());
3007       if (isAccessedAsGotIndirect(Op)) {
3008         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3009                                                 PPCII::MO_PCREL_FLAG |
3010                                                     PPCII::MO_GOT_FLAG);
3011         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3012         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3013                                    MachinePointerInfo());
3014         return Load;
3015       } else {
3016         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3017                                                 PPCII::MO_PCREL_FLAG);
3018         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3019       }
3020     }
3021     setUsesTOCBasePtr(DAG);
3022     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3023     return getTOCEntry(DAG, DL, GA);
3024   }
3025 
3026   unsigned MOHiFlag, MOLoFlag;
3027   bool IsPIC = isPositionIndependent();
3028   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3029 
3030   if (IsPIC && Subtarget.isSVR4ABI()) {
3031     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3032                                             GSDN->getOffset(),
3033                                             PPCII::MO_PIC_FLAG);
3034     return getTOCEntry(DAG, DL, GA);
3035   }
3036 
3037   SDValue GAHi =
3038     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3039   SDValue GALo =
3040     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3041 
3042   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3043 }
3044 
3045 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3046   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3047   SDLoc dl(Op);
3048 
3049   if (Op.getValueType() == MVT::v2i64) {
3050     // When the operands themselves are v2i64 values, we need to do something
3051     // special because VSX has no underlying comparison operations for these.
3052     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3053       // Equality can be handled by casting to the legal type for Altivec
3054       // comparisons, everything else needs to be expanded.
3055       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3056         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3057                  DAG.getSetCC(dl, MVT::v4i32,
3058                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3059                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3060                    CC));
3061       }
3062 
3063       return SDValue();
3064     }
3065 
3066     // We handle most of these in the usual way.
3067     return Op;
3068   }
3069 
3070   // If we're comparing for equality to zero, expose the fact that this is
3071   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3072   // fold the new nodes.
3073   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3074     return V;
3075 
3076   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3077     // Leave comparisons against 0 and -1 alone for now, since they're usually
3078     // optimized.  FIXME: revisit this when we can custom lower all setcc
3079     // optimizations.
3080     if (C->isAllOnesValue() || C->isNullValue())
3081       return SDValue();
3082   }
3083 
3084   // If we have an integer seteq/setne, turn it into a compare against zero
3085   // by xor'ing the rhs with the lhs, which is faster than setting a
3086   // condition register, reading it back out, and masking the correct bit.  The
3087   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3088   // the result to other bit-twiddling opportunities.
3089   EVT LHSVT = Op.getOperand(0).getValueType();
3090   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3091     EVT VT = Op.getValueType();
3092     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3093                                 Op.getOperand(1));
3094     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3095   }
3096   return SDValue();
3097 }
3098 
3099 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3100   SDNode *Node = Op.getNode();
3101   EVT VT = Node->getValueType(0);
3102   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3103   SDValue InChain = Node->getOperand(0);
3104   SDValue VAListPtr = Node->getOperand(1);
3105   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3106   SDLoc dl(Node);
3107 
3108   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3109 
3110   // gpr_index
3111   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3112                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3113   InChain = GprIndex.getValue(1);
3114 
3115   if (VT == MVT::i64) {
3116     // Check if GprIndex is even
3117     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3118                                  DAG.getConstant(1, dl, MVT::i32));
3119     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3120                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3121     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3122                                           DAG.getConstant(1, dl, MVT::i32));
3123     // Align GprIndex to be even if it isn't
3124     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3125                            GprIndex);
3126   }
3127 
3128   // fpr index is 1 byte after gpr
3129   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3130                                DAG.getConstant(1, dl, MVT::i32));
3131 
3132   // fpr
3133   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3134                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3135   InChain = FprIndex.getValue(1);
3136 
3137   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3138                                        DAG.getConstant(8, dl, MVT::i32));
3139 
3140   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3141                                         DAG.getConstant(4, dl, MVT::i32));
3142 
3143   // areas
3144   SDValue OverflowArea =
3145       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3146   InChain = OverflowArea.getValue(1);
3147 
3148   SDValue RegSaveArea =
3149       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3150   InChain = RegSaveArea.getValue(1);
3151 
3152   // select overflow_area if index > 8
3153   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3154                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3155 
3156   // adjustment constant gpr_index * 4/8
3157   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3158                                     VT.isInteger() ? GprIndex : FprIndex,
3159                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3160                                                     MVT::i32));
3161 
3162   // OurReg = RegSaveArea + RegConstant
3163   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3164                                RegConstant);
3165 
3166   // Floating types are 32 bytes into RegSaveArea
3167   if (VT.isFloatingPoint())
3168     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3169                          DAG.getConstant(32, dl, MVT::i32));
3170 
3171   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3172   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3173                                    VT.isInteger() ? GprIndex : FprIndex,
3174                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3175                                                    MVT::i32));
3176 
3177   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3178                               VT.isInteger() ? VAListPtr : FprPtr,
3179                               MachinePointerInfo(SV), MVT::i8);
3180 
3181   // determine if we should load from reg_save_area or overflow_area
3182   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3183 
3184   // increase overflow_area by 4/8 if gpr/fpr > 8
3185   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3186                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3187                                           dl, MVT::i32));
3188 
3189   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3190                              OverflowAreaPlusN);
3191 
3192   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3193                               MachinePointerInfo(), MVT::i32);
3194 
3195   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3196 }
3197 
3198 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3199   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3200 
3201   // We have to copy the entire va_list struct:
3202   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3203   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3204                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3205                        false, true, false, MachinePointerInfo(),
3206                        MachinePointerInfo());
3207 }
3208 
3209 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3210                                                   SelectionDAG &DAG) const {
3211   if (Subtarget.isAIXABI())
3212     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3213 
3214   return Op.getOperand(0);
3215 }
3216 
3217 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3218                                                 SelectionDAG &DAG) const {
3219   if (Subtarget.isAIXABI())
3220     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3221 
3222   SDValue Chain = Op.getOperand(0);
3223   SDValue Trmp = Op.getOperand(1); // trampoline
3224   SDValue FPtr = Op.getOperand(2); // nested function
3225   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3226   SDLoc dl(Op);
3227 
3228   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3229   bool isPPC64 = (PtrVT == MVT::i64);
3230   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3231 
3232   TargetLowering::ArgListTy Args;
3233   TargetLowering::ArgListEntry Entry;
3234 
3235   Entry.Ty = IntPtrTy;
3236   Entry.Node = Trmp; Args.push_back(Entry);
3237 
3238   // TrampSize == (isPPC64 ? 48 : 40);
3239   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3240                                isPPC64 ? MVT::i64 : MVT::i32);
3241   Args.push_back(Entry);
3242 
3243   Entry.Node = FPtr; Args.push_back(Entry);
3244   Entry.Node = Nest; Args.push_back(Entry);
3245 
3246   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3247   TargetLowering::CallLoweringInfo CLI(DAG);
3248   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3249       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3250       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3251 
3252   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3253   return CallResult.second;
3254 }
3255 
3256 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3257   MachineFunction &MF = DAG.getMachineFunction();
3258   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3259   EVT PtrVT = getPointerTy(MF.getDataLayout());
3260 
3261   SDLoc dl(Op);
3262 
3263   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3264     // vastart just stores the address of the VarArgsFrameIndex slot into the
3265     // memory location argument.
3266     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3267     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3268     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3269                         MachinePointerInfo(SV));
3270   }
3271 
3272   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3273   // We suppose the given va_list is already allocated.
3274   //
3275   // typedef struct {
3276   //  char gpr;     /* index into the array of 8 GPRs
3277   //                 * stored in the register save area
3278   //                 * gpr=0 corresponds to r3,
3279   //                 * gpr=1 to r4, etc.
3280   //                 */
3281   //  char fpr;     /* index into the array of 8 FPRs
3282   //                 * stored in the register save area
3283   //                 * fpr=0 corresponds to f1,
3284   //                 * fpr=1 to f2, etc.
3285   //                 */
3286   //  char *overflow_arg_area;
3287   //                /* location on stack that holds
3288   //                 * the next overflow argument
3289   //                 */
3290   //  char *reg_save_area;
3291   //               /* where r3:r10 and f1:f8 (if saved)
3292   //                * are stored
3293   //                */
3294   // } va_list[1];
3295 
3296   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3297   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3298   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3299                                             PtrVT);
3300   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3301                                  PtrVT);
3302 
3303   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3304   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3305 
3306   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3307   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3308 
3309   uint64_t FPROffset = 1;
3310   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3311 
3312   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3313 
3314   // Store first byte : number of int regs
3315   SDValue firstStore =
3316       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3317                         MachinePointerInfo(SV), MVT::i8);
3318   uint64_t nextOffset = FPROffset;
3319   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3320                                   ConstFPROffset);
3321 
3322   // Store second byte : number of float regs
3323   SDValue secondStore =
3324       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3325                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3326   nextOffset += StackOffset;
3327   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3328 
3329   // Store second word : arguments given on stack
3330   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3331                                     MachinePointerInfo(SV, nextOffset));
3332   nextOffset += FrameOffset;
3333   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3334 
3335   // Store third word : arguments given in registers
3336   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3337                       MachinePointerInfo(SV, nextOffset));
3338 }
3339 
3340 /// FPR - The set of FP registers that should be allocated for arguments
3341 /// on Darwin and AIX.
3342 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3343                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3344                                 PPC::F11, PPC::F12, PPC::F13};
3345 
3346 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3347 /// the stack.
3348 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3349                                        unsigned PtrByteSize) {
3350   unsigned ArgSize = ArgVT.getStoreSize();
3351   if (Flags.isByVal())
3352     ArgSize = Flags.getByValSize();
3353 
3354   // Round up to multiples of the pointer size, except for array members,
3355   // which are always packed.
3356   if (!Flags.isInConsecutiveRegs())
3357     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3358 
3359   return ArgSize;
3360 }
3361 
3362 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3363 /// on the stack.
3364 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3365                                          ISD::ArgFlagsTy Flags,
3366                                          unsigned PtrByteSize) {
3367   Align Alignment(PtrByteSize);
3368 
3369   // Altivec parameters are padded to a 16 byte boundary.
3370   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3371       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3372       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3373       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3374     Alignment = Align(16);
3375 
3376   // ByVal parameters are aligned as requested.
3377   if (Flags.isByVal()) {
3378     auto BVAlign = Flags.getNonZeroByValAlign();
3379     if (BVAlign > PtrByteSize) {
3380       if (BVAlign.value() % PtrByteSize != 0)
3381         llvm_unreachable(
3382             "ByVal alignment is not a multiple of the pointer size");
3383 
3384       Alignment = BVAlign;
3385     }
3386   }
3387 
3388   // Array members are always packed to their original alignment.
3389   if (Flags.isInConsecutiveRegs()) {
3390     // If the array member was split into multiple registers, the first
3391     // needs to be aligned to the size of the full type.  (Except for
3392     // ppcf128, which is only aligned as its f64 components.)
3393     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3394       Alignment = Align(OrigVT.getStoreSize());
3395     else
3396       Alignment = Align(ArgVT.getStoreSize());
3397   }
3398 
3399   return Alignment;
3400 }
3401 
3402 /// CalculateStackSlotUsed - Return whether this argument will use its
3403 /// stack slot (instead of being passed in registers).  ArgOffset,
3404 /// AvailableFPRs, and AvailableVRs must hold the current argument
3405 /// position, and will be updated to account for this argument.
3406 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3407                                    unsigned PtrByteSize, unsigned LinkageSize,
3408                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3409                                    unsigned &AvailableFPRs,
3410                                    unsigned &AvailableVRs) {
3411   bool UseMemory = false;
3412 
3413   // Respect alignment of argument on the stack.
3414   Align Alignment =
3415       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3416   ArgOffset = alignTo(ArgOffset, Alignment);
3417   // If there's no space left in the argument save area, we must
3418   // use memory (this check also catches zero-sized arguments).
3419   if (ArgOffset >= LinkageSize + ParamAreaSize)
3420     UseMemory = true;
3421 
3422   // Allocate argument on the stack.
3423   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3424   if (Flags.isInConsecutiveRegsLast())
3425     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3426   // If we overran the argument save area, we must use memory
3427   // (this check catches arguments passed partially in memory)
3428   if (ArgOffset > LinkageSize + ParamAreaSize)
3429     UseMemory = true;
3430 
3431   // However, if the argument is actually passed in an FPR or a VR,
3432   // we don't use memory after all.
3433   if (!Flags.isByVal()) {
3434     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3435       if (AvailableFPRs > 0) {
3436         --AvailableFPRs;
3437         return false;
3438       }
3439     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3440         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3441         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3442         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3443       if (AvailableVRs > 0) {
3444         --AvailableVRs;
3445         return false;
3446       }
3447   }
3448 
3449   return UseMemory;
3450 }
3451 
3452 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3453 /// ensure minimum alignment required for target.
3454 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3455                                      unsigned NumBytes) {
3456   return alignTo(NumBytes, Lowering->getStackAlign());
3457 }
3458 
3459 SDValue PPCTargetLowering::LowerFormalArguments(
3460     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3461     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3462     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3463   if (Subtarget.isAIXABI())
3464     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3465                                     InVals);
3466   if (Subtarget.is64BitELFABI())
3467     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3468                                        InVals);
3469   if (Subtarget.is32BitELFABI())
3470     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3471                                        InVals);
3472 
3473   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3474                                      InVals);
3475 }
3476 
3477 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3478     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3479     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3480     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3481 
3482   // 32-bit SVR4 ABI Stack Frame Layout:
3483   //              +-----------------------------------+
3484   //        +-->  |            Back chain             |
3485   //        |     +-----------------------------------+
3486   //        |     | Floating-point register save area |
3487   //        |     +-----------------------------------+
3488   //        |     |    General register save area     |
3489   //        |     +-----------------------------------+
3490   //        |     |          CR save word             |
3491   //        |     +-----------------------------------+
3492   //        |     |         VRSAVE save word          |
3493   //        |     +-----------------------------------+
3494   //        |     |         Alignment padding         |
3495   //        |     +-----------------------------------+
3496   //        |     |     Vector register save area     |
3497   //        |     +-----------------------------------+
3498   //        |     |       Local variable space        |
3499   //        |     +-----------------------------------+
3500   //        |     |        Parameter list area        |
3501   //        |     +-----------------------------------+
3502   //        |     |           LR save word            |
3503   //        |     +-----------------------------------+
3504   // SP-->  +---  |            Back chain             |
3505   //              +-----------------------------------+
3506   //
3507   // Specifications:
3508   //   System V Application Binary Interface PowerPC Processor Supplement
3509   //   AltiVec Technology Programming Interface Manual
3510 
3511   MachineFunction &MF = DAG.getMachineFunction();
3512   MachineFrameInfo &MFI = MF.getFrameInfo();
3513   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3514 
3515   EVT PtrVT = getPointerTy(MF.getDataLayout());
3516   // Potential tail calls could cause overwriting of argument stack slots.
3517   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3518                        (CallConv == CallingConv::Fast));
3519   const Align PtrAlign(4);
3520 
3521   // Assign locations to all of the incoming arguments.
3522   SmallVector<CCValAssign, 16> ArgLocs;
3523   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3524                  *DAG.getContext());
3525 
3526   // Reserve space for the linkage area on the stack.
3527   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3528   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3529   if (useSoftFloat())
3530     CCInfo.PreAnalyzeFormalArguments(Ins);
3531 
3532   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3533   CCInfo.clearWasPPCF128();
3534 
3535   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3536     CCValAssign &VA = ArgLocs[i];
3537 
3538     // Arguments stored in registers.
3539     if (VA.isRegLoc()) {
3540       const TargetRegisterClass *RC;
3541       EVT ValVT = VA.getValVT();
3542 
3543       switch (ValVT.getSimpleVT().SimpleTy) {
3544         default:
3545           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3546         case MVT::i1:
3547         case MVT::i32:
3548           RC = &PPC::GPRCRegClass;
3549           break;
3550         case MVT::f32:
3551           if (Subtarget.hasP8Vector())
3552             RC = &PPC::VSSRCRegClass;
3553           else if (Subtarget.hasSPE())
3554             RC = &PPC::GPRCRegClass;
3555           else
3556             RC = &PPC::F4RCRegClass;
3557           break;
3558         case MVT::f64:
3559           if (Subtarget.hasVSX())
3560             RC = &PPC::VSFRCRegClass;
3561           else if (Subtarget.hasSPE())
3562             // SPE passes doubles in GPR pairs.
3563             RC = &PPC::GPRCRegClass;
3564           else
3565             RC = &PPC::F8RCRegClass;
3566           break;
3567         case MVT::v16i8:
3568         case MVT::v8i16:
3569         case MVT::v4i32:
3570           RC = &PPC::VRRCRegClass;
3571           break;
3572         case MVT::v4f32:
3573           RC = &PPC::VRRCRegClass;
3574           break;
3575         case MVT::v2f64:
3576         case MVT::v2i64:
3577           RC = &PPC::VRRCRegClass;
3578           break;
3579       }
3580 
3581       SDValue ArgValue;
3582       // Transform the arguments stored in physical registers into
3583       // virtual ones.
3584       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3585         assert(i + 1 < e && "No second half of double precision argument");
3586         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3587         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3588         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3589         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3590         if (!Subtarget.isLittleEndian())
3591           std::swap (ArgValueLo, ArgValueHi);
3592         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3593                                ArgValueHi);
3594       } else {
3595         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3596         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3597                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3598         if (ValVT == MVT::i1)
3599           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3600       }
3601 
3602       InVals.push_back(ArgValue);
3603     } else {
3604       // Argument stored in memory.
3605       assert(VA.isMemLoc());
3606 
3607       // Get the extended size of the argument type in stack
3608       unsigned ArgSize = VA.getLocVT().getStoreSize();
3609       // Get the actual size of the argument type
3610       unsigned ObjSize = VA.getValVT().getStoreSize();
3611       unsigned ArgOffset = VA.getLocMemOffset();
3612       // Stack objects in PPC32 are right justified.
3613       ArgOffset += ArgSize - ObjSize;
3614       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3615 
3616       // Create load nodes to retrieve arguments from the stack.
3617       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3618       InVals.push_back(
3619           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3620     }
3621   }
3622 
3623   // Assign locations to all of the incoming aggregate by value arguments.
3624   // Aggregates passed by value are stored in the local variable space of the
3625   // caller's stack frame, right above the parameter list area.
3626   SmallVector<CCValAssign, 16> ByValArgLocs;
3627   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3628                       ByValArgLocs, *DAG.getContext());
3629 
3630   // Reserve stack space for the allocations in CCInfo.
3631   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3632 
3633   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3634 
3635   // Area that is at least reserved in the caller of this function.
3636   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3637   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3638 
3639   // Set the size that is at least reserved in caller of this function.  Tail
3640   // call optimized function's reserved stack space needs to be aligned so that
3641   // taking the difference between two stack areas will result in an aligned
3642   // stack.
3643   MinReservedArea =
3644       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3645   FuncInfo->setMinReservedArea(MinReservedArea);
3646 
3647   SmallVector<SDValue, 8> MemOps;
3648 
3649   // If the function takes variable number of arguments, make a frame index for
3650   // the start of the first vararg value... for expansion of llvm.va_start.
3651   if (isVarArg) {
3652     static const MCPhysReg GPArgRegs[] = {
3653       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3654       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3655     };
3656     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3657 
3658     static const MCPhysReg FPArgRegs[] = {
3659       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3660       PPC::F8
3661     };
3662     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3663 
3664     if (useSoftFloat() || hasSPE())
3665        NumFPArgRegs = 0;
3666 
3667     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3668     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3669 
3670     // Make room for NumGPArgRegs and NumFPArgRegs.
3671     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3672                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3673 
3674     FuncInfo->setVarArgsStackOffset(
3675       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3676                             CCInfo.getNextStackOffset(), true));
3677 
3678     FuncInfo->setVarArgsFrameIndex(
3679         MFI.CreateStackObject(Depth, Align(8), false));
3680     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3681 
3682     // The fixed integer arguments of a variadic function are stored to the
3683     // VarArgsFrameIndex on the stack so that they may be loaded by
3684     // dereferencing the result of va_next.
3685     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3686       // Get an existing live-in vreg, or add a new one.
3687       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3688       if (!VReg)
3689         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3690 
3691       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3692       SDValue Store =
3693           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3694       MemOps.push_back(Store);
3695       // Increment the address by four for the next argument to store
3696       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3697       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3698     }
3699 
3700     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3701     // is set.
3702     // The double arguments are stored to the VarArgsFrameIndex
3703     // on the stack.
3704     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3705       // Get an existing live-in vreg, or add a new one.
3706       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3707       if (!VReg)
3708         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3709 
3710       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3711       SDValue Store =
3712           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3713       MemOps.push_back(Store);
3714       // Increment the address by eight for the next argument to store
3715       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3716                                          PtrVT);
3717       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3718     }
3719   }
3720 
3721   if (!MemOps.empty())
3722     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3723 
3724   return Chain;
3725 }
3726 
3727 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3728 // value to MVT::i64 and then truncate to the correct register size.
3729 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3730                                              EVT ObjectVT, SelectionDAG &DAG,
3731                                              SDValue ArgVal,
3732                                              const SDLoc &dl) const {
3733   if (Flags.isSExt())
3734     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3735                          DAG.getValueType(ObjectVT));
3736   else if (Flags.isZExt())
3737     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3738                          DAG.getValueType(ObjectVT));
3739 
3740   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3741 }
3742 
3743 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3744     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3745     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3746     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3747   // TODO: add description of PPC stack frame format, or at least some docs.
3748   //
3749   bool isELFv2ABI = Subtarget.isELFv2ABI();
3750   bool isLittleEndian = Subtarget.isLittleEndian();
3751   MachineFunction &MF = DAG.getMachineFunction();
3752   MachineFrameInfo &MFI = MF.getFrameInfo();
3753   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3754 
3755   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3756          "fastcc not supported on varargs functions");
3757 
3758   EVT PtrVT = getPointerTy(MF.getDataLayout());
3759   // Potential tail calls could cause overwriting of argument stack slots.
3760   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3761                        (CallConv == CallingConv::Fast));
3762   unsigned PtrByteSize = 8;
3763   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3764 
3765   static const MCPhysReg GPR[] = {
3766     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3767     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3768   };
3769   static const MCPhysReg VR[] = {
3770     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3771     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3772   };
3773 
3774   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3775   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3776   const unsigned Num_VR_Regs  = array_lengthof(VR);
3777 
3778   // Do a first pass over the arguments to determine whether the ABI
3779   // guarantees that our caller has allocated the parameter save area
3780   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3781   // in the ELFv2 ABI, it is true if this is a vararg function or if
3782   // any parameter is located in a stack slot.
3783 
3784   bool HasParameterArea = !isELFv2ABI || isVarArg;
3785   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3786   unsigned NumBytes = LinkageSize;
3787   unsigned AvailableFPRs = Num_FPR_Regs;
3788   unsigned AvailableVRs = Num_VR_Regs;
3789   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3790     if (Ins[i].Flags.isNest())
3791       continue;
3792 
3793     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3794                                PtrByteSize, LinkageSize, ParamAreaSize,
3795                                NumBytes, AvailableFPRs, AvailableVRs))
3796       HasParameterArea = true;
3797   }
3798 
3799   // Add DAG nodes to load the arguments or copy them out of registers.  On
3800   // entry to a function on PPC, the arguments start after the linkage area,
3801   // although the first ones are often in registers.
3802 
3803   unsigned ArgOffset = LinkageSize;
3804   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3805   SmallVector<SDValue, 8> MemOps;
3806   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3807   unsigned CurArgIdx = 0;
3808   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3809     SDValue ArgVal;
3810     bool needsLoad = false;
3811     EVT ObjectVT = Ins[ArgNo].VT;
3812     EVT OrigVT = Ins[ArgNo].ArgVT;
3813     unsigned ObjSize = ObjectVT.getStoreSize();
3814     unsigned ArgSize = ObjSize;
3815     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3816     if (Ins[ArgNo].isOrigArg()) {
3817       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3818       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3819     }
3820     // We re-align the argument offset for each argument, except when using the
3821     // fast calling convention, when we need to make sure we do that only when
3822     // we'll actually use a stack slot.
3823     unsigned CurArgOffset;
3824     Align Alignment;
3825     auto ComputeArgOffset = [&]() {
3826       /* Respect alignment of argument on the stack.  */
3827       Alignment =
3828           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3829       ArgOffset = alignTo(ArgOffset, Alignment);
3830       CurArgOffset = ArgOffset;
3831     };
3832 
3833     if (CallConv != CallingConv::Fast) {
3834       ComputeArgOffset();
3835 
3836       /* Compute GPR index associated with argument offset.  */
3837       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3838       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3839     }
3840 
3841     // FIXME the codegen can be much improved in some cases.
3842     // We do not have to keep everything in memory.
3843     if (Flags.isByVal()) {
3844       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3845 
3846       if (CallConv == CallingConv::Fast)
3847         ComputeArgOffset();
3848 
3849       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3850       ObjSize = Flags.getByValSize();
3851       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3852       // Empty aggregate parameters do not take up registers.  Examples:
3853       //   struct { } a;
3854       //   union  { } b;
3855       //   int c[0];
3856       // etc.  However, we have to provide a place-holder in InVals, so
3857       // pretend we have an 8-byte item at the current address for that
3858       // purpose.
3859       if (!ObjSize) {
3860         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3861         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3862         InVals.push_back(FIN);
3863         continue;
3864       }
3865 
3866       // Create a stack object covering all stack doublewords occupied
3867       // by the argument.  If the argument is (fully or partially) on
3868       // the stack, or if the argument is fully in registers but the
3869       // caller has allocated the parameter save anyway, we can refer
3870       // directly to the caller's stack frame.  Otherwise, create a
3871       // local copy in our own frame.
3872       int FI;
3873       if (HasParameterArea ||
3874           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3875         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3876       else
3877         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3878       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3879 
3880       // Handle aggregates smaller than 8 bytes.
3881       if (ObjSize < PtrByteSize) {
3882         // The value of the object is its address, which differs from the
3883         // address of the enclosing doubleword on big-endian systems.
3884         SDValue Arg = FIN;
3885         if (!isLittleEndian) {
3886           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3887           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3888         }
3889         InVals.push_back(Arg);
3890 
3891         if (GPR_idx != Num_GPR_Regs) {
3892           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3893           FuncInfo->addLiveInAttr(VReg, Flags);
3894           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3895           SDValue Store;
3896 
3897           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3898             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3899                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3900             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3901                                       MachinePointerInfo(&*FuncArg), ObjType);
3902           } else {
3903             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3904             // store the whole register as-is to the parameter save area
3905             // slot.
3906             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3907                                  MachinePointerInfo(&*FuncArg));
3908           }
3909 
3910           MemOps.push_back(Store);
3911         }
3912         // Whether we copied from a register or not, advance the offset
3913         // into the parameter save area by a full doubleword.
3914         ArgOffset += PtrByteSize;
3915         continue;
3916       }
3917 
3918       // The value of the object is its address, which is the address of
3919       // its first stack doubleword.
3920       InVals.push_back(FIN);
3921 
3922       // Store whatever pieces of the object are in registers to memory.
3923       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3924         if (GPR_idx == Num_GPR_Regs)
3925           break;
3926 
3927         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3928         FuncInfo->addLiveInAttr(VReg, Flags);
3929         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3930         SDValue Addr = FIN;
3931         if (j) {
3932           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3933           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3934         }
3935         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3936                                      MachinePointerInfo(&*FuncArg, j));
3937         MemOps.push_back(Store);
3938         ++GPR_idx;
3939       }
3940       ArgOffset += ArgSize;
3941       continue;
3942     }
3943 
3944     switch (ObjectVT.getSimpleVT().SimpleTy) {
3945     default: llvm_unreachable("Unhandled argument type!");
3946     case MVT::i1:
3947     case MVT::i32:
3948     case MVT::i64:
3949       if (Flags.isNest()) {
3950         // The 'nest' parameter, if any, is passed in R11.
3951         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3952         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3953 
3954         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3955           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3956 
3957         break;
3958       }
3959 
3960       // These can be scalar arguments or elements of an integer array type
3961       // passed directly.  Clang may use those instead of "byval" aggregate
3962       // types to avoid forcing arguments to memory unnecessarily.
3963       if (GPR_idx != Num_GPR_Regs) {
3964         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3965         FuncInfo->addLiveInAttr(VReg, Flags);
3966         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3967 
3968         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3969           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3970           // value to MVT::i64 and then truncate to the correct register size.
3971           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3972       } else {
3973         if (CallConv == CallingConv::Fast)
3974           ComputeArgOffset();
3975 
3976         needsLoad = true;
3977         ArgSize = PtrByteSize;
3978       }
3979       if (CallConv != CallingConv::Fast || needsLoad)
3980         ArgOffset += 8;
3981       break;
3982 
3983     case MVT::f32:
3984     case MVT::f64:
3985       // These can be scalar arguments or elements of a float array type
3986       // passed directly.  The latter are used to implement ELFv2 homogenous
3987       // float aggregates.
3988       if (FPR_idx != Num_FPR_Regs) {
3989         unsigned VReg;
3990 
3991         if (ObjectVT == MVT::f32)
3992           VReg = MF.addLiveIn(FPR[FPR_idx],
3993                               Subtarget.hasP8Vector()
3994                                   ? &PPC::VSSRCRegClass
3995                                   : &PPC::F4RCRegClass);
3996         else
3997           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3998                                                 ? &PPC::VSFRCRegClass
3999                                                 : &PPC::F8RCRegClass);
4000 
4001         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4002         ++FPR_idx;
4003       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4004         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4005         // once we support fp <-> gpr moves.
4006 
4007         // This can only ever happen in the presence of f32 array types,
4008         // since otherwise we never run out of FPRs before running out
4009         // of GPRs.
4010         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4011         FuncInfo->addLiveInAttr(VReg, Flags);
4012         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4013 
4014         if (ObjectVT == MVT::f32) {
4015           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4016             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4017                                  DAG.getConstant(32, dl, MVT::i32));
4018           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4019         }
4020 
4021         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4022       } else {
4023         if (CallConv == CallingConv::Fast)
4024           ComputeArgOffset();
4025 
4026         needsLoad = true;
4027       }
4028 
4029       // When passing an array of floats, the array occupies consecutive
4030       // space in the argument area; only round up to the next doubleword
4031       // at the end of the array.  Otherwise, each float takes 8 bytes.
4032       if (CallConv != CallingConv::Fast || needsLoad) {
4033         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4034         ArgOffset += ArgSize;
4035         if (Flags.isInConsecutiveRegsLast())
4036           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4037       }
4038       break;
4039     case MVT::v4f32:
4040     case MVT::v4i32:
4041     case MVT::v8i16:
4042     case MVT::v16i8:
4043     case MVT::v2f64:
4044     case MVT::v2i64:
4045     case MVT::v1i128:
4046     case MVT::f128:
4047       // These can be scalar arguments or elements of a vector array type
4048       // passed directly.  The latter are used to implement ELFv2 homogenous
4049       // vector aggregates.
4050       if (VR_idx != Num_VR_Regs) {
4051         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4052         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4053         ++VR_idx;
4054       } else {
4055         if (CallConv == CallingConv::Fast)
4056           ComputeArgOffset();
4057         needsLoad = true;
4058       }
4059       if (CallConv != CallingConv::Fast || needsLoad)
4060         ArgOffset += 16;
4061       break;
4062     }
4063 
4064     // We need to load the argument to a virtual register if we determined
4065     // above that we ran out of physical registers of the appropriate type.
4066     if (needsLoad) {
4067       if (ObjSize < ArgSize && !isLittleEndian)
4068         CurArgOffset += ArgSize - ObjSize;
4069       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4070       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4071       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4072     }
4073 
4074     InVals.push_back(ArgVal);
4075   }
4076 
4077   // Area that is at least reserved in the caller of this function.
4078   unsigned MinReservedArea;
4079   if (HasParameterArea)
4080     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4081   else
4082     MinReservedArea = LinkageSize;
4083 
4084   // Set the size that is at least reserved in caller of this function.  Tail
4085   // call optimized functions' reserved stack space needs to be aligned so that
4086   // taking the difference between two stack areas will result in an aligned
4087   // stack.
4088   MinReservedArea =
4089       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4090   FuncInfo->setMinReservedArea(MinReservedArea);
4091 
4092   // If the function takes variable number of arguments, make a frame index for
4093   // the start of the first vararg value... for expansion of llvm.va_start.
4094   // On ELFv2ABI spec, it writes:
4095   // C programs that are intended to be *portable* across different compilers
4096   // and architectures must use the header file <stdarg.h> to deal with variable
4097   // argument lists.
4098   if (isVarArg && MFI.hasVAStart()) {
4099     int Depth = ArgOffset;
4100 
4101     FuncInfo->setVarArgsFrameIndex(
4102       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4103     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4104 
4105     // If this function is vararg, store any remaining integer argument regs
4106     // to their spots on the stack so that they may be loaded by dereferencing
4107     // the result of va_next.
4108     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4109          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4110       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4111       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4112       SDValue Store =
4113           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4114       MemOps.push_back(Store);
4115       // Increment the address by four for the next argument to store
4116       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4117       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4118     }
4119   }
4120 
4121   if (!MemOps.empty())
4122     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4123 
4124   return Chain;
4125 }
4126 
4127 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4128     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4129     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4130     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4131   // TODO: add description of PPC stack frame format, or at least some docs.
4132   //
4133   MachineFunction &MF = DAG.getMachineFunction();
4134   MachineFrameInfo &MFI = MF.getFrameInfo();
4135   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4136 
4137   EVT PtrVT = getPointerTy(MF.getDataLayout());
4138   bool isPPC64 = PtrVT == MVT::i64;
4139   // Potential tail calls could cause overwriting of argument stack slots.
4140   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4141                        (CallConv == CallingConv::Fast));
4142   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4143   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4144   unsigned ArgOffset = LinkageSize;
4145   // Area that is at least reserved in caller of this function.
4146   unsigned MinReservedArea = ArgOffset;
4147 
4148   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4149     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4150     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4151   };
4152   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4153     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4154     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4155   };
4156   static const MCPhysReg VR[] = {
4157     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4158     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4159   };
4160 
4161   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4162   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4163   const unsigned Num_VR_Regs  = array_lengthof( VR);
4164 
4165   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4166 
4167   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4168 
4169   // In 32-bit non-varargs functions, the stack space for vectors is after the
4170   // stack space for non-vectors.  We do not use this space unless we have
4171   // too many vectors to fit in registers, something that only occurs in
4172   // constructed examples:), but we have to walk the arglist to figure
4173   // that out...for the pathological case, compute VecArgOffset as the
4174   // start of the vector parameter area.  Computing VecArgOffset is the
4175   // entire point of the following loop.
4176   unsigned VecArgOffset = ArgOffset;
4177   if (!isVarArg && !isPPC64) {
4178     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4179          ++ArgNo) {
4180       EVT ObjectVT = Ins[ArgNo].VT;
4181       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4182 
4183       if (Flags.isByVal()) {
4184         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4185         unsigned ObjSize = Flags.getByValSize();
4186         unsigned ArgSize =
4187                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4188         VecArgOffset += ArgSize;
4189         continue;
4190       }
4191 
4192       switch(ObjectVT.getSimpleVT().SimpleTy) {
4193       default: llvm_unreachable("Unhandled argument type!");
4194       case MVT::i1:
4195       case MVT::i32:
4196       case MVT::f32:
4197         VecArgOffset += 4;
4198         break;
4199       case MVT::i64:  // PPC64
4200       case MVT::f64:
4201         // FIXME: We are guaranteed to be !isPPC64 at this point.
4202         // Does MVT::i64 apply?
4203         VecArgOffset += 8;
4204         break;
4205       case MVT::v4f32:
4206       case MVT::v4i32:
4207       case MVT::v8i16:
4208       case MVT::v16i8:
4209         // Nothing to do, we're only looking at Nonvector args here.
4210         break;
4211       }
4212     }
4213   }
4214   // We've found where the vector parameter area in memory is.  Skip the
4215   // first 12 parameters; these don't use that memory.
4216   VecArgOffset = ((VecArgOffset+15)/16)*16;
4217   VecArgOffset += 12*16;
4218 
4219   // Add DAG nodes to load the arguments or copy them out of registers.  On
4220   // entry to a function on PPC, the arguments start after the linkage area,
4221   // although the first ones are often in registers.
4222 
4223   SmallVector<SDValue, 8> MemOps;
4224   unsigned nAltivecParamsAtEnd = 0;
4225   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4226   unsigned CurArgIdx = 0;
4227   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4228     SDValue ArgVal;
4229     bool needsLoad = false;
4230     EVT ObjectVT = Ins[ArgNo].VT;
4231     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4232     unsigned ArgSize = ObjSize;
4233     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4234     if (Ins[ArgNo].isOrigArg()) {
4235       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4236       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4237     }
4238     unsigned CurArgOffset = ArgOffset;
4239 
4240     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4241     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4242         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4243       if (isVarArg || isPPC64) {
4244         MinReservedArea = ((MinReservedArea+15)/16)*16;
4245         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4246                                                   Flags,
4247                                                   PtrByteSize);
4248       } else  nAltivecParamsAtEnd++;
4249     } else
4250       // Calculate min reserved area.
4251       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4252                                                 Flags,
4253                                                 PtrByteSize);
4254 
4255     // FIXME the codegen can be much improved in some cases.
4256     // We do not have to keep everything in memory.
4257     if (Flags.isByVal()) {
4258       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4259 
4260       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4261       ObjSize = Flags.getByValSize();
4262       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4263       // Objects of size 1 and 2 are right justified, everything else is
4264       // left justified.  This means the memory address is adjusted forwards.
4265       if (ObjSize==1 || ObjSize==2) {
4266         CurArgOffset = CurArgOffset + (4 - ObjSize);
4267       }
4268       // The value of the object is its address.
4269       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4270       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4271       InVals.push_back(FIN);
4272       if (ObjSize==1 || ObjSize==2) {
4273         if (GPR_idx != Num_GPR_Regs) {
4274           unsigned VReg;
4275           if (isPPC64)
4276             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4277           else
4278             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4279           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4280           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4281           SDValue Store =
4282               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4283                                 MachinePointerInfo(&*FuncArg), ObjType);
4284           MemOps.push_back(Store);
4285           ++GPR_idx;
4286         }
4287 
4288         ArgOffset += PtrByteSize;
4289 
4290         continue;
4291       }
4292       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4293         // Store whatever pieces of the object are in registers
4294         // to memory.  ArgOffset will be the address of the beginning
4295         // of the object.
4296         if (GPR_idx != Num_GPR_Regs) {
4297           unsigned VReg;
4298           if (isPPC64)
4299             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4300           else
4301             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4302           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4303           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4304           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4305           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4306                                        MachinePointerInfo(&*FuncArg, j));
4307           MemOps.push_back(Store);
4308           ++GPR_idx;
4309           ArgOffset += PtrByteSize;
4310         } else {
4311           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4312           break;
4313         }
4314       }
4315       continue;
4316     }
4317 
4318     switch (ObjectVT.getSimpleVT().SimpleTy) {
4319     default: llvm_unreachable("Unhandled argument type!");
4320     case MVT::i1:
4321     case MVT::i32:
4322       if (!isPPC64) {
4323         if (GPR_idx != Num_GPR_Regs) {
4324           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4325           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4326 
4327           if (ObjectVT == MVT::i1)
4328             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4329 
4330           ++GPR_idx;
4331         } else {
4332           needsLoad = true;
4333           ArgSize = PtrByteSize;
4334         }
4335         // All int arguments reserve stack space in the Darwin ABI.
4336         ArgOffset += PtrByteSize;
4337         break;
4338       }
4339       LLVM_FALLTHROUGH;
4340     case MVT::i64:  // PPC64
4341       if (GPR_idx != Num_GPR_Regs) {
4342         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4343         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4344 
4345         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4346           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4347           // value to MVT::i64 and then truncate to the correct register size.
4348           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4349 
4350         ++GPR_idx;
4351       } else {
4352         needsLoad = true;
4353         ArgSize = PtrByteSize;
4354       }
4355       // All int arguments reserve stack space in the Darwin ABI.
4356       ArgOffset += 8;
4357       break;
4358 
4359     case MVT::f32:
4360     case MVT::f64:
4361       // Every 4 bytes of argument space consumes one of the GPRs available for
4362       // argument passing.
4363       if (GPR_idx != Num_GPR_Regs) {
4364         ++GPR_idx;
4365         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4366           ++GPR_idx;
4367       }
4368       if (FPR_idx != Num_FPR_Regs) {
4369         unsigned VReg;
4370 
4371         if (ObjectVT == MVT::f32)
4372           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4373         else
4374           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4375 
4376         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4377         ++FPR_idx;
4378       } else {
4379         needsLoad = true;
4380       }
4381 
4382       // All FP arguments reserve stack space in the Darwin ABI.
4383       ArgOffset += isPPC64 ? 8 : ObjSize;
4384       break;
4385     case MVT::v4f32:
4386     case MVT::v4i32:
4387     case MVT::v8i16:
4388     case MVT::v16i8:
4389       // Note that vector arguments in registers don't reserve stack space,
4390       // except in varargs functions.
4391       if (VR_idx != Num_VR_Regs) {
4392         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4393         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4394         if (isVarArg) {
4395           while ((ArgOffset % 16) != 0) {
4396             ArgOffset += PtrByteSize;
4397             if (GPR_idx != Num_GPR_Regs)
4398               GPR_idx++;
4399           }
4400           ArgOffset += 16;
4401           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4402         }
4403         ++VR_idx;
4404       } else {
4405         if (!isVarArg && !isPPC64) {
4406           // Vectors go after all the nonvectors.
4407           CurArgOffset = VecArgOffset;
4408           VecArgOffset += 16;
4409         } else {
4410           // Vectors are aligned.
4411           ArgOffset = ((ArgOffset+15)/16)*16;
4412           CurArgOffset = ArgOffset;
4413           ArgOffset += 16;
4414         }
4415         needsLoad = true;
4416       }
4417       break;
4418     }
4419 
4420     // We need to load the argument to a virtual register if we determined above
4421     // that we ran out of physical registers of the appropriate type.
4422     if (needsLoad) {
4423       int FI = MFI.CreateFixedObject(ObjSize,
4424                                      CurArgOffset + (ArgSize - ObjSize),
4425                                      isImmutable);
4426       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4427       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4428     }
4429 
4430     InVals.push_back(ArgVal);
4431   }
4432 
4433   // Allow for Altivec parameters at the end, if needed.
4434   if (nAltivecParamsAtEnd) {
4435     MinReservedArea = ((MinReservedArea+15)/16)*16;
4436     MinReservedArea += 16*nAltivecParamsAtEnd;
4437   }
4438 
4439   // Area that is at least reserved in the caller of this function.
4440   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4441 
4442   // Set the size that is at least reserved in caller of this function.  Tail
4443   // call optimized functions' reserved stack space needs to be aligned so that
4444   // taking the difference between two stack areas will result in an aligned
4445   // stack.
4446   MinReservedArea =
4447       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4448   FuncInfo->setMinReservedArea(MinReservedArea);
4449 
4450   // If the function takes variable number of arguments, make a frame index for
4451   // the start of the first vararg value... for expansion of llvm.va_start.
4452   if (isVarArg) {
4453     int Depth = ArgOffset;
4454 
4455     FuncInfo->setVarArgsFrameIndex(
4456       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4457                             Depth, true));
4458     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4459 
4460     // If this function is vararg, store any remaining integer argument regs
4461     // to their spots on the stack so that they may be loaded by dereferencing
4462     // the result of va_next.
4463     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4464       unsigned VReg;
4465 
4466       if (isPPC64)
4467         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4468       else
4469         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4470 
4471       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4472       SDValue Store =
4473           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4474       MemOps.push_back(Store);
4475       // Increment the address by four for the next argument to store
4476       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4477       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4478     }
4479   }
4480 
4481   if (!MemOps.empty())
4482     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4483 
4484   return Chain;
4485 }
4486 
4487 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4488 /// adjusted to accommodate the arguments for the tailcall.
4489 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4490                                    unsigned ParamSize) {
4491 
4492   if (!isTailCall) return 0;
4493 
4494   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4495   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4496   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4497   // Remember only if the new adjustment is bigger.
4498   if (SPDiff < FI->getTailCallSPDelta())
4499     FI->setTailCallSPDelta(SPDiff);
4500 
4501   return SPDiff;
4502 }
4503 
4504 static bool isFunctionGlobalAddress(SDValue Callee);
4505 
4506 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4507                               const TargetMachine &TM) {
4508   // It does not make sense to call callsShareTOCBase() with a caller that
4509   // is PC Relative since PC Relative callers do not have a TOC.
4510 #ifndef NDEBUG
4511   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4512   assert(!STICaller->isUsingPCRelativeCalls() &&
4513          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4514 #endif
4515 
4516   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4517   // don't have enough information to determine if the caller and callee share
4518   // the same  TOC base, so we have to pessimistically assume they don't for
4519   // correctness.
4520   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4521   if (!G)
4522     return false;
4523 
4524   const GlobalValue *GV = G->getGlobal();
4525 
4526   // If the callee is preemptable, then the static linker will use a plt-stub
4527   // which saves the toc to the stack, and needs a nop after the call
4528   // instruction to convert to a toc-restore.
4529   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4530     return false;
4531 
4532   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4533   // We may need a TOC restore in the situation where the caller requires a
4534   // valid TOC but the callee is PC Relative and does not.
4535   const Function *F = dyn_cast<Function>(GV);
4536   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4537 
4538   // If we have an Alias we can try to get the function from there.
4539   if (Alias) {
4540     const GlobalObject *GlobalObj = Alias->getBaseObject();
4541     F = dyn_cast<Function>(GlobalObj);
4542   }
4543 
4544   // If we still have no valid function pointer we do not have enough
4545   // information to determine if the callee uses PC Relative calls so we must
4546   // assume that it does.
4547   if (!F)
4548     return false;
4549 
4550   // If the callee uses PC Relative we cannot guarantee that the callee won't
4551   // clobber the TOC of the caller and so we must assume that the two
4552   // functions do not share a TOC base.
4553   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4554   if (STICallee->isUsingPCRelativeCalls())
4555     return false;
4556 
4557   // The medium and large code models are expected to provide a sufficiently
4558   // large TOC to provide all data addressing needs of a module with a
4559   // single TOC.
4560   if (CodeModel::Medium == TM.getCodeModel() ||
4561       CodeModel::Large == TM.getCodeModel())
4562     return true;
4563 
4564   // Otherwise we need to ensure callee and caller are in the same section,
4565   // since the linker may allocate multiple TOCs, and we don't know which
4566   // sections will belong to the same TOC base.
4567   if (!GV->isStrongDefinitionForLinker())
4568     return false;
4569 
4570   // Any explicitly-specified sections and section prefixes must also match.
4571   // Also, if we're using -ffunction-sections, then each function is always in
4572   // a different section (the same is true for COMDAT functions).
4573   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4574       GV->getSection() != Caller->getSection())
4575     return false;
4576   if (const auto *F = dyn_cast<Function>(GV)) {
4577     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4578       return false;
4579   }
4580 
4581   return true;
4582 }
4583 
4584 static bool
4585 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4586                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4587   assert(Subtarget.is64BitELFABI());
4588 
4589   const unsigned PtrByteSize = 8;
4590   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4591 
4592   static const MCPhysReg GPR[] = {
4593     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4594     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4595   };
4596   static const MCPhysReg VR[] = {
4597     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4598     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4599   };
4600 
4601   const unsigned NumGPRs = array_lengthof(GPR);
4602   const unsigned NumFPRs = 13;
4603   const unsigned NumVRs = array_lengthof(VR);
4604   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4605 
4606   unsigned NumBytes = LinkageSize;
4607   unsigned AvailableFPRs = NumFPRs;
4608   unsigned AvailableVRs = NumVRs;
4609 
4610   for (const ISD::OutputArg& Param : Outs) {
4611     if (Param.Flags.isNest()) continue;
4612 
4613     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4614                                LinkageSize, ParamAreaSize, NumBytes,
4615                                AvailableFPRs, AvailableVRs))
4616       return true;
4617   }
4618   return false;
4619 }
4620 
4621 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4622   if (CB.arg_size() != CallerFn->arg_size())
4623     return false;
4624 
4625   auto CalleeArgIter = CB.arg_begin();
4626   auto CalleeArgEnd = CB.arg_end();
4627   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4628 
4629   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4630     const Value* CalleeArg = *CalleeArgIter;
4631     const Value* CallerArg = &(*CallerArgIter);
4632     if (CalleeArg == CallerArg)
4633       continue;
4634 
4635     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4636     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4637     //      }
4638     // 1st argument of callee is undef and has the same type as caller.
4639     if (CalleeArg->getType() == CallerArg->getType() &&
4640         isa<UndefValue>(CalleeArg))
4641       continue;
4642 
4643     return false;
4644   }
4645 
4646   return true;
4647 }
4648 
4649 // Returns true if TCO is possible between the callers and callees
4650 // calling conventions.
4651 static bool
4652 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4653                                     CallingConv::ID CalleeCC) {
4654   // Tail calls are possible with fastcc and ccc.
4655   auto isTailCallableCC  = [] (CallingConv::ID CC){
4656       return  CC == CallingConv::C || CC == CallingConv::Fast;
4657   };
4658   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4659     return false;
4660 
4661   // We can safely tail call both fastcc and ccc callees from a c calling
4662   // convention caller. If the caller is fastcc, we may have less stack space
4663   // than a non-fastcc caller with the same signature so disable tail-calls in
4664   // that case.
4665   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4666 }
4667 
4668 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4669     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4670     const SmallVectorImpl<ISD::OutputArg> &Outs,
4671     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4672   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4673 
4674   if (DisableSCO && !TailCallOpt) return false;
4675 
4676   // Variadic argument functions are not supported.
4677   if (isVarArg) return false;
4678 
4679   auto &Caller = DAG.getMachineFunction().getFunction();
4680   // Check that the calling conventions are compatible for tco.
4681   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4682     return false;
4683 
4684   // Caller contains any byval parameter is not supported.
4685   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4686     return false;
4687 
4688   // Callee contains any byval parameter is not supported, too.
4689   // Note: This is a quick work around, because in some cases, e.g.
4690   // caller's stack size > callee's stack size, we are still able to apply
4691   // sibling call optimization. For example, gcc is able to do SCO for caller1
4692   // in the following example, but not for caller2.
4693   //   struct test {
4694   //     long int a;
4695   //     char ary[56];
4696   //   } gTest;
4697   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4698   //     b->a = v.a;
4699   //     return 0;
4700   //   }
4701   //   void caller1(struct test a, struct test c, struct test *b) {
4702   //     callee(gTest, b); }
4703   //   void caller2(struct test *b) { callee(gTest, b); }
4704   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4705     return false;
4706 
4707   // If callee and caller use different calling conventions, we cannot pass
4708   // parameters on stack since offsets for the parameter area may be different.
4709   if (Caller.getCallingConv() != CalleeCC &&
4710       needStackSlotPassParameters(Subtarget, Outs))
4711     return false;
4712 
4713   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4714   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4715   // callee potentially have different TOC bases then we cannot tail call since
4716   // we need to restore the TOC pointer after the call.
4717   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4718   // We cannot guarantee this for indirect calls or calls to external functions.
4719   // When PC-Relative addressing is used, the concept of the TOC is no longer
4720   // applicable so this check is not required.
4721   // Check first for indirect calls.
4722   if (!Subtarget.isUsingPCRelativeCalls() &&
4723       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4724     return false;
4725 
4726   // Check if we share the TOC base.
4727   if (!Subtarget.isUsingPCRelativeCalls() &&
4728       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4729     return false;
4730 
4731   // TCO allows altering callee ABI, so we don't have to check further.
4732   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4733     return true;
4734 
4735   if (DisableSCO) return false;
4736 
4737   // If callee use the same argument list that caller is using, then we can
4738   // apply SCO on this case. If it is not, then we need to check if callee needs
4739   // stack for passing arguments.
4740   // PC Relative tail calls may not have a CallBase.
4741   // If there is no CallBase we cannot verify if we have the same argument
4742   // list so assume that we don't have the same argument list.
4743   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4744       needStackSlotPassParameters(Subtarget, Outs))
4745     return false;
4746   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4747     return false;
4748 
4749   return true;
4750 }
4751 
4752 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4753 /// for tail call optimization. Targets which want to do tail call
4754 /// optimization should implement this function.
4755 bool
4756 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4757                                                      CallingConv::ID CalleeCC,
4758                                                      bool isVarArg,
4759                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4760                                                      SelectionDAG& DAG) const {
4761   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4762     return false;
4763 
4764   // Variable argument functions are not supported.
4765   if (isVarArg)
4766     return false;
4767 
4768   MachineFunction &MF = DAG.getMachineFunction();
4769   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4770   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4771     // Functions containing by val parameters are not supported.
4772     for (unsigned i = 0; i != Ins.size(); i++) {
4773        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4774        if (Flags.isByVal()) return false;
4775     }
4776 
4777     // Non-PIC/GOT tail calls are supported.
4778     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4779       return true;
4780 
4781     // At the moment we can only do local tail calls (in same module, hidden
4782     // or protected) if we are generating PIC.
4783     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4784       return G->getGlobal()->hasHiddenVisibility()
4785           || G->getGlobal()->hasProtectedVisibility();
4786   }
4787 
4788   return false;
4789 }
4790 
4791 /// isCallCompatibleAddress - Return the immediate to use if the specified
4792 /// 32-bit value is representable in the immediate field of a BxA instruction.
4793 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4794   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4795   if (!C) return nullptr;
4796 
4797   int Addr = C->getZExtValue();
4798   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4799       SignExtend32<26>(Addr) != Addr)
4800     return nullptr;  // Top 6 bits have to be sext of immediate.
4801 
4802   return DAG
4803       .getConstant(
4804           (int)C->getZExtValue() >> 2, SDLoc(Op),
4805           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4806       .getNode();
4807 }
4808 
4809 namespace {
4810 
4811 struct TailCallArgumentInfo {
4812   SDValue Arg;
4813   SDValue FrameIdxOp;
4814   int FrameIdx = 0;
4815 
4816   TailCallArgumentInfo() = default;
4817 };
4818 
4819 } // end anonymous namespace
4820 
4821 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4822 static void StoreTailCallArgumentsToStackSlot(
4823     SelectionDAG &DAG, SDValue Chain,
4824     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4825     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4826   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4827     SDValue Arg = TailCallArgs[i].Arg;
4828     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4829     int FI = TailCallArgs[i].FrameIdx;
4830     // Store relative to framepointer.
4831     MemOpChains.push_back(DAG.getStore(
4832         Chain, dl, Arg, FIN,
4833         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4834   }
4835 }
4836 
4837 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4838 /// the appropriate stack slot for the tail call optimized function call.
4839 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4840                                              SDValue OldRetAddr, SDValue OldFP,
4841                                              int SPDiff, const SDLoc &dl) {
4842   if (SPDiff) {
4843     // Calculate the new stack slot for the return address.
4844     MachineFunction &MF = DAG.getMachineFunction();
4845     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4846     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4847     bool isPPC64 = Subtarget.isPPC64();
4848     int SlotSize = isPPC64 ? 8 : 4;
4849     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4850     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4851                                                          NewRetAddrLoc, true);
4852     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4853     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4854     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4855                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4856   }
4857   return Chain;
4858 }
4859 
4860 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4861 /// the position of the argument.
4862 static void
4863 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4864                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4865                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4866   int Offset = ArgOffset + SPDiff;
4867   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4868   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4869   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4870   SDValue FIN = DAG.getFrameIndex(FI, VT);
4871   TailCallArgumentInfo Info;
4872   Info.Arg = Arg;
4873   Info.FrameIdxOp = FIN;
4874   Info.FrameIdx = FI;
4875   TailCallArguments.push_back(Info);
4876 }
4877 
4878 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4879 /// stack slot. Returns the chain as result and the loaded frame pointers in
4880 /// LROpOut/FPOpout. Used when tail calling.
4881 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4882     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4883     SDValue &FPOpOut, const SDLoc &dl) const {
4884   if (SPDiff) {
4885     // Load the LR and FP stack slot for later adjusting.
4886     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4887     LROpOut = getReturnAddrFrameIndex(DAG);
4888     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4889     Chain = SDValue(LROpOut.getNode(), 1);
4890   }
4891   return Chain;
4892 }
4893 
4894 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4895 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4896 /// specified by the specific parameter attribute. The copy will be passed as
4897 /// a byval function parameter.
4898 /// Sometimes what we are copying is the end of a larger object, the part that
4899 /// does not fit in registers.
4900 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4901                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4902                                          SelectionDAG &DAG, const SDLoc &dl) {
4903   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4904   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4905                        Flags.getNonZeroByValAlign(), false, false, false,
4906                        MachinePointerInfo(), MachinePointerInfo());
4907 }
4908 
4909 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4910 /// tail calls.
4911 static void LowerMemOpCallTo(
4912     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4913     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4914     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4915     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4916   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4917   if (!isTailCall) {
4918     if (isVector) {
4919       SDValue StackPtr;
4920       if (isPPC64)
4921         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4922       else
4923         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4924       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4925                            DAG.getConstant(ArgOffset, dl, PtrVT));
4926     }
4927     MemOpChains.push_back(
4928         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4929     // Calculate and remember argument location.
4930   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4931                                   TailCallArguments);
4932 }
4933 
4934 static void
4935 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4936                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4937                 SDValue FPOp,
4938                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4939   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4940   // might overwrite each other in case of tail call optimization.
4941   SmallVector<SDValue, 8> MemOpChains2;
4942   // Do not flag preceding copytoreg stuff together with the following stuff.
4943   InFlag = SDValue();
4944   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4945                                     MemOpChains2, dl);
4946   if (!MemOpChains2.empty())
4947     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4948 
4949   // Store the return address to the appropriate stack slot.
4950   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4951 
4952   // Emit callseq_end just before tailcall node.
4953   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4954                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4955   InFlag = Chain.getValue(1);
4956 }
4957 
4958 // Is this global address that of a function that can be called by name? (as
4959 // opposed to something that must hold a descriptor for an indirect call).
4960 static bool isFunctionGlobalAddress(SDValue Callee) {
4961   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4962     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4963         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4964       return false;
4965 
4966     return G->getGlobal()->getValueType()->isFunctionTy();
4967   }
4968 
4969   return false;
4970 }
4971 
4972 SDValue PPCTargetLowering::LowerCallResult(
4973     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4974     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4975     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4976   SmallVector<CCValAssign, 16> RVLocs;
4977   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4978                     *DAG.getContext());
4979 
4980   CCRetInfo.AnalyzeCallResult(
4981       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4982                ? RetCC_PPC_Cold
4983                : RetCC_PPC);
4984 
4985   // Copy all of the result registers out of their specified physreg.
4986   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4987     CCValAssign &VA = RVLocs[i];
4988     assert(VA.isRegLoc() && "Can only return in registers!");
4989 
4990     SDValue Val;
4991 
4992     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
4993       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4994                                       InFlag);
4995       Chain = Lo.getValue(1);
4996       InFlag = Lo.getValue(2);
4997       VA = RVLocs[++i]; // skip ahead to next loc
4998       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4999                                       InFlag);
5000       Chain = Hi.getValue(1);
5001       InFlag = Hi.getValue(2);
5002       if (!Subtarget.isLittleEndian())
5003         std::swap (Lo, Hi);
5004       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5005     } else {
5006       Val = DAG.getCopyFromReg(Chain, dl,
5007                                VA.getLocReg(), VA.getLocVT(), InFlag);
5008       Chain = Val.getValue(1);
5009       InFlag = Val.getValue(2);
5010     }
5011 
5012     switch (VA.getLocInfo()) {
5013     default: llvm_unreachable("Unknown loc info!");
5014     case CCValAssign::Full: break;
5015     case CCValAssign::AExt:
5016       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5017       break;
5018     case CCValAssign::ZExt:
5019       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5020                         DAG.getValueType(VA.getValVT()));
5021       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5022       break;
5023     case CCValAssign::SExt:
5024       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5025                         DAG.getValueType(VA.getValVT()));
5026       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5027       break;
5028     }
5029 
5030     InVals.push_back(Val);
5031   }
5032 
5033   return Chain;
5034 }
5035 
5036 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5037                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5038   // PatchPoint calls are not indirect.
5039   if (isPatchPoint)
5040     return false;
5041 
5042   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5043     return false;
5044 
5045   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5046   // becuase the immediate function pointer points to a descriptor instead of
5047   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5048   // pointer immediate points to the global entry point, while the BLA would
5049   // need to jump to the local entry point (see rL211174).
5050   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5051       isBLACompatibleAddress(Callee, DAG))
5052     return false;
5053 
5054   return true;
5055 }
5056 
5057 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5058 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5059   return Subtarget.isAIXABI() ||
5060          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5061 }
5062 
5063 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5064                               const Function &Caller,
5065                               const SDValue &Callee,
5066                               const PPCSubtarget &Subtarget,
5067                               const TargetMachine &TM) {
5068   if (CFlags.IsTailCall)
5069     return PPCISD::TC_RETURN;
5070 
5071   // This is a call through a function pointer.
5072   if (CFlags.IsIndirect) {
5073     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5074     // indirect calls. The save of the caller's TOC pointer to the stack will be
5075     // inserted into the DAG as part of call lowering. The restore of the TOC
5076     // pointer is modeled by using a pseudo instruction for the call opcode that
5077     // represents the 2 instruction sequence of an indirect branch and link,
5078     // immediately followed by a load of the TOC pointer from the the stack save
5079     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5080     // as it is not saved or used.
5081     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5082                                                : PPCISD::BCTRL;
5083   }
5084 
5085   if (Subtarget.isUsingPCRelativeCalls()) {
5086     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5087     return PPCISD::CALL_NOTOC;
5088   }
5089 
5090   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5091   // immediately following the call instruction if the caller and callee may
5092   // have different TOC bases. At link time if the linker determines the calls
5093   // may not share a TOC base, the call is redirected to a trampoline inserted
5094   // by the linker. The trampoline will (among other things) save the callers
5095   // TOC pointer at an ABI designated offset in the linkage area and the linker
5096   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5097   // into gpr2.
5098   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5099     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5100                                                   : PPCISD::CALL_NOP;
5101 
5102   return PPCISD::CALL;
5103 }
5104 
5105 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5106                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5107   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5108     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5109       return SDValue(Dest, 0);
5110 
5111   // Returns true if the callee is local, and false otherwise.
5112   auto isLocalCallee = [&]() {
5113     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5114     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5115     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5116 
5117     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5118            !dyn_cast_or_null<GlobalIFunc>(GV);
5119   };
5120 
5121   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5122   // a static relocation model causes some versions of GNU LD (2.17.50, at
5123   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5124   // built with secure-PLT.
5125   bool UsePlt =
5126       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5127       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5128 
5129   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5130     const TargetMachine &TM = Subtarget.getTargetMachine();
5131     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5132     MCSymbolXCOFF *S =
5133         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5134 
5135     if (GV->isDeclaration() && !S->hasRepresentedCsectSet()) {
5136       // On AIX, an undefined symbol needs to be associated with a
5137       // MCSectionXCOFF to get the correct storage mapping class.
5138       // In this case, XCOFF::XMC_PR.
5139       const XCOFF::StorageClass SC =
5140           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV);
5141       auto &Context = DAG.getMachineFunction().getMMI().getContext();
5142       MCSectionXCOFF *Sec = Context.getXCOFFSection(
5143           S->getSymbolTableName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5144           SectionKind::getMetadata());
5145       S->setRepresentedCsect(Sec);
5146     }
5147 
5148     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5149     return DAG.getMCSymbol(S, PtrVT);
5150   };
5151 
5152   if (isFunctionGlobalAddress(Callee)) {
5153     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5154 
5155     if (Subtarget.isAIXABI()) {
5156       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5157       return getAIXFuncEntryPointSymbolSDNode(GV);
5158     }
5159     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5160                                       UsePlt ? PPCII::MO_PLT : 0);
5161   }
5162 
5163   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5164     const char *SymName = S->getSymbol();
5165     if (Subtarget.isAIXABI()) {
5166       // If there exists a user-declared function whose name is the same as the
5167       // ExternalSymbol's, then we pick up the user-declared version.
5168       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5169       if (const Function *F =
5170               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5171         return getAIXFuncEntryPointSymbolSDNode(F);
5172 
5173       // On AIX, direct function calls reference the symbol for the function's
5174       // entry point, which is named by prepending a "." before the function's
5175       // C-linkage name.
5176       const auto getFunctionEntryPointSymbol = [&](StringRef SymName) {
5177         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5178         return cast<MCSymbolXCOFF>(
5179             Context.getOrCreateSymbol(Twine(".") + Twine(SymName)));
5180       };
5181 
5182       SymName = getFunctionEntryPointSymbol(SymName)->getName().data();
5183     }
5184     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5185                                        UsePlt ? PPCII::MO_PLT : 0);
5186   }
5187 
5188   // No transformation needed.
5189   assert(Callee.getNode() && "What no callee?");
5190   return Callee;
5191 }
5192 
5193 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5194   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5195          "Expected a CALLSEQ_STARTSDNode.");
5196 
5197   // The last operand is the chain, except when the node has glue. If the node
5198   // has glue, then the last operand is the glue, and the chain is the second
5199   // last operand.
5200   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5201   if (LastValue.getValueType() != MVT::Glue)
5202     return LastValue;
5203 
5204   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5205 }
5206 
5207 // Creates the node that moves a functions address into the count register
5208 // to prepare for an indirect call instruction.
5209 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5210                                 SDValue &Glue, SDValue &Chain,
5211                                 const SDLoc &dl) {
5212   SDValue MTCTROps[] = {Chain, Callee, Glue};
5213   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5214   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5215                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5216   // The glue is the second value produced.
5217   Glue = Chain.getValue(1);
5218 }
5219 
5220 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5221                                           SDValue &Glue, SDValue &Chain,
5222                                           SDValue CallSeqStart,
5223                                           const CallBase *CB, const SDLoc &dl,
5224                                           bool hasNest,
5225                                           const PPCSubtarget &Subtarget) {
5226   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5227   // entry point, but to the function descriptor (the function entry point
5228   // address is part of the function descriptor though).
5229   // The function descriptor is a three doubleword structure with the
5230   // following fields: function entry point, TOC base address and
5231   // environment pointer.
5232   // Thus for a call through a function pointer, the following actions need
5233   // to be performed:
5234   //   1. Save the TOC of the caller in the TOC save area of its stack
5235   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5236   //   2. Load the address of the function entry point from the function
5237   //      descriptor.
5238   //   3. Load the TOC of the callee from the function descriptor into r2.
5239   //   4. Load the environment pointer from the function descriptor into
5240   //      r11.
5241   //   5. Branch to the function entry point address.
5242   //   6. On return of the callee, the TOC of the caller needs to be
5243   //      restored (this is done in FinishCall()).
5244   //
5245   // The loads are scheduled at the beginning of the call sequence, and the
5246   // register copies are flagged together to ensure that no other
5247   // operations can be scheduled in between. E.g. without flagging the
5248   // copies together, a TOC access in the caller could be scheduled between
5249   // the assignment of the callee TOC and the branch to the callee, which leads
5250   // to incorrect code.
5251 
5252   // Start by loading the function address from the descriptor.
5253   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5254   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5255                       ? (MachineMemOperand::MODereferenceable |
5256                          MachineMemOperand::MOInvariant)
5257                       : MachineMemOperand::MONone;
5258 
5259   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5260 
5261   // Registers used in building the DAG.
5262   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5263   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5264 
5265   // Offsets of descriptor members.
5266   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5267   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5268 
5269   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5270   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5271 
5272   // One load for the functions entry point address.
5273   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5274                                     Alignment, MMOFlags);
5275 
5276   // One for loading the TOC anchor for the module that contains the called
5277   // function.
5278   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5279   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5280   SDValue TOCPtr =
5281       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5282                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5283 
5284   // One for loading the environment pointer.
5285   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5286   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5287   SDValue LoadEnvPtr =
5288       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5289                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5290 
5291 
5292   // Then copy the newly loaded TOC anchor to the TOC pointer.
5293   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5294   Chain = TOCVal.getValue(0);
5295   Glue = TOCVal.getValue(1);
5296 
5297   // If the function call has an explicit 'nest' parameter, it takes the
5298   // place of the environment pointer.
5299   assert((!hasNest || !Subtarget.isAIXABI()) &&
5300          "Nest parameter is not supported on AIX.");
5301   if (!hasNest) {
5302     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5303     Chain = EnvVal.getValue(0);
5304     Glue = EnvVal.getValue(1);
5305   }
5306 
5307   // The rest of the indirect call sequence is the same as the non-descriptor
5308   // DAG.
5309   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5310 }
5311 
5312 static void
5313 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5314                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5315                   SelectionDAG &DAG,
5316                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5317                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5318                   const PPCSubtarget &Subtarget) {
5319   const bool IsPPC64 = Subtarget.isPPC64();
5320   // MVT for a general purpose register.
5321   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5322 
5323   // First operand is always the chain.
5324   Ops.push_back(Chain);
5325 
5326   // If it's a direct call pass the callee as the second operand.
5327   if (!CFlags.IsIndirect)
5328     Ops.push_back(Callee);
5329   else {
5330     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5331 
5332     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5333     // on the stack (this would have been done in `LowerCall_64SVR4` or
5334     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5335     // represents both the indirect branch and a load that restores the TOC
5336     // pointer from the linkage area. The operand for the TOC restore is an add
5337     // of the TOC save offset to the stack pointer. This must be the second
5338     // operand: after the chain input but before any other variadic arguments.
5339     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5340     // saved or used.
5341     if (isTOCSaveRestoreRequired(Subtarget)) {
5342       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5343 
5344       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5345       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5346       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5347       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5348       Ops.push_back(AddTOC);
5349     }
5350 
5351     // Add the register used for the environment pointer.
5352     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5353       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5354                                     RegVT));
5355 
5356 
5357     // Add CTR register as callee so a bctr can be emitted later.
5358     if (CFlags.IsTailCall)
5359       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5360   }
5361 
5362   // If this is a tail call add stack pointer delta.
5363   if (CFlags.IsTailCall)
5364     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5365 
5366   // Add argument registers to the end of the list so that they are known live
5367   // into the call.
5368   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5369     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5370                                   RegsToPass[i].second.getValueType()));
5371 
5372   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5373   // no way to mark dependencies as implicit here.
5374   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5375   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5376        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5377     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5378 
5379   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5380   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5381     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5382 
5383   // Add a register mask operand representing the call-preserved registers.
5384   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5385   const uint32_t *Mask =
5386       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5387   assert(Mask && "Missing call preserved mask for calling convention");
5388   Ops.push_back(DAG.getRegisterMask(Mask));
5389 
5390   // If the glue is valid, it is the last operand.
5391   if (Glue.getNode())
5392     Ops.push_back(Glue);
5393 }
5394 
5395 SDValue PPCTargetLowering::FinishCall(
5396     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5397     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5398     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5399     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5400     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5401 
5402   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5403       Subtarget.isAIXABI())
5404     setUsesTOCBasePtr(DAG);
5405 
5406   unsigned CallOpc =
5407       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5408                     Subtarget, DAG.getTarget());
5409 
5410   if (!CFlags.IsIndirect)
5411     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5412   else if (Subtarget.usesFunctionDescriptors())
5413     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5414                                   dl, CFlags.HasNest, Subtarget);
5415   else
5416     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5417 
5418   // Build the operand list for the call instruction.
5419   SmallVector<SDValue, 8> Ops;
5420   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5421                     SPDiff, Subtarget);
5422 
5423   // Emit tail call.
5424   if (CFlags.IsTailCall) {
5425     // Indirect tail call when using PC Relative calls do not have the same
5426     // constraints.
5427     assert(((Callee.getOpcode() == ISD::Register &&
5428              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5429             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5430             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5431             isa<ConstantSDNode>(Callee) ||
5432             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5433            "Expecting a global address, external symbol, absolute value, "
5434            "register or an indirect tail call when PC Relative calls are "
5435            "used.");
5436     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5437     assert(CallOpc == PPCISD::TC_RETURN &&
5438            "Unexpected call opcode for a tail call.");
5439     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5440     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5441   }
5442 
5443   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5444   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5445   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5446   Glue = Chain.getValue(1);
5447 
5448   // When performing tail call optimization the callee pops its arguments off
5449   // the stack. Account for this here so these bytes can be pushed back on in
5450   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5451   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5452                          getTargetMachine().Options.GuaranteedTailCallOpt)
5453                             ? NumBytes
5454                             : 0;
5455 
5456   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5457                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5458                              Glue, dl);
5459   Glue = Chain.getValue(1);
5460 
5461   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5462                          DAG, InVals);
5463 }
5464 
5465 SDValue
5466 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5467                              SmallVectorImpl<SDValue> &InVals) const {
5468   SelectionDAG &DAG                     = CLI.DAG;
5469   SDLoc &dl                             = CLI.DL;
5470   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5471   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5472   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5473   SDValue Chain                         = CLI.Chain;
5474   SDValue Callee                        = CLI.Callee;
5475   bool &isTailCall                      = CLI.IsTailCall;
5476   CallingConv::ID CallConv              = CLI.CallConv;
5477   bool isVarArg                         = CLI.IsVarArg;
5478   bool isPatchPoint                     = CLI.IsPatchPoint;
5479   const CallBase *CB                    = CLI.CB;
5480 
5481   if (isTailCall) {
5482     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5483       isTailCall = false;
5484     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5485       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5486           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5487     else
5488       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5489                                                      Ins, DAG);
5490     if (isTailCall) {
5491       ++NumTailCalls;
5492       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5493         ++NumSiblingCalls;
5494 
5495       // PC Relative calls no longer guarantee that the callee is a Global
5496       // Address Node. The callee could be an indirect tail call in which
5497       // case the SDValue for the callee could be a load (to load the address
5498       // of a function pointer) or it may be a register copy (to move the
5499       // address of the callee from a function parameter into a virtual
5500       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5501       assert((Subtarget.isUsingPCRelativeCalls() ||
5502               isa<GlobalAddressSDNode>(Callee)) &&
5503              "Callee should be an llvm::Function object.");
5504 
5505       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5506                         << "\nTCO callee: ");
5507       LLVM_DEBUG(Callee.dump());
5508     }
5509   }
5510 
5511   if (!isTailCall && CB && CB->isMustTailCall())
5512     report_fatal_error("failed to perform tail call elimination on a call "
5513                        "site marked musttail");
5514 
5515   // When long calls (i.e. indirect calls) are always used, calls are always
5516   // made via function pointer. If we have a function name, first translate it
5517   // into a pointer.
5518   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5519       !isTailCall)
5520     Callee = LowerGlobalAddress(Callee, DAG);
5521 
5522   CallFlags CFlags(
5523       CallConv, isTailCall, isVarArg, isPatchPoint,
5524       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5525       // hasNest
5526       Subtarget.is64BitELFABI() &&
5527           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5528       CLI.NoMerge);
5529 
5530   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5531     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5532                             InVals, CB);
5533 
5534   if (Subtarget.isSVR4ABI())
5535     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5536                             InVals, CB);
5537 
5538   if (Subtarget.isAIXABI())
5539     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5540                          InVals, CB);
5541 
5542   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5543                           InVals, CB);
5544 }
5545 
5546 SDValue PPCTargetLowering::LowerCall_32SVR4(
5547     SDValue Chain, SDValue Callee, CallFlags CFlags,
5548     const SmallVectorImpl<ISD::OutputArg> &Outs,
5549     const SmallVectorImpl<SDValue> &OutVals,
5550     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5551     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5552     const CallBase *CB) const {
5553   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5554   // of the 32-bit SVR4 ABI stack frame layout.
5555 
5556   const CallingConv::ID CallConv = CFlags.CallConv;
5557   const bool IsVarArg = CFlags.IsVarArg;
5558   const bool IsTailCall = CFlags.IsTailCall;
5559 
5560   assert((CallConv == CallingConv::C ||
5561           CallConv == CallingConv::Cold ||
5562           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5563 
5564   const Align PtrAlign(4);
5565 
5566   MachineFunction &MF = DAG.getMachineFunction();
5567 
5568   // Mark this function as potentially containing a function that contains a
5569   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5570   // and restoring the callers stack pointer in this functions epilog. This is
5571   // done because by tail calling the called function might overwrite the value
5572   // in this function's (MF) stack pointer stack slot 0(SP).
5573   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5574       CallConv == CallingConv::Fast)
5575     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5576 
5577   // Count how many bytes are to be pushed on the stack, including the linkage
5578   // area, parameter list area and the part of the local variable space which
5579   // contains copies of aggregates which are passed by value.
5580 
5581   // Assign locations to all of the outgoing arguments.
5582   SmallVector<CCValAssign, 16> ArgLocs;
5583   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5584 
5585   // Reserve space for the linkage area on the stack.
5586   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5587                        PtrAlign);
5588   if (useSoftFloat())
5589     CCInfo.PreAnalyzeCallOperands(Outs);
5590 
5591   if (IsVarArg) {
5592     // Handle fixed and variable vector arguments differently.
5593     // Fixed vector arguments go into registers as long as registers are
5594     // available. Variable vector arguments always go into memory.
5595     unsigned NumArgs = Outs.size();
5596 
5597     for (unsigned i = 0; i != NumArgs; ++i) {
5598       MVT ArgVT = Outs[i].VT;
5599       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5600       bool Result;
5601 
5602       if (Outs[i].IsFixed) {
5603         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5604                                CCInfo);
5605       } else {
5606         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5607                                       ArgFlags, CCInfo);
5608       }
5609 
5610       if (Result) {
5611 #ifndef NDEBUG
5612         errs() << "Call operand #" << i << " has unhandled type "
5613              << EVT(ArgVT).getEVTString() << "\n";
5614 #endif
5615         llvm_unreachable(nullptr);
5616       }
5617     }
5618   } else {
5619     // All arguments are treated the same.
5620     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5621   }
5622   CCInfo.clearWasPPCF128();
5623 
5624   // Assign locations to all of the outgoing aggregate by value arguments.
5625   SmallVector<CCValAssign, 16> ByValArgLocs;
5626   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5627 
5628   // Reserve stack space for the allocations in CCInfo.
5629   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5630 
5631   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5632 
5633   // Size of the linkage area, parameter list area and the part of the local
5634   // space variable where copies of aggregates which are passed by value are
5635   // stored.
5636   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5637 
5638   // Calculate by how many bytes the stack has to be adjusted in case of tail
5639   // call optimization.
5640   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5641 
5642   // Adjust the stack pointer for the new arguments...
5643   // These operations are automatically eliminated by the prolog/epilog pass
5644   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5645   SDValue CallSeqStart = Chain;
5646 
5647   // Load the return address and frame pointer so it can be moved somewhere else
5648   // later.
5649   SDValue LROp, FPOp;
5650   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5651 
5652   // Set up a copy of the stack pointer for use loading and storing any
5653   // arguments that may not fit in the registers available for argument
5654   // passing.
5655   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5656 
5657   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5658   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5659   SmallVector<SDValue, 8> MemOpChains;
5660 
5661   bool seenFloatArg = false;
5662   // Walk the register/memloc assignments, inserting copies/loads.
5663   // i - Tracks the index into the list of registers allocated for the call
5664   // RealArgIdx - Tracks the index into the list of actual function arguments
5665   // j - Tracks the index into the list of byval arguments
5666   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5667        i != e;
5668        ++i, ++RealArgIdx) {
5669     CCValAssign &VA = ArgLocs[i];
5670     SDValue Arg = OutVals[RealArgIdx];
5671     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5672 
5673     if (Flags.isByVal()) {
5674       // Argument is an aggregate which is passed by value, thus we need to
5675       // create a copy of it in the local variable space of the current stack
5676       // frame (which is the stack frame of the caller) and pass the address of
5677       // this copy to the callee.
5678       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5679       CCValAssign &ByValVA = ByValArgLocs[j++];
5680       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5681 
5682       // Memory reserved in the local variable space of the callers stack frame.
5683       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5684 
5685       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5686       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5687                            StackPtr, PtrOff);
5688 
5689       // Create a copy of the argument in the local area of the current
5690       // stack frame.
5691       SDValue MemcpyCall =
5692         CreateCopyOfByValArgument(Arg, PtrOff,
5693                                   CallSeqStart.getNode()->getOperand(0),
5694                                   Flags, DAG, dl);
5695 
5696       // This must go outside the CALLSEQ_START..END.
5697       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5698                                                      SDLoc(MemcpyCall));
5699       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5700                              NewCallSeqStart.getNode());
5701       Chain = CallSeqStart = NewCallSeqStart;
5702 
5703       // Pass the address of the aggregate copy on the stack either in a
5704       // physical register or in the parameter list area of the current stack
5705       // frame to the callee.
5706       Arg = PtrOff;
5707     }
5708 
5709     // When useCRBits() is true, there can be i1 arguments.
5710     // It is because getRegisterType(MVT::i1) => MVT::i1,
5711     // and for other integer types getRegisterType() => MVT::i32.
5712     // Extend i1 and ensure callee will get i32.
5713     if (Arg.getValueType() == MVT::i1)
5714       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5715                         dl, MVT::i32, Arg);
5716 
5717     if (VA.isRegLoc()) {
5718       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5719       // Put argument in a physical register.
5720       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5721         bool IsLE = Subtarget.isLittleEndian();
5722         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5723                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5724         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5725         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5726                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5727         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5728                              SVal.getValue(0)));
5729       } else
5730         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5731     } else {
5732       // Put argument in the parameter list area of the current stack frame.
5733       assert(VA.isMemLoc());
5734       unsigned LocMemOffset = VA.getLocMemOffset();
5735 
5736       if (!IsTailCall) {
5737         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5738         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5739                              StackPtr, PtrOff);
5740 
5741         MemOpChains.push_back(
5742             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5743       } else {
5744         // Calculate and remember argument location.
5745         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5746                                  TailCallArguments);
5747       }
5748     }
5749   }
5750 
5751   if (!MemOpChains.empty())
5752     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5753 
5754   // Build a sequence of copy-to-reg nodes chained together with token chain
5755   // and flag operands which copy the outgoing args into the appropriate regs.
5756   SDValue InFlag;
5757   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5758     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5759                              RegsToPass[i].second, InFlag);
5760     InFlag = Chain.getValue(1);
5761   }
5762 
5763   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5764   // registers.
5765   if (IsVarArg) {
5766     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5767     SDValue Ops[] = { Chain, InFlag };
5768 
5769     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5770                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5771 
5772     InFlag = Chain.getValue(1);
5773   }
5774 
5775   if (IsTailCall)
5776     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5777                     TailCallArguments);
5778 
5779   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5780                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5781 }
5782 
5783 // Copy an argument into memory, being careful to do this outside the
5784 // call sequence for the call to which the argument belongs.
5785 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5786     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5787     SelectionDAG &DAG, const SDLoc &dl) const {
5788   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5789                         CallSeqStart.getNode()->getOperand(0),
5790                         Flags, DAG, dl);
5791   // The MEMCPY must go outside the CALLSEQ_START..END.
5792   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5793   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5794                                                  SDLoc(MemcpyCall));
5795   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5796                          NewCallSeqStart.getNode());
5797   return NewCallSeqStart;
5798 }
5799 
5800 SDValue PPCTargetLowering::LowerCall_64SVR4(
5801     SDValue Chain, SDValue Callee, CallFlags CFlags,
5802     const SmallVectorImpl<ISD::OutputArg> &Outs,
5803     const SmallVectorImpl<SDValue> &OutVals,
5804     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5805     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5806     const CallBase *CB) const {
5807   bool isELFv2ABI = Subtarget.isELFv2ABI();
5808   bool isLittleEndian = Subtarget.isLittleEndian();
5809   unsigned NumOps = Outs.size();
5810   bool IsSibCall = false;
5811   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5812 
5813   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5814   unsigned PtrByteSize = 8;
5815 
5816   MachineFunction &MF = DAG.getMachineFunction();
5817 
5818   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5819     IsSibCall = true;
5820 
5821   // Mark this function as potentially containing a function that contains a
5822   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5823   // and restoring the callers stack pointer in this functions epilog. This is
5824   // done because by tail calling the called function might overwrite the value
5825   // in this function's (MF) stack pointer stack slot 0(SP).
5826   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5827     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5828 
5829   assert(!(IsFastCall && CFlags.IsVarArg) &&
5830          "fastcc not supported on varargs functions");
5831 
5832   // Count how many bytes are to be pushed on the stack, including the linkage
5833   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5834   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5835   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5836   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5837   unsigned NumBytes = LinkageSize;
5838   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5839 
5840   static const MCPhysReg GPR[] = {
5841     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5842     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5843   };
5844   static const MCPhysReg VR[] = {
5845     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5846     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5847   };
5848 
5849   const unsigned NumGPRs = array_lengthof(GPR);
5850   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5851   const unsigned NumVRs  = array_lengthof(VR);
5852 
5853   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5854   // can be passed to the callee in registers.
5855   // For the fast calling convention, there is another check below.
5856   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5857   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5858   if (!HasParameterArea) {
5859     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5860     unsigned AvailableFPRs = NumFPRs;
5861     unsigned AvailableVRs = NumVRs;
5862     unsigned NumBytesTmp = NumBytes;
5863     for (unsigned i = 0; i != NumOps; ++i) {
5864       if (Outs[i].Flags.isNest()) continue;
5865       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5866                                  PtrByteSize, LinkageSize, ParamAreaSize,
5867                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5868         HasParameterArea = true;
5869     }
5870   }
5871 
5872   // When using the fast calling convention, we don't provide backing for
5873   // arguments that will be in registers.
5874   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5875 
5876   // Avoid allocating parameter area for fastcc functions if all the arguments
5877   // can be passed in the registers.
5878   if (IsFastCall)
5879     HasParameterArea = false;
5880 
5881   // Add up all the space actually used.
5882   for (unsigned i = 0; i != NumOps; ++i) {
5883     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5884     EVT ArgVT = Outs[i].VT;
5885     EVT OrigVT = Outs[i].ArgVT;
5886 
5887     if (Flags.isNest())
5888       continue;
5889 
5890     if (IsFastCall) {
5891       if (Flags.isByVal()) {
5892         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5893         if (NumGPRsUsed > NumGPRs)
5894           HasParameterArea = true;
5895       } else {
5896         switch (ArgVT.getSimpleVT().SimpleTy) {
5897         default: llvm_unreachable("Unexpected ValueType for argument!");
5898         case MVT::i1:
5899         case MVT::i32:
5900         case MVT::i64:
5901           if (++NumGPRsUsed <= NumGPRs)
5902             continue;
5903           break;
5904         case MVT::v4i32:
5905         case MVT::v8i16:
5906         case MVT::v16i8:
5907         case MVT::v2f64:
5908         case MVT::v2i64:
5909         case MVT::v1i128:
5910         case MVT::f128:
5911           if (++NumVRsUsed <= NumVRs)
5912             continue;
5913           break;
5914         case MVT::v4f32:
5915           if (++NumVRsUsed <= NumVRs)
5916             continue;
5917           break;
5918         case MVT::f32:
5919         case MVT::f64:
5920           if (++NumFPRsUsed <= NumFPRs)
5921             continue;
5922           break;
5923         }
5924         HasParameterArea = true;
5925       }
5926     }
5927 
5928     /* Respect alignment of argument on the stack.  */
5929     auto Alignement =
5930         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5931     NumBytes = alignTo(NumBytes, Alignement);
5932 
5933     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5934     if (Flags.isInConsecutiveRegsLast())
5935       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5936   }
5937 
5938   unsigned NumBytesActuallyUsed = NumBytes;
5939 
5940   // In the old ELFv1 ABI,
5941   // the prolog code of the callee may store up to 8 GPR argument registers to
5942   // the stack, allowing va_start to index over them in memory if its varargs.
5943   // Because we cannot tell if this is needed on the caller side, we have to
5944   // conservatively assume that it is needed.  As such, make sure we have at
5945   // least enough stack space for the caller to store the 8 GPRs.
5946   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5947   // really requires memory operands, e.g. a vararg function.
5948   if (HasParameterArea)
5949     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5950   else
5951     NumBytes = LinkageSize;
5952 
5953   // Tail call needs the stack to be aligned.
5954   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5955     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5956 
5957   int SPDiff = 0;
5958 
5959   // Calculate by how many bytes the stack has to be adjusted in case of tail
5960   // call optimization.
5961   if (!IsSibCall)
5962     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
5963 
5964   // To protect arguments on the stack from being clobbered in a tail call,
5965   // force all the loads to happen before doing any other lowering.
5966   if (CFlags.IsTailCall)
5967     Chain = DAG.getStackArgumentTokenFactor(Chain);
5968 
5969   // Adjust the stack pointer for the new arguments...
5970   // These operations are automatically eliminated by the prolog/epilog pass
5971   if (!IsSibCall)
5972     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5973   SDValue CallSeqStart = Chain;
5974 
5975   // Load the return address and frame pointer so it can be move somewhere else
5976   // later.
5977   SDValue LROp, FPOp;
5978   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5979 
5980   // Set up a copy of the stack pointer for use loading and storing any
5981   // arguments that may not fit in the registers available for argument
5982   // passing.
5983   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5984 
5985   // Figure out which arguments are going to go in registers, and which in
5986   // memory.  Also, if this is a vararg function, floating point operations
5987   // must be stored to our stack, and loaded into integer regs as well, if
5988   // any integer regs are available for argument passing.
5989   unsigned ArgOffset = LinkageSize;
5990 
5991   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5992   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5993 
5994   SmallVector<SDValue, 8> MemOpChains;
5995   for (unsigned i = 0; i != NumOps; ++i) {
5996     SDValue Arg = OutVals[i];
5997     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5998     EVT ArgVT = Outs[i].VT;
5999     EVT OrigVT = Outs[i].ArgVT;
6000 
6001     // PtrOff will be used to store the current argument to the stack if a
6002     // register cannot be found for it.
6003     SDValue PtrOff;
6004 
6005     // We re-align the argument offset for each argument, except when using the
6006     // fast calling convention, when we need to make sure we do that only when
6007     // we'll actually use a stack slot.
6008     auto ComputePtrOff = [&]() {
6009       /* Respect alignment of argument on the stack.  */
6010       auto Alignment =
6011           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6012       ArgOffset = alignTo(ArgOffset, Alignment);
6013 
6014       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6015 
6016       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6017     };
6018 
6019     if (!IsFastCall) {
6020       ComputePtrOff();
6021 
6022       /* Compute GPR index associated with argument offset.  */
6023       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6024       GPR_idx = std::min(GPR_idx, NumGPRs);
6025     }
6026 
6027     // Promote integers to 64-bit values.
6028     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6029       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6030       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6031       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6032     }
6033 
6034     // FIXME memcpy is used way more than necessary.  Correctness first.
6035     // Note: "by value" is code for passing a structure by value, not
6036     // basic types.
6037     if (Flags.isByVal()) {
6038       // Note: Size includes alignment padding, so
6039       //   struct x { short a; char b; }
6040       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6041       // These are the proper values we need for right-justifying the
6042       // aggregate in a parameter register.
6043       unsigned Size = Flags.getByValSize();
6044 
6045       // An empty aggregate parameter takes up no storage and no
6046       // registers.
6047       if (Size == 0)
6048         continue;
6049 
6050       if (IsFastCall)
6051         ComputePtrOff();
6052 
6053       // All aggregates smaller than 8 bytes must be passed right-justified.
6054       if (Size==1 || Size==2 || Size==4) {
6055         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6056         if (GPR_idx != NumGPRs) {
6057           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6058                                         MachinePointerInfo(), VT);
6059           MemOpChains.push_back(Load.getValue(1));
6060           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6061 
6062           ArgOffset += PtrByteSize;
6063           continue;
6064         }
6065       }
6066 
6067       if (GPR_idx == NumGPRs && Size < 8) {
6068         SDValue AddPtr = PtrOff;
6069         if (!isLittleEndian) {
6070           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6071                                           PtrOff.getValueType());
6072           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6073         }
6074         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6075                                                           CallSeqStart,
6076                                                           Flags, DAG, dl);
6077         ArgOffset += PtrByteSize;
6078         continue;
6079       }
6080       // Copy entire object into memory.  There are cases where gcc-generated
6081       // code assumes it is there, even if it could be put entirely into
6082       // registers.  (This is not what the doc says.)
6083 
6084       // FIXME: The above statement is likely due to a misunderstanding of the
6085       // documents.  All arguments must be copied into the parameter area BY
6086       // THE CALLEE in the event that the callee takes the address of any
6087       // formal argument.  That has not yet been implemented.  However, it is
6088       // reasonable to use the stack area as a staging area for the register
6089       // load.
6090 
6091       // Skip this for small aggregates, as we will use the same slot for a
6092       // right-justified copy, below.
6093       if (Size >= 8)
6094         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6095                                                           CallSeqStart,
6096                                                           Flags, DAG, dl);
6097 
6098       // When a register is available, pass a small aggregate right-justified.
6099       if (Size < 8 && GPR_idx != NumGPRs) {
6100         // The easiest way to get this right-justified in a register
6101         // is to copy the structure into the rightmost portion of a
6102         // local variable slot, then load the whole slot into the
6103         // register.
6104         // FIXME: The memcpy seems to produce pretty awful code for
6105         // small aggregates, particularly for packed ones.
6106         // FIXME: It would be preferable to use the slot in the
6107         // parameter save area instead of a new local variable.
6108         SDValue AddPtr = PtrOff;
6109         if (!isLittleEndian) {
6110           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6111           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6112         }
6113         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6114                                                           CallSeqStart,
6115                                                           Flags, DAG, dl);
6116 
6117         // Load the slot into the register.
6118         SDValue Load =
6119             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6120         MemOpChains.push_back(Load.getValue(1));
6121         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6122 
6123         // Done with this argument.
6124         ArgOffset += PtrByteSize;
6125         continue;
6126       }
6127 
6128       // For aggregates larger than PtrByteSize, copy the pieces of the
6129       // object that fit into registers from the parameter save area.
6130       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6131         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6132         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6133         if (GPR_idx != NumGPRs) {
6134           SDValue Load =
6135               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6136           MemOpChains.push_back(Load.getValue(1));
6137           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6138           ArgOffset += PtrByteSize;
6139         } else {
6140           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6141           break;
6142         }
6143       }
6144       continue;
6145     }
6146 
6147     switch (Arg.getSimpleValueType().SimpleTy) {
6148     default: llvm_unreachable("Unexpected ValueType for argument!");
6149     case MVT::i1:
6150     case MVT::i32:
6151     case MVT::i64:
6152       if (Flags.isNest()) {
6153         // The 'nest' parameter, if any, is passed in R11.
6154         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6155         break;
6156       }
6157 
6158       // These can be scalar arguments or elements of an integer array type
6159       // passed directly.  Clang may use those instead of "byval" aggregate
6160       // types to avoid forcing arguments to memory unnecessarily.
6161       if (GPR_idx != NumGPRs) {
6162         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6163       } else {
6164         if (IsFastCall)
6165           ComputePtrOff();
6166 
6167         assert(HasParameterArea &&
6168                "Parameter area must exist to pass an argument in memory.");
6169         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6170                          true, CFlags.IsTailCall, false, MemOpChains,
6171                          TailCallArguments, dl);
6172         if (IsFastCall)
6173           ArgOffset += PtrByteSize;
6174       }
6175       if (!IsFastCall)
6176         ArgOffset += PtrByteSize;
6177       break;
6178     case MVT::f32:
6179     case MVT::f64: {
6180       // These can be scalar arguments or elements of a float array type
6181       // passed directly.  The latter are used to implement ELFv2 homogenous
6182       // float aggregates.
6183 
6184       // Named arguments go into FPRs first, and once they overflow, the
6185       // remaining arguments go into GPRs and then the parameter save area.
6186       // Unnamed arguments for vararg functions always go to GPRs and
6187       // then the parameter save area.  For now, put all arguments to vararg
6188       // routines always in both locations (FPR *and* GPR or stack slot).
6189       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6190       bool NeededLoad = false;
6191 
6192       // First load the argument into the next available FPR.
6193       if (FPR_idx != NumFPRs)
6194         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6195 
6196       // Next, load the argument into GPR or stack slot if needed.
6197       if (!NeedGPROrStack)
6198         ;
6199       else if (GPR_idx != NumGPRs && !IsFastCall) {
6200         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6201         // once we support fp <-> gpr moves.
6202 
6203         // In the non-vararg case, this can only ever happen in the
6204         // presence of f32 array types, since otherwise we never run
6205         // out of FPRs before running out of GPRs.
6206         SDValue ArgVal;
6207 
6208         // Double values are always passed in a single GPR.
6209         if (Arg.getValueType() != MVT::f32) {
6210           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6211 
6212         // Non-array float values are extended and passed in a GPR.
6213         } else if (!Flags.isInConsecutiveRegs()) {
6214           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6215           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6216 
6217         // If we have an array of floats, we collect every odd element
6218         // together with its predecessor into one GPR.
6219         } else if (ArgOffset % PtrByteSize != 0) {
6220           SDValue Lo, Hi;
6221           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6222           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6223           if (!isLittleEndian)
6224             std::swap(Lo, Hi);
6225           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6226 
6227         // The final element, if even, goes into the first half of a GPR.
6228         } else if (Flags.isInConsecutiveRegsLast()) {
6229           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6230           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6231           if (!isLittleEndian)
6232             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6233                                  DAG.getConstant(32, dl, MVT::i32));
6234 
6235         // Non-final even elements are skipped; they will be handled
6236         // together the with subsequent argument on the next go-around.
6237         } else
6238           ArgVal = SDValue();
6239 
6240         if (ArgVal.getNode())
6241           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6242       } else {
6243         if (IsFastCall)
6244           ComputePtrOff();
6245 
6246         // Single-precision floating-point values are mapped to the
6247         // second (rightmost) word of the stack doubleword.
6248         if (Arg.getValueType() == MVT::f32 &&
6249             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6250           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6251           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6252         }
6253 
6254         assert(HasParameterArea &&
6255                "Parameter area must exist to pass an argument in memory.");
6256         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6257                          true, CFlags.IsTailCall, false, MemOpChains,
6258                          TailCallArguments, dl);
6259 
6260         NeededLoad = true;
6261       }
6262       // When passing an array of floats, the array occupies consecutive
6263       // space in the argument area; only round up to the next doubleword
6264       // at the end of the array.  Otherwise, each float takes 8 bytes.
6265       if (!IsFastCall || NeededLoad) {
6266         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6267                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6268         if (Flags.isInConsecutiveRegsLast())
6269           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6270       }
6271       break;
6272     }
6273     case MVT::v4f32:
6274     case MVT::v4i32:
6275     case MVT::v8i16:
6276     case MVT::v16i8:
6277     case MVT::v2f64:
6278     case MVT::v2i64:
6279     case MVT::v1i128:
6280     case MVT::f128:
6281       // These can be scalar arguments or elements of a vector array type
6282       // passed directly.  The latter are used to implement ELFv2 homogenous
6283       // vector aggregates.
6284 
6285       // For a varargs call, named arguments go into VRs or on the stack as
6286       // usual; unnamed arguments always go to the stack or the corresponding
6287       // GPRs when within range.  For now, we always put the value in both
6288       // locations (or even all three).
6289       if (CFlags.IsVarArg) {
6290         assert(HasParameterArea &&
6291                "Parameter area must exist if we have a varargs call.");
6292         // We could elide this store in the case where the object fits
6293         // entirely in R registers.  Maybe later.
6294         SDValue Store =
6295             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6296         MemOpChains.push_back(Store);
6297         if (VR_idx != NumVRs) {
6298           SDValue Load =
6299               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6300           MemOpChains.push_back(Load.getValue(1));
6301           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6302         }
6303         ArgOffset += 16;
6304         for (unsigned i=0; i<16; i+=PtrByteSize) {
6305           if (GPR_idx == NumGPRs)
6306             break;
6307           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6308                                    DAG.getConstant(i, dl, PtrVT));
6309           SDValue Load =
6310               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6311           MemOpChains.push_back(Load.getValue(1));
6312           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6313         }
6314         break;
6315       }
6316 
6317       // Non-varargs Altivec params go into VRs or on the stack.
6318       if (VR_idx != NumVRs) {
6319         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6320       } else {
6321         if (IsFastCall)
6322           ComputePtrOff();
6323 
6324         assert(HasParameterArea &&
6325                "Parameter area must exist to pass an argument in memory.");
6326         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6327                          true, CFlags.IsTailCall, true, MemOpChains,
6328                          TailCallArguments, dl);
6329         if (IsFastCall)
6330           ArgOffset += 16;
6331       }
6332 
6333       if (!IsFastCall)
6334         ArgOffset += 16;
6335       break;
6336     }
6337   }
6338 
6339   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6340          "mismatch in size of parameter area");
6341   (void)NumBytesActuallyUsed;
6342 
6343   if (!MemOpChains.empty())
6344     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6345 
6346   // Check if this is an indirect call (MTCTR/BCTRL).
6347   // See prepareDescriptorIndirectCall and buildCallOperands for more
6348   // information about calls through function pointers in the 64-bit SVR4 ABI.
6349   if (CFlags.IsIndirect) {
6350     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6351     // caller in the TOC save area.
6352     if (isTOCSaveRestoreRequired(Subtarget)) {
6353       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6354       // Load r2 into a virtual register and store it to the TOC save area.
6355       setUsesTOCBasePtr(DAG);
6356       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6357       // TOC save area offset.
6358       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6359       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6360       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6361       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6362                            MachinePointerInfo::getStack(
6363                                DAG.getMachineFunction(), TOCSaveOffset));
6364     }
6365     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6366     // This does not mean the MTCTR instruction must use R12; it's easier
6367     // to model this as an extra parameter, so do that.
6368     if (isELFv2ABI && !CFlags.IsPatchPoint)
6369       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6370   }
6371 
6372   // Build a sequence of copy-to-reg nodes chained together with token chain
6373   // and flag operands which copy the outgoing args into the appropriate regs.
6374   SDValue InFlag;
6375   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6376     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6377                              RegsToPass[i].second, InFlag);
6378     InFlag = Chain.getValue(1);
6379   }
6380 
6381   if (CFlags.IsTailCall && !IsSibCall)
6382     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6383                     TailCallArguments);
6384 
6385   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6386                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6387 }
6388 
6389 SDValue PPCTargetLowering::LowerCall_Darwin(
6390     SDValue Chain, SDValue Callee, CallFlags CFlags,
6391     const SmallVectorImpl<ISD::OutputArg> &Outs,
6392     const SmallVectorImpl<SDValue> &OutVals,
6393     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6394     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6395     const CallBase *CB) const {
6396   unsigned NumOps = Outs.size();
6397 
6398   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6399   bool isPPC64 = PtrVT == MVT::i64;
6400   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6401 
6402   MachineFunction &MF = DAG.getMachineFunction();
6403 
6404   // Mark this function as potentially containing a function that contains a
6405   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6406   // and restoring the callers stack pointer in this functions epilog. This is
6407   // done because by tail calling the called function might overwrite the value
6408   // in this function's (MF) stack pointer stack slot 0(SP).
6409   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6410       CFlags.CallConv == CallingConv::Fast)
6411     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6412 
6413   // Count how many bytes are to be pushed on the stack, including the linkage
6414   // area, and parameter passing area.  We start with 24/48 bytes, which is
6415   // prereserved space for [SP][CR][LR][3 x unused].
6416   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6417   unsigned NumBytes = LinkageSize;
6418 
6419   // Add up all the space actually used.
6420   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6421   // they all go in registers, but we must reserve stack space for them for
6422   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6423   // assigned stack space in order, with padding so Altivec parameters are
6424   // 16-byte aligned.
6425   unsigned nAltivecParamsAtEnd = 0;
6426   for (unsigned i = 0; i != NumOps; ++i) {
6427     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6428     EVT ArgVT = Outs[i].VT;
6429     // Varargs Altivec parameters are padded to a 16 byte boundary.
6430     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6431         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6432         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6433       if (!CFlags.IsVarArg && !isPPC64) {
6434         // Non-varargs Altivec parameters go after all the non-Altivec
6435         // parameters; handle those later so we know how much padding we need.
6436         nAltivecParamsAtEnd++;
6437         continue;
6438       }
6439       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6440       NumBytes = ((NumBytes+15)/16)*16;
6441     }
6442     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6443   }
6444 
6445   // Allow for Altivec parameters at the end, if needed.
6446   if (nAltivecParamsAtEnd) {
6447     NumBytes = ((NumBytes+15)/16)*16;
6448     NumBytes += 16*nAltivecParamsAtEnd;
6449   }
6450 
6451   // The prolog code of the callee may store up to 8 GPR argument registers to
6452   // the stack, allowing va_start to index over them in memory if its varargs.
6453   // Because we cannot tell if this is needed on the caller side, we have to
6454   // conservatively assume that it is needed.  As such, make sure we have at
6455   // least enough stack space for the caller to store the 8 GPRs.
6456   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6457 
6458   // Tail call needs the stack to be aligned.
6459   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6460       CFlags.CallConv == CallingConv::Fast)
6461     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6462 
6463   // Calculate by how many bytes the stack has to be adjusted in case of tail
6464   // call optimization.
6465   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6466 
6467   // To protect arguments on the stack from being clobbered in a tail call,
6468   // force all the loads to happen before doing any other lowering.
6469   if (CFlags.IsTailCall)
6470     Chain = DAG.getStackArgumentTokenFactor(Chain);
6471 
6472   // Adjust the stack pointer for the new arguments...
6473   // These operations are automatically eliminated by the prolog/epilog pass
6474   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6475   SDValue CallSeqStart = Chain;
6476 
6477   // Load the return address and frame pointer so it can be move somewhere else
6478   // later.
6479   SDValue LROp, FPOp;
6480   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6481 
6482   // Set up a copy of the stack pointer for use loading and storing any
6483   // arguments that may not fit in the registers available for argument
6484   // passing.
6485   SDValue StackPtr;
6486   if (isPPC64)
6487     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6488   else
6489     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6490 
6491   // Figure out which arguments are going to go in registers, and which in
6492   // memory.  Also, if this is a vararg function, floating point operations
6493   // must be stored to our stack, and loaded into integer regs as well, if
6494   // any integer regs are available for argument passing.
6495   unsigned ArgOffset = LinkageSize;
6496   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6497 
6498   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6499     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6500     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6501   };
6502   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6503     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6504     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6505   };
6506   static const MCPhysReg VR[] = {
6507     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6508     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6509   };
6510   const unsigned NumGPRs = array_lengthof(GPR_32);
6511   const unsigned NumFPRs = 13;
6512   const unsigned NumVRs  = array_lengthof(VR);
6513 
6514   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6515 
6516   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6517   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6518 
6519   SmallVector<SDValue, 8> MemOpChains;
6520   for (unsigned i = 0; i != NumOps; ++i) {
6521     SDValue Arg = OutVals[i];
6522     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6523 
6524     // PtrOff will be used to store the current argument to the stack if a
6525     // register cannot be found for it.
6526     SDValue PtrOff;
6527 
6528     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6529 
6530     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6531 
6532     // On PPC64, promote integers to 64-bit values.
6533     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6534       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6535       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6536       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6537     }
6538 
6539     // FIXME memcpy is used way more than necessary.  Correctness first.
6540     // Note: "by value" is code for passing a structure by value, not
6541     // basic types.
6542     if (Flags.isByVal()) {
6543       unsigned Size = Flags.getByValSize();
6544       // Very small objects are passed right-justified.  Everything else is
6545       // passed left-justified.
6546       if (Size==1 || Size==2) {
6547         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6548         if (GPR_idx != NumGPRs) {
6549           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6550                                         MachinePointerInfo(), VT);
6551           MemOpChains.push_back(Load.getValue(1));
6552           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6553 
6554           ArgOffset += PtrByteSize;
6555         } else {
6556           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6557                                           PtrOff.getValueType());
6558           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6559           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6560                                                             CallSeqStart,
6561                                                             Flags, DAG, dl);
6562           ArgOffset += PtrByteSize;
6563         }
6564         continue;
6565       }
6566       // Copy entire object into memory.  There are cases where gcc-generated
6567       // code assumes it is there, even if it could be put entirely into
6568       // registers.  (This is not what the doc says.)
6569       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6570                                                         CallSeqStart,
6571                                                         Flags, DAG, dl);
6572 
6573       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6574       // copy the pieces of the object that fit into registers from the
6575       // parameter save area.
6576       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6577         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6578         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6579         if (GPR_idx != NumGPRs) {
6580           SDValue Load =
6581               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6582           MemOpChains.push_back(Load.getValue(1));
6583           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6584           ArgOffset += PtrByteSize;
6585         } else {
6586           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6587           break;
6588         }
6589       }
6590       continue;
6591     }
6592 
6593     switch (Arg.getSimpleValueType().SimpleTy) {
6594     default: llvm_unreachable("Unexpected ValueType for argument!");
6595     case MVT::i1:
6596     case MVT::i32:
6597     case MVT::i64:
6598       if (GPR_idx != NumGPRs) {
6599         if (Arg.getValueType() == MVT::i1)
6600           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6601 
6602         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6603       } else {
6604         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6605                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6606                          TailCallArguments, dl);
6607       }
6608       ArgOffset += PtrByteSize;
6609       break;
6610     case MVT::f32:
6611     case MVT::f64:
6612       if (FPR_idx != NumFPRs) {
6613         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6614 
6615         if (CFlags.IsVarArg) {
6616           SDValue Store =
6617               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6618           MemOpChains.push_back(Store);
6619 
6620           // Float varargs are always shadowed in available integer registers
6621           if (GPR_idx != NumGPRs) {
6622             SDValue Load =
6623                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6624             MemOpChains.push_back(Load.getValue(1));
6625             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6626           }
6627           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6628             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6629             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6630             SDValue Load =
6631                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6632             MemOpChains.push_back(Load.getValue(1));
6633             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6634           }
6635         } else {
6636           // If we have any FPRs remaining, we may also have GPRs remaining.
6637           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6638           // GPRs.
6639           if (GPR_idx != NumGPRs)
6640             ++GPR_idx;
6641           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6642               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6643             ++GPR_idx;
6644         }
6645       } else
6646         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6647                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6648                          TailCallArguments, dl);
6649       if (isPPC64)
6650         ArgOffset += 8;
6651       else
6652         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6653       break;
6654     case MVT::v4f32:
6655     case MVT::v4i32:
6656     case MVT::v8i16:
6657     case MVT::v16i8:
6658       if (CFlags.IsVarArg) {
6659         // These go aligned on the stack, or in the corresponding R registers
6660         // when within range.  The Darwin PPC ABI doc claims they also go in
6661         // V registers; in fact gcc does this only for arguments that are
6662         // prototyped, not for those that match the ...  We do it for all
6663         // arguments, seems to work.
6664         while (ArgOffset % 16 !=0) {
6665           ArgOffset += PtrByteSize;
6666           if (GPR_idx != NumGPRs)
6667             GPR_idx++;
6668         }
6669         // We could elide this store in the case where the object fits
6670         // entirely in R registers.  Maybe later.
6671         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6672                              DAG.getConstant(ArgOffset, dl, PtrVT));
6673         SDValue Store =
6674             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6675         MemOpChains.push_back(Store);
6676         if (VR_idx != NumVRs) {
6677           SDValue Load =
6678               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6679           MemOpChains.push_back(Load.getValue(1));
6680           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6681         }
6682         ArgOffset += 16;
6683         for (unsigned i=0; i<16; i+=PtrByteSize) {
6684           if (GPR_idx == NumGPRs)
6685             break;
6686           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6687                                    DAG.getConstant(i, dl, PtrVT));
6688           SDValue Load =
6689               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6690           MemOpChains.push_back(Load.getValue(1));
6691           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6692         }
6693         break;
6694       }
6695 
6696       // Non-varargs Altivec params generally go in registers, but have
6697       // stack space allocated at the end.
6698       if (VR_idx != NumVRs) {
6699         // Doesn't have GPR space allocated.
6700         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6701       } else if (nAltivecParamsAtEnd==0) {
6702         // We are emitting Altivec params in order.
6703         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6704                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6705                          TailCallArguments, dl);
6706         ArgOffset += 16;
6707       }
6708       break;
6709     }
6710   }
6711   // If all Altivec parameters fit in registers, as they usually do,
6712   // they get stack space following the non-Altivec parameters.  We
6713   // don't track this here because nobody below needs it.
6714   // If there are more Altivec parameters than fit in registers emit
6715   // the stores here.
6716   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6717     unsigned j = 0;
6718     // Offset is aligned; skip 1st 12 params which go in V registers.
6719     ArgOffset = ((ArgOffset+15)/16)*16;
6720     ArgOffset += 12*16;
6721     for (unsigned i = 0; i != NumOps; ++i) {
6722       SDValue Arg = OutVals[i];
6723       EVT ArgType = Outs[i].VT;
6724       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6725           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6726         if (++j > NumVRs) {
6727           SDValue PtrOff;
6728           // We are emitting Altivec params in order.
6729           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6730                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6731                            TailCallArguments, dl);
6732           ArgOffset += 16;
6733         }
6734       }
6735     }
6736   }
6737 
6738   if (!MemOpChains.empty())
6739     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6740 
6741   // On Darwin, R12 must contain the address of an indirect callee.  This does
6742   // not mean the MTCTR instruction must use R12; it's easier to model this as
6743   // an extra parameter, so do that.
6744   if (CFlags.IsIndirect) {
6745     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6746     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6747                                                    PPC::R12), Callee));
6748   }
6749 
6750   // Build a sequence of copy-to-reg nodes chained together with token chain
6751   // and flag operands which copy the outgoing args into the appropriate regs.
6752   SDValue InFlag;
6753   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6754     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6755                              RegsToPass[i].second, InFlag);
6756     InFlag = Chain.getValue(1);
6757   }
6758 
6759   if (CFlags.IsTailCall)
6760     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6761                     TailCallArguments);
6762 
6763   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6764                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6765 }
6766 
6767 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6768                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6769                    CCState &State) {
6770 
6771   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6772       State.getMachineFunction().getSubtarget());
6773   const bool IsPPC64 = Subtarget.isPPC64();
6774   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6775   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6776 
6777   assert((!ValVT.isInteger() ||
6778           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6779          "Integer argument exceeds register size: should have been legalized");
6780 
6781   if (ValVT == MVT::f128)
6782     report_fatal_error("f128 is unimplemented on AIX.");
6783 
6784   if (ArgFlags.isNest())
6785     report_fatal_error("Nest arguments are unimplemented.");
6786 
6787   if (ValVT.isVector() || LocVT.isVector())
6788     report_fatal_error("Vector arguments are unimplemented on AIX.");
6789 
6790   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6791                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6792                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6793   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6794                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6795                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6796 
6797   if (ArgFlags.isByVal()) {
6798     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6799       report_fatal_error("Pass-by-value arguments with alignment greater than "
6800                          "register width are not supported.");
6801 
6802     const unsigned ByValSize = ArgFlags.getByValSize();
6803 
6804     // An empty aggregate parameter takes up no storage and no registers,
6805     // but needs a MemLoc for a stack slot for the formal arguments side.
6806     if (ByValSize == 0) {
6807       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6808                                        State.getNextStackOffset(), RegVT,
6809                                        LocInfo));
6810       return false;
6811     }
6812 
6813     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6814     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6815     for (const unsigned E = Offset + StackSize; Offset < E;
6816          Offset += PtrAlign.value()) {
6817       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6818         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6819       else {
6820         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6821                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6822                                          LocInfo));
6823         break;
6824       }
6825     }
6826     return false;
6827   }
6828 
6829   // Arguments always reserve parameter save area.
6830   switch (ValVT.SimpleTy) {
6831   default:
6832     report_fatal_error("Unhandled value type for argument.");
6833   case MVT::i64:
6834     // i64 arguments should have been split to i32 for PPC32.
6835     assert(IsPPC64 && "PPC32 should have split i64 values.");
6836     LLVM_FALLTHROUGH;
6837   case MVT::i1:
6838   case MVT::i32: {
6839     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6840     // AIX integer arguments are always passed in register width.
6841     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6842       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6843                                   : CCValAssign::LocInfo::ZExt;
6844     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6845       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6846     else
6847       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6848 
6849     return false;
6850   }
6851   case MVT::f32:
6852   case MVT::f64: {
6853     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6854     const unsigned StoreSize = LocVT.getStoreSize();
6855     // Floats are always 4-byte aligned in the PSA on AIX.
6856     // This includes f64 in 64-bit mode for ABI compatibility.
6857     const unsigned Offset =
6858         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6859     unsigned FReg = State.AllocateReg(FPR);
6860     if (FReg)
6861       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6862 
6863     // Reserve and initialize GPRs or initialize the PSA as required.
6864     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6865       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6866         assert(FReg && "An FPR should be available when a GPR is reserved.");
6867         if (State.isVarArg()) {
6868           // Successfully reserved GPRs are only initialized for vararg calls.
6869           // Custom handling is required for:
6870           //   f64 in PPC32 needs to be split into 2 GPRs.
6871           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6872           State.addLoc(
6873               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6874         }
6875       } else {
6876         // If there are insufficient GPRs, the PSA needs to be initialized.
6877         // Initialization occurs even if an FPR was initialized for
6878         // compatibility with the AIX XL compiler. The full memory for the
6879         // argument will be initialized even if a prior word is saved in GPR.
6880         // A custom memLoc is used when the argument also passes in FPR so
6881         // that the callee handling can skip over it easily.
6882         State.addLoc(
6883             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6884                                              LocInfo)
6885                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6886         break;
6887       }
6888     }
6889 
6890     return false;
6891   }
6892   }
6893   return true;
6894 }
6895 
6896 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6897                                                     bool IsPPC64) {
6898   assert((IsPPC64 || SVT != MVT::i64) &&
6899          "i64 should have been split for 32-bit codegen.");
6900 
6901   switch (SVT) {
6902   default:
6903     report_fatal_error("Unexpected value type for formal argument");
6904   case MVT::i1:
6905   case MVT::i32:
6906   case MVT::i64:
6907     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6908   case MVT::f32:
6909     return &PPC::F4RCRegClass;
6910   case MVT::f64:
6911     return &PPC::F8RCRegClass;
6912   }
6913 }
6914 
6915 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6916                                         SelectionDAG &DAG, SDValue ArgValue,
6917                                         MVT LocVT, const SDLoc &dl) {
6918   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6919   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6920 
6921   if (Flags.isSExt())
6922     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6923                            DAG.getValueType(ValVT));
6924   else if (Flags.isZExt())
6925     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6926                            DAG.getValueType(ValVT));
6927 
6928   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6929 }
6930 
6931 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6932   const unsigned LASize = FL->getLinkageSize();
6933 
6934   if (PPC::GPRCRegClass.contains(Reg)) {
6935     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6936            "Reg must be a valid argument register!");
6937     return LASize + 4 * (Reg - PPC::R3);
6938   }
6939 
6940   if (PPC::G8RCRegClass.contains(Reg)) {
6941     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6942            "Reg must be a valid argument register!");
6943     return LASize + 8 * (Reg - PPC::X3);
6944   }
6945 
6946   llvm_unreachable("Only general purpose registers expected.");
6947 }
6948 
6949 //   AIX ABI Stack Frame Layout:
6950 //
6951 //   Low Memory +--------------------------------------------+
6952 //   SP   +---> | Back chain                                 | ---+
6953 //        |     +--------------------------------------------+    |
6954 //        |     | Saved Condition Register                   |    |
6955 //        |     +--------------------------------------------+    |
6956 //        |     | Saved Linkage Register                     |    |
6957 //        |     +--------------------------------------------+    | Linkage Area
6958 //        |     | Reserved for compilers                     |    |
6959 //        |     +--------------------------------------------+    |
6960 //        |     | Reserved for binders                       |    |
6961 //        |     +--------------------------------------------+    |
6962 //        |     | Saved TOC pointer                          | ---+
6963 //        |     +--------------------------------------------+
6964 //        |     | Parameter save area                        |
6965 //        |     +--------------------------------------------+
6966 //        |     | Alloca space                               |
6967 //        |     +--------------------------------------------+
6968 //        |     | Local variable space                       |
6969 //        |     +--------------------------------------------+
6970 //        |     | Float/int conversion temporary             |
6971 //        |     +--------------------------------------------+
6972 //        |     | Save area for AltiVec registers            |
6973 //        |     +--------------------------------------------+
6974 //        |     | AltiVec alignment padding                  |
6975 //        |     +--------------------------------------------+
6976 //        |     | Save area for VRSAVE register              |
6977 //        |     +--------------------------------------------+
6978 //        |     | Save area for General Purpose registers    |
6979 //        |     +--------------------------------------------+
6980 //        |     | Save area for Floating Point registers     |
6981 //        |     +--------------------------------------------+
6982 //        +---- | Back chain                                 |
6983 // High Memory  +--------------------------------------------+
6984 //
6985 //  Specifications:
6986 //  AIX 7.2 Assembler Language Reference
6987 //  Subroutine linkage convention
6988 
6989 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6990     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6991     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6992     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6993 
6994   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6995           CallConv == CallingConv::Fast) &&
6996          "Unexpected calling convention!");
6997 
6998   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6999     report_fatal_error("Tail call support is unimplemented on AIX.");
7000 
7001   if (useSoftFloat())
7002     report_fatal_error("Soft float support is unimplemented on AIX.");
7003 
7004   const PPCSubtarget &Subtarget =
7005       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7006 
7007   const bool IsPPC64 = Subtarget.isPPC64();
7008   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7009 
7010   // Assign locations to all of the incoming arguments.
7011   SmallVector<CCValAssign, 16> ArgLocs;
7012   MachineFunction &MF = DAG.getMachineFunction();
7013   MachineFrameInfo &MFI = MF.getFrameInfo();
7014   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7015 
7016   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7017   // Reserve space for the linkage area on the stack.
7018   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7019   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7020   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7021 
7022   SmallVector<SDValue, 8> MemOps;
7023 
7024   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7025     CCValAssign &VA = ArgLocs[I++];
7026     MVT LocVT = VA.getLocVT();
7027     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7028 
7029     // For compatibility with the AIX XL compiler, the float args in the
7030     // parameter save area are initialized even if the argument is available
7031     // in register.  The caller is required to initialize both the register
7032     // and memory, however, the callee can choose to expect it in either.
7033     // The memloc is dismissed here because the argument is retrieved from
7034     // the register.
7035     if (VA.isMemLoc() && VA.needsCustom())
7036       continue;
7037 
7038     if (Flags.isByVal() && VA.isMemLoc()) {
7039       const unsigned Size =
7040           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7041                   PtrByteSize);
7042       const int FI = MF.getFrameInfo().CreateFixedObject(
7043           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7044           /* IsAliased */ true);
7045       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7046       InVals.push_back(FIN);
7047 
7048       continue;
7049     }
7050 
7051     if (Flags.isByVal()) {
7052       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7053 
7054       const MCPhysReg ArgReg = VA.getLocReg();
7055       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7056 
7057       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7058         report_fatal_error("Over aligned byvals not supported yet.");
7059 
7060       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7061       const int FI = MF.getFrameInfo().CreateFixedObject(
7062           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7063           /* IsAliased */ true);
7064       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7065       InVals.push_back(FIN);
7066 
7067       // Add live ins for all the RegLocs for the same ByVal.
7068       const TargetRegisterClass *RegClass =
7069           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7070 
7071       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7072                                                unsigned Offset) {
7073         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7074         // Since the callers side has left justified the aggregate in the
7075         // register, we can simply store the entire register into the stack
7076         // slot.
7077         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7078         // The store to the fixedstack object is needed becuase accessing a
7079         // field of the ByVal will use a gep and load. Ideally we will optimize
7080         // to extracting the value from the register directly, and elide the
7081         // stores when the arguments address is not taken, but that will need to
7082         // be future work.
7083         SDValue Store =
7084             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7085                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7086                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7087 
7088         MemOps.push_back(Store);
7089       };
7090 
7091       unsigned Offset = 0;
7092       HandleRegLoc(VA.getLocReg(), Offset);
7093       Offset += PtrByteSize;
7094       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7095            Offset += PtrByteSize) {
7096         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7097                "RegLocs should be for ByVal argument.");
7098 
7099         const CCValAssign RL = ArgLocs[I++];
7100         HandleRegLoc(RL.getLocReg(), Offset);
7101       }
7102 
7103       if (Offset != StackSize) {
7104         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7105                "Expected MemLoc for remaining bytes.");
7106         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7107         // Consume the MemLoc.The InVal has already been emitted, so nothing
7108         // more needs to be done.
7109         ++I;
7110       }
7111 
7112       continue;
7113     }
7114 
7115     EVT ValVT = VA.getValVT();
7116     if (VA.isRegLoc() && !VA.needsCustom()) {
7117       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7118       unsigned VReg =
7119           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7120       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7121       if (ValVT.isScalarInteger() &&
7122           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7123         ArgValue =
7124             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7125       }
7126       InVals.push_back(ArgValue);
7127       continue;
7128     }
7129     if (VA.isMemLoc()) {
7130       const unsigned LocSize = LocVT.getStoreSize();
7131       const unsigned ValSize = ValVT.getStoreSize();
7132       assert((ValSize <= LocSize) &&
7133              "Object size is larger than size of MemLoc");
7134       int CurArgOffset = VA.getLocMemOffset();
7135       // Objects are right-justified because AIX is big-endian.
7136       if (LocSize > ValSize)
7137         CurArgOffset += LocSize - ValSize;
7138       // Potential tail calls could cause overwriting of argument stack slots.
7139       const bool IsImmutable =
7140           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7141             (CallConv == CallingConv::Fast));
7142       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7143       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7144       SDValue ArgValue =
7145           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7146       InVals.push_back(ArgValue);
7147       continue;
7148     }
7149   }
7150 
7151   // On AIX a minimum of 8 words is saved to the parameter save area.
7152   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7153   // Area that is at least reserved in the caller of this function.
7154   unsigned CallerReservedArea =
7155       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7156 
7157   // Set the size that is at least reserved in caller of this function. Tail
7158   // call optimized function's reserved stack space needs to be aligned so
7159   // that taking the difference between two stack areas will result in an
7160   // aligned stack.
7161   CallerReservedArea =
7162       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7163   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7164   FuncInfo->setMinReservedArea(CallerReservedArea);
7165 
7166   if (isVarArg) {
7167     FuncInfo->setVarArgsFrameIndex(
7168         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7169     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7170 
7171     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7172                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7173 
7174     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7175                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7176     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7177 
7178     // The fixed integer arguments of a variadic function are stored to the
7179     // VarArgsFrameIndex on the stack so that they may be loaded by
7180     // dereferencing the result of va_next.
7181     for (unsigned GPRIndex =
7182              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7183          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7184 
7185       const unsigned VReg =
7186           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7187                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7188 
7189       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7190       SDValue Store =
7191           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7192       MemOps.push_back(Store);
7193       // Increment the address for the next argument to store.
7194       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7195       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7196     }
7197   }
7198 
7199   if (!MemOps.empty())
7200     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7201 
7202   return Chain;
7203 }
7204 
7205 SDValue PPCTargetLowering::LowerCall_AIX(
7206     SDValue Chain, SDValue Callee, CallFlags CFlags,
7207     const SmallVectorImpl<ISD::OutputArg> &Outs,
7208     const SmallVectorImpl<SDValue> &OutVals,
7209     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7210     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7211     const CallBase *CB) const {
7212   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7213   // AIX ABI stack frame layout.
7214 
7215   assert((CFlags.CallConv == CallingConv::C ||
7216           CFlags.CallConv == CallingConv::Cold ||
7217           CFlags.CallConv == CallingConv::Fast) &&
7218          "Unexpected calling convention!");
7219 
7220   if (CFlags.IsPatchPoint)
7221     report_fatal_error("This call type is unimplemented on AIX.");
7222 
7223   const PPCSubtarget& Subtarget =
7224       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7225   if (Subtarget.hasAltivec())
7226     report_fatal_error("Altivec support is unimplemented on AIX.");
7227 
7228   MachineFunction &MF = DAG.getMachineFunction();
7229   SmallVector<CCValAssign, 16> ArgLocs;
7230   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7231                  *DAG.getContext());
7232 
7233   // Reserve space for the linkage save area (LSA) on the stack.
7234   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7235   //   [SP][CR][LR][2 x reserved][TOC].
7236   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7237   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7238   const bool IsPPC64 = Subtarget.isPPC64();
7239   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7240   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7241   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7242   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7243 
7244   // The prolog code of the callee may store up to 8 GPR argument registers to
7245   // the stack, allowing va_start to index over them in memory if the callee
7246   // is variadic.
7247   // Because we cannot tell if this is needed on the caller side, we have to
7248   // conservatively assume that it is needed.  As such, make sure we have at
7249   // least enough stack space for the caller to store the 8 GPRs.
7250   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7251   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7252                                      CCInfo.getNextStackOffset());
7253 
7254   // Adjust the stack pointer for the new arguments...
7255   // These operations are automatically eliminated by the prolog/epilog pass.
7256   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7257   SDValue CallSeqStart = Chain;
7258 
7259   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7260   SmallVector<SDValue, 8> MemOpChains;
7261 
7262   // Set up a copy of the stack pointer for loading and storing any
7263   // arguments that may not fit in the registers available for argument
7264   // passing.
7265   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7266                                    : DAG.getRegister(PPC::R1, MVT::i32);
7267 
7268   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7269     const unsigned ValNo = ArgLocs[I].getValNo();
7270     SDValue Arg = OutVals[ValNo];
7271     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7272 
7273     if (Flags.isByVal()) {
7274       const unsigned ByValSize = Flags.getByValSize();
7275 
7276       // Nothing to do for zero-sized ByVals on the caller side.
7277       if (!ByValSize) {
7278         ++I;
7279         continue;
7280       }
7281 
7282       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7283         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7284                               (LoadOffset != 0)
7285                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7286                                   : Arg,
7287                               MachinePointerInfo(), VT);
7288       };
7289 
7290       unsigned LoadOffset = 0;
7291 
7292       // Initialize registers, which are fully occupied by the by-val argument.
7293       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7294         SDValue Load = GetLoad(PtrVT, LoadOffset);
7295         MemOpChains.push_back(Load.getValue(1));
7296         LoadOffset += PtrByteSize;
7297         const CCValAssign &ByValVA = ArgLocs[I++];
7298         assert(ByValVA.getValNo() == ValNo &&
7299                "Unexpected location for pass-by-value argument.");
7300         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7301       }
7302 
7303       if (LoadOffset == ByValSize)
7304         continue;
7305 
7306       // There must be one more loc to handle the remainder.
7307       assert(ArgLocs[I].getValNo() == ValNo &&
7308              "Expected additional location for by-value argument.");
7309 
7310       if (ArgLocs[I].isMemLoc()) {
7311         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7312         const CCValAssign &ByValVA = ArgLocs[I++];
7313         ISD::ArgFlagsTy MemcpyFlags = Flags;
7314         // Only memcpy the bytes that don't pass in register.
7315         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7316         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7317             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7318                               : Arg,
7319             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7320             CallSeqStart, MemcpyFlags, DAG, dl);
7321         continue;
7322       }
7323 
7324       // Initialize the final register residue.
7325       // Any residue that occupies the final by-val arg register must be
7326       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7327       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7328       // 2 and 1 byte loads.
7329       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7330       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7331              "Unexpected register residue for by-value argument.");
7332       SDValue ResidueVal;
7333       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7334         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7335         const MVT VT =
7336             N == 1 ? MVT::i8
7337                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7338         SDValue Load = GetLoad(VT, LoadOffset);
7339         MemOpChains.push_back(Load.getValue(1));
7340         LoadOffset += N;
7341         Bytes += N;
7342 
7343         // By-val arguments are passed left-justfied in register.
7344         // Every load here needs to be shifted, otherwise a full register load
7345         // should have been used.
7346         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7347                "Unexpected load emitted during handling of pass-by-value "
7348                "argument.");
7349         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7350         EVT ShiftAmountTy =
7351             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7352         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7353         SDValue ShiftedLoad =
7354             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7355         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7356                                               ShiftedLoad)
7357                                 : ShiftedLoad;
7358       }
7359 
7360       const CCValAssign &ByValVA = ArgLocs[I++];
7361       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7362       continue;
7363     }
7364 
7365     CCValAssign &VA = ArgLocs[I++];
7366     const MVT LocVT = VA.getLocVT();
7367     const MVT ValVT = VA.getValVT();
7368 
7369     switch (VA.getLocInfo()) {
7370     default:
7371       report_fatal_error("Unexpected argument extension type.");
7372     case CCValAssign::Full:
7373       break;
7374     case CCValAssign::ZExt:
7375       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7376       break;
7377     case CCValAssign::SExt:
7378       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7379       break;
7380     }
7381 
7382     if (VA.isRegLoc() && !VA.needsCustom()) {
7383       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7384       continue;
7385     }
7386 
7387     if (VA.isMemLoc()) {
7388       SDValue PtrOff =
7389           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7390       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7391       MemOpChains.push_back(
7392           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7393 
7394       continue;
7395     }
7396 
7397     // Custom handling is used for GPR initializations for vararg float
7398     // arguments.
7399     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7400            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7401            "Unexpected register handling for calling convention.");
7402 
7403     SDValue ArgAsInt =
7404         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7405 
7406     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7407       // f32 in 32-bit GPR
7408       // f64 in 64-bit GPR
7409       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7410     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7411       // f32 in 64-bit GPR.
7412       RegsToPass.push_back(std::make_pair(
7413           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7414     else {
7415       // f64 in two 32-bit GPRs
7416       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7417       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7418              "Unexpected custom register for argument!");
7419       CCValAssign &GPR1 = VA;
7420       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7421                                      DAG.getConstant(32, dl, MVT::i8));
7422       RegsToPass.push_back(std::make_pair(
7423           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7424 
7425       if (I != E) {
7426         // If only 1 GPR was available, there will only be one custom GPR and
7427         // the argument will also pass in memory.
7428         CCValAssign &PeekArg = ArgLocs[I];
7429         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7430           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7431           CCValAssign &GPR2 = ArgLocs[I++];
7432           RegsToPass.push_back(std::make_pair(
7433               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7434         }
7435       }
7436     }
7437   }
7438 
7439   if (!MemOpChains.empty())
7440     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7441 
7442   // For indirect calls, we need to save the TOC base to the stack for
7443   // restoration after the call.
7444   if (CFlags.IsIndirect) {
7445     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7446     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7447     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7448     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7449     const unsigned TOCSaveOffset =
7450         Subtarget.getFrameLowering()->getTOCSaveOffset();
7451 
7452     setUsesTOCBasePtr(DAG);
7453     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7454     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7455     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7456     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7457     Chain = DAG.getStore(
7458         Val.getValue(1), dl, Val, AddPtr,
7459         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7460   }
7461 
7462   // Build a sequence of copy-to-reg nodes chained together with token chain
7463   // and flag operands which copy the outgoing args into the appropriate regs.
7464   SDValue InFlag;
7465   for (auto Reg : RegsToPass) {
7466     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7467     InFlag = Chain.getValue(1);
7468   }
7469 
7470   const int SPDiff = 0;
7471   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7472                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7473 }
7474 
7475 bool
7476 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7477                                   MachineFunction &MF, bool isVarArg,
7478                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7479                                   LLVMContext &Context) const {
7480   SmallVector<CCValAssign, 16> RVLocs;
7481   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7482   return CCInfo.CheckReturn(
7483       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7484                 ? RetCC_PPC_Cold
7485                 : RetCC_PPC);
7486 }
7487 
7488 SDValue
7489 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7490                                bool isVarArg,
7491                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7492                                const SmallVectorImpl<SDValue> &OutVals,
7493                                const SDLoc &dl, SelectionDAG &DAG) const {
7494   SmallVector<CCValAssign, 16> RVLocs;
7495   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7496                  *DAG.getContext());
7497   CCInfo.AnalyzeReturn(Outs,
7498                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7499                            ? RetCC_PPC_Cold
7500                            : RetCC_PPC);
7501 
7502   SDValue Flag;
7503   SmallVector<SDValue, 4> RetOps(1, Chain);
7504 
7505   // Copy the result values into the output registers.
7506   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7507     CCValAssign &VA = RVLocs[i];
7508     assert(VA.isRegLoc() && "Can only return in registers!");
7509 
7510     SDValue Arg = OutVals[RealResIdx];
7511 
7512     switch (VA.getLocInfo()) {
7513     default: llvm_unreachable("Unknown loc info!");
7514     case CCValAssign::Full: break;
7515     case CCValAssign::AExt:
7516       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7517       break;
7518     case CCValAssign::ZExt:
7519       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7520       break;
7521     case CCValAssign::SExt:
7522       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7523       break;
7524     }
7525     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7526       bool isLittleEndian = Subtarget.isLittleEndian();
7527       // Legalize ret f64 -> ret 2 x i32.
7528       SDValue SVal =
7529           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7530                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7531       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7532       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7533       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7534                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7535       Flag = Chain.getValue(1);
7536       VA = RVLocs[++i]; // skip ahead to next loc
7537       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7538     } else
7539       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7540     Flag = Chain.getValue(1);
7541     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7542   }
7543 
7544   RetOps[0] = Chain;  // Update chain.
7545 
7546   // Add the flag if we have it.
7547   if (Flag.getNode())
7548     RetOps.push_back(Flag);
7549 
7550   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7551 }
7552 
7553 SDValue
7554 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7555                                                 SelectionDAG &DAG) const {
7556   SDLoc dl(Op);
7557 
7558   // Get the correct type for integers.
7559   EVT IntVT = Op.getValueType();
7560 
7561   // Get the inputs.
7562   SDValue Chain = Op.getOperand(0);
7563   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7564   // Build a DYNAREAOFFSET node.
7565   SDValue Ops[2] = {Chain, FPSIdx};
7566   SDVTList VTs = DAG.getVTList(IntVT);
7567   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7568 }
7569 
7570 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7571                                              SelectionDAG &DAG) const {
7572   // When we pop the dynamic allocation we need to restore the SP link.
7573   SDLoc dl(Op);
7574 
7575   // Get the correct type for pointers.
7576   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7577 
7578   // Construct the stack pointer operand.
7579   bool isPPC64 = Subtarget.isPPC64();
7580   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7581   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7582 
7583   // Get the operands for the STACKRESTORE.
7584   SDValue Chain = Op.getOperand(0);
7585   SDValue SaveSP = Op.getOperand(1);
7586 
7587   // Load the old link SP.
7588   SDValue LoadLinkSP =
7589       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7590 
7591   // Restore the stack pointer.
7592   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7593 
7594   // Store the old link SP.
7595   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7596 }
7597 
7598 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7599   MachineFunction &MF = DAG.getMachineFunction();
7600   bool isPPC64 = Subtarget.isPPC64();
7601   EVT PtrVT = getPointerTy(MF.getDataLayout());
7602 
7603   // Get current frame pointer save index.  The users of this index will be
7604   // primarily DYNALLOC instructions.
7605   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7606   int RASI = FI->getReturnAddrSaveIndex();
7607 
7608   // If the frame pointer save index hasn't been defined yet.
7609   if (!RASI) {
7610     // Find out what the fix offset of the frame pointer save area.
7611     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7612     // Allocate the frame index for frame pointer save area.
7613     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7614     // Save the result.
7615     FI->setReturnAddrSaveIndex(RASI);
7616   }
7617   return DAG.getFrameIndex(RASI, PtrVT);
7618 }
7619 
7620 SDValue
7621 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7622   MachineFunction &MF = DAG.getMachineFunction();
7623   bool isPPC64 = Subtarget.isPPC64();
7624   EVT PtrVT = getPointerTy(MF.getDataLayout());
7625 
7626   // Get current frame pointer save index.  The users of this index will be
7627   // primarily DYNALLOC instructions.
7628   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7629   int FPSI = FI->getFramePointerSaveIndex();
7630 
7631   // If the frame pointer save index hasn't been defined yet.
7632   if (!FPSI) {
7633     // Find out what the fix offset of the frame pointer save area.
7634     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7635     // Allocate the frame index for frame pointer save area.
7636     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7637     // Save the result.
7638     FI->setFramePointerSaveIndex(FPSI);
7639   }
7640   return DAG.getFrameIndex(FPSI, PtrVT);
7641 }
7642 
7643 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7644                                                    SelectionDAG &DAG) const {
7645   MachineFunction &MF = DAG.getMachineFunction();
7646   // Get the inputs.
7647   SDValue Chain = Op.getOperand(0);
7648   SDValue Size  = Op.getOperand(1);
7649   SDLoc dl(Op);
7650 
7651   // Get the correct type for pointers.
7652   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7653   // Negate the size.
7654   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7655                                 DAG.getConstant(0, dl, PtrVT), Size);
7656   // Construct a node for the frame pointer save index.
7657   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7658   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7659   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7660   if (hasInlineStackProbe(MF))
7661     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7662   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7663 }
7664 
7665 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7666                                                      SelectionDAG &DAG) const {
7667   MachineFunction &MF = DAG.getMachineFunction();
7668 
7669   bool isPPC64 = Subtarget.isPPC64();
7670   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7671 
7672   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7673   return DAG.getFrameIndex(FI, PtrVT);
7674 }
7675 
7676 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7677                                                SelectionDAG &DAG) const {
7678   SDLoc DL(Op);
7679   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7680                      DAG.getVTList(MVT::i32, MVT::Other),
7681                      Op.getOperand(0), Op.getOperand(1));
7682 }
7683 
7684 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7685                                                 SelectionDAG &DAG) const {
7686   SDLoc DL(Op);
7687   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7688                      Op.getOperand(0), Op.getOperand(1));
7689 }
7690 
7691 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7692 
7693   assert(Op.getValueType() == MVT::i1 &&
7694          "Custom lowering only for i1 loads");
7695 
7696   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7697 
7698   SDLoc dl(Op);
7699   LoadSDNode *LD = cast<LoadSDNode>(Op);
7700 
7701   SDValue Chain = LD->getChain();
7702   SDValue BasePtr = LD->getBasePtr();
7703   MachineMemOperand *MMO = LD->getMemOperand();
7704 
7705   SDValue NewLD =
7706       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7707                      BasePtr, MVT::i8, MMO);
7708   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7709 
7710   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7711   return DAG.getMergeValues(Ops, dl);
7712 }
7713 
7714 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7715   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7716          "Custom lowering only for i1 stores");
7717 
7718   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7719 
7720   SDLoc dl(Op);
7721   StoreSDNode *ST = cast<StoreSDNode>(Op);
7722 
7723   SDValue Chain = ST->getChain();
7724   SDValue BasePtr = ST->getBasePtr();
7725   SDValue Value = ST->getValue();
7726   MachineMemOperand *MMO = ST->getMemOperand();
7727 
7728   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7729                       Value);
7730   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7731 }
7732 
7733 // FIXME: Remove this once the ANDI glue bug is fixed:
7734 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7735   assert(Op.getValueType() == MVT::i1 &&
7736          "Custom lowering only for i1 results");
7737 
7738   SDLoc DL(Op);
7739   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7740 }
7741 
7742 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7743                                                SelectionDAG &DAG) const {
7744 
7745   // Implements a vector truncate that fits in a vector register as a shuffle.
7746   // We want to legalize vector truncates down to where the source fits in
7747   // a vector register (and target is therefore smaller than vector register
7748   // size).  At that point legalization will try to custom lower the sub-legal
7749   // result and get here - where we can contain the truncate as a single target
7750   // operation.
7751 
7752   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7753   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7754   //
7755   // We will implement it for big-endian ordering as this (where x denotes
7756   // undefined):
7757   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7758   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7759   //
7760   // The same operation in little-endian ordering will be:
7761   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7762   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7763 
7764   assert(Op.getValueType().isVector() && "Vector type expected.");
7765 
7766   SDLoc DL(Op);
7767   SDValue N1 = Op.getOperand(0);
7768   unsigned SrcSize = N1.getValueType().getSizeInBits();
7769   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7770   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7771 
7772   EVT TrgVT = Op.getValueType();
7773   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7774   EVT EltVT = TrgVT.getVectorElementType();
7775   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7776   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7777 
7778   // First list the elements we want to keep.
7779   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7780   SmallVector<int, 16> ShuffV;
7781   if (Subtarget.isLittleEndian())
7782     for (unsigned i = 0; i < TrgNumElts; ++i)
7783       ShuffV.push_back(i * SizeMult);
7784   else
7785     for (unsigned i = 1; i <= TrgNumElts; ++i)
7786       ShuffV.push_back(i * SizeMult - 1);
7787 
7788   // Populate the remaining elements with undefs.
7789   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7790     // ShuffV.push_back(i + WideNumElts);
7791     ShuffV.push_back(WideNumElts + 1);
7792 
7793   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7794   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7795 }
7796 
7797 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7798 /// possible.
7799 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7800   // Not FP, or using SPE? Not a fsel.
7801   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7802       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
7803     return Op;
7804 
7805   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7806 
7807   EVT ResVT = Op.getValueType();
7808   EVT CmpVT = Op.getOperand(0).getValueType();
7809   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7810   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7811   SDLoc dl(Op);
7812   SDNodeFlags Flags = Op.getNode()->getFlags();
7813 
7814   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7815   // presence of infinities.
7816   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7817     switch (CC) {
7818     default:
7819       break;
7820     case ISD::SETOGT:
7821     case ISD::SETGT:
7822       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7823     case ISD::SETOLT:
7824     case ISD::SETLT:
7825       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7826     }
7827   }
7828 
7829   // We might be able to do better than this under some circumstances, but in
7830   // general, fsel-based lowering of select is a finite-math-only optimization.
7831   // For more information, see section F.3 of the 2.06 ISA specification.
7832   // With ISA 3.0
7833   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7834       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7835     return Op;
7836 
7837   // If the RHS of the comparison is a 0.0, we don't need to do the
7838   // subtraction at all.
7839   SDValue Sel1;
7840   if (isFloatingPointZero(RHS))
7841     switch (CC) {
7842     default: break;       // SETUO etc aren't handled by fsel.
7843     case ISD::SETNE:
7844       std::swap(TV, FV);
7845       LLVM_FALLTHROUGH;
7846     case ISD::SETEQ:
7847       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7848         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7849       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7850       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7851         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7852       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7853                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7854     case ISD::SETULT:
7855     case ISD::SETLT:
7856       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7857       LLVM_FALLTHROUGH;
7858     case ISD::SETOGE:
7859     case ISD::SETGE:
7860       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7861         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7862       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7863     case ISD::SETUGT:
7864     case ISD::SETGT:
7865       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7866       LLVM_FALLTHROUGH;
7867     case ISD::SETOLE:
7868     case ISD::SETLE:
7869       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7870         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7871       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7872                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7873     }
7874 
7875   SDValue Cmp;
7876   switch (CC) {
7877   default: break;       // SETUO etc aren't handled by fsel.
7878   case ISD::SETNE:
7879     std::swap(TV, FV);
7880     LLVM_FALLTHROUGH;
7881   case ISD::SETEQ:
7882     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7883     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7884       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7885     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7886     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7887       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7888     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7889                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7890   case ISD::SETULT:
7891   case ISD::SETLT:
7892     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7893     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7894       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7895     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7896   case ISD::SETOGE:
7897   case ISD::SETGE:
7898     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7899     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7900       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7901     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7902   case ISD::SETUGT:
7903   case ISD::SETGT:
7904     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7905     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7906       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7907     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7908   case ISD::SETOLE:
7909   case ISD::SETLE:
7910     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7911     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7912       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7913     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7914   }
7915   return Op;
7916 }
7917 
7918 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7919                               const PPCSubtarget &Subtarget) {
7920   SDLoc dl(Op);
7921   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
7922   SDValue Src = Op.getOperand(0);
7923   assert(Src.getValueType().isFloatingPoint());
7924   if (Src.getValueType() == MVT::f32)
7925     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7926   SDValue Conv;
7927   switch (Op.getSimpleValueType().SimpleTy) {
7928   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7929   case MVT::i32:
7930     Conv = DAG.getNode(
7931         IsSigned ? PPCISD::FCTIWZ
7932                  : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7933         dl, MVT::f64, Src);
7934     break;
7935   case MVT::i64:
7936     assert((IsSigned || Subtarget.hasFPCVT()) &&
7937            "i64 FP_TO_UINT is supported only with FPCVT");
7938     Conv = DAG.getNode(IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ, dl,
7939                        MVT::f64, Src);
7940   }
7941   return Conv;
7942 }
7943 
7944 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7945                                                SelectionDAG &DAG,
7946                                                const SDLoc &dl) const {
7947   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
7948   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
7949 
7950   // Convert the FP value to an int value through memory.
7951   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7952                   (IsSigned || Subtarget.hasFPCVT());
7953   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7954   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7955   MachinePointerInfo MPI =
7956       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7957 
7958   // Emit a store to the stack slot.
7959   SDValue Chain;
7960   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
7961   if (i32Stack) {
7962     MachineFunction &MF = DAG.getMachineFunction();
7963     Alignment = Align(4);
7964     MachineMemOperand *MMO =
7965         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
7966     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7967     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7968               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7969   } else
7970     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
7971 
7972   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7973   // add in a bias on big endian.
7974   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7975     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7976                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7977     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7978   }
7979 
7980   RLI.Chain = Chain;
7981   RLI.Ptr = FIPtr;
7982   RLI.MPI = MPI;
7983   RLI.Alignment = Alignment;
7984 }
7985 
7986 /// Custom lowers floating point to integer conversions to use
7987 /// the direct move instructions available in ISA 2.07 to avoid the
7988 /// need for load/store combinations.
7989 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7990                                                     SelectionDAG &DAG,
7991                                                     const SDLoc &dl) const {
7992   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7993   return DAG.getNode(PPCISD::MFVSR, dl, Op.getSimpleValueType().SimpleTy,
7994                      convertFPToInt(Op, DAG, Subtarget));
7995 }
7996 
7997 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7998                                           const SDLoc &dl) const {
7999   SDValue Src = Op.getOperand(0);
8000   // FP to INT conversions are legal for f128.
8001   if (Src.getValueType() == MVT::f128)
8002     return Op;
8003 
8004   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8005   // PPC (the libcall is not available).
8006   if (Src.getValueType() == MVT::ppcf128) {
8007     if (Op.getValueType() == MVT::i32) {
8008       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8009         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8010                                  DAG.getIntPtrConstant(0, dl));
8011         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8012                                  DAG.getIntPtrConstant(1, dl));
8013 
8014         // Add the two halves of the long double in round-to-zero mode.
8015         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8016 
8017         // Now use a smaller FP_TO_SINT.
8018         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8019       }
8020       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8021         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8022         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8023         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8024         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8025         // FIXME: generated code sucks.
8026         // TODO: Are there fast-math-flags to propagate to this FSUB?
8027         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Tmp);
8028         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8029         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8030                            DAG.getConstant(0x80000000, dl, MVT::i32));
8031         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8032         return DAG.getSelectCC(dl, Src, Tmp, True, False, ISD::SETGE);
8033       }
8034     }
8035 
8036     return SDValue();
8037   }
8038 
8039   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8040     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8041 
8042   ReuseLoadInfo RLI;
8043   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8044 
8045   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8046                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8047 }
8048 
8049 // We're trying to insert a regular store, S, and then a load, L. If the
8050 // incoming value, O, is a load, we might just be able to have our load use the
8051 // address used by O. However, we don't know if anything else will store to
8052 // that address before we can load from it. To prevent this situation, we need
8053 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8054 // the same chain operand as O, we create a token factor from the chain results
8055 // of O and L, and we replace all uses of O's chain result with that token
8056 // factor (see spliceIntoChain below for this last part).
8057 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8058                                             ReuseLoadInfo &RLI,
8059                                             SelectionDAG &DAG,
8060                                             ISD::LoadExtType ET) const {
8061   SDLoc dl(Op);
8062   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8063                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8064   if (ET == ISD::NON_EXTLOAD &&
8065       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8066       isOperationLegalOrCustom(Op.getOpcode(),
8067                                Op.getOperand(0).getValueType())) {
8068 
8069     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8070     return true;
8071   }
8072 
8073   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8074   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8075       LD->isNonTemporal())
8076     return false;
8077   if (LD->getMemoryVT() != MemVT)
8078     return false;
8079 
8080   RLI.Ptr = LD->getBasePtr();
8081   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8082     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8083            "Non-pre-inc AM on PPC?");
8084     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8085                           LD->getOffset());
8086   }
8087 
8088   RLI.Chain = LD->getChain();
8089   RLI.MPI = LD->getPointerInfo();
8090   RLI.IsDereferenceable = LD->isDereferenceable();
8091   RLI.IsInvariant = LD->isInvariant();
8092   RLI.Alignment = LD->getAlign();
8093   RLI.AAInfo = LD->getAAInfo();
8094   RLI.Ranges = LD->getRanges();
8095 
8096   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8097   return true;
8098 }
8099 
8100 // Given the head of the old chain, ResChain, insert a token factor containing
8101 // it and NewResChain, and make users of ResChain now be users of that token
8102 // factor.
8103 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8104 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8105                                         SDValue NewResChain,
8106                                         SelectionDAG &DAG) const {
8107   if (!ResChain)
8108     return;
8109 
8110   SDLoc dl(NewResChain);
8111 
8112   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8113                            NewResChain, DAG.getUNDEF(MVT::Other));
8114   assert(TF.getNode() != NewResChain.getNode() &&
8115          "A new TF really is required here");
8116 
8117   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8118   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8119 }
8120 
8121 /// Analyze profitability of direct move
8122 /// prefer float load to int load plus direct move
8123 /// when there is no integer use of int load
8124 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8125   SDNode *Origin = Op.getOperand(0).getNode();
8126   if (Origin->getOpcode() != ISD::LOAD)
8127     return true;
8128 
8129   // If there is no LXSIBZX/LXSIHZX, like Power8,
8130   // prefer direct move if the memory size is 1 or 2 bytes.
8131   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8132   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8133     return true;
8134 
8135   for (SDNode::use_iterator UI = Origin->use_begin(),
8136                             UE = Origin->use_end();
8137        UI != UE; ++UI) {
8138 
8139     // Only look at the users of the loaded value.
8140     if (UI.getUse().get().getResNo() != 0)
8141       continue;
8142 
8143     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8144         UI->getOpcode() != ISD::UINT_TO_FP)
8145       return true;
8146   }
8147 
8148   return false;
8149 }
8150 
8151 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8152                               const PPCSubtarget &Subtarget) {
8153   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
8154   SDLoc dl(Op);
8155   // If we have FCFIDS, then use it when converting to single-precision.
8156   // Otherwise, convert to double-precision and then round.
8157   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8158   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8159                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8160   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8161   return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8162 }
8163 
8164 /// Custom lowers integer to floating point conversions to use
8165 /// the direct move instructions available in ISA 2.07 to avoid the
8166 /// need for load/store combinations.
8167 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8168                                                     SelectionDAG &DAG,
8169                                                     const SDLoc &dl) const {
8170   assert((Op.getValueType() == MVT::f32 ||
8171           Op.getValueType() == MVT::f64) &&
8172          "Invalid floating point type as target of conversion");
8173   assert(Subtarget.hasFPCVT() &&
8174          "Int to FP conversions with direct moves require FPCVT");
8175   SDValue Src = Op.getOperand(0);
8176   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8177   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8178   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8179   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8180   return convertIntToFP(Op, Mov, DAG, Subtarget);
8181 }
8182 
8183 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8184 
8185   EVT VecVT = Vec.getValueType();
8186   assert(VecVT.isVector() && "Expected a vector type.");
8187   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8188 
8189   EVT EltVT = VecVT.getVectorElementType();
8190   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8191   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8192 
8193   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8194   SmallVector<SDValue, 16> Ops(NumConcat);
8195   Ops[0] = Vec;
8196   SDValue UndefVec = DAG.getUNDEF(VecVT);
8197   for (unsigned i = 1; i < NumConcat; ++i)
8198     Ops[i] = UndefVec;
8199 
8200   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8201 }
8202 
8203 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8204                                                 const SDLoc &dl) const {
8205 
8206   unsigned Opc = Op.getOpcode();
8207   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8208          "Unexpected conversion type");
8209   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8210          "Supports conversions to v2f64/v4f32 only.");
8211 
8212   bool SignedConv = Opc == ISD::SINT_TO_FP;
8213   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8214 
8215   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8216   EVT WideVT = Wide.getValueType();
8217   unsigned WideNumElts = WideVT.getVectorNumElements();
8218   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8219 
8220   SmallVector<int, 16> ShuffV;
8221   for (unsigned i = 0; i < WideNumElts; ++i)
8222     ShuffV.push_back(i + WideNumElts);
8223 
8224   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8225   int SaveElts = FourEltRes ? 4 : 2;
8226   if (Subtarget.isLittleEndian())
8227     for (int i = 0; i < SaveElts; i++)
8228       ShuffV[i * Stride] = i;
8229   else
8230     for (int i = 1; i <= SaveElts; i++)
8231       ShuffV[i * Stride - 1] = i - 1;
8232 
8233   SDValue ShuffleSrc2 =
8234       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8235   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8236 
8237   SDValue Extend;
8238   if (SignedConv) {
8239     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8240     EVT ExtVT = Op.getOperand(0).getValueType();
8241     if (Subtarget.hasP9Altivec())
8242       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8243                                IntermediateVT.getVectorNumElements());
8244 
8245     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8246                          DAG.getValueType(ExtVT));
8247   } else
8248     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8249 
8250   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8251 }
8252 
8253 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8254                                           SelectionDAG &DAG) const {
8255   SDLoc dl(Op);
8256   SDValue Src = Op.getOperand(0);
8257   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
8258 
8259   EVT InVT = Src.getValueType();
8260   EVT OutVT = Op.getValueType();
8261   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8262       isOperationCustom(Op.getOpcode(), InVT))
8263     return LowerINT_TO_FPVector(Op, DAG, dl);
8264 
8265   // Conversions to f128 are legal.
8266   if (Op.getValueType() == MVT::f128)
8267     return Op;
8268 
8269   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8270   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8271     return SDValue();
8272 
8273   if (Src.getValueType() == MVT::i1)
8274     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8275                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8276                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8277 
8278   // If we have direct moves, we can do all the conversion, skip the store/load
8279   // however, without FPCVT we can't do most conversions.
8280   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8281       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8282     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8283 
8284   assert((IsSigned || Subtarget.hasFPCVT()) &&
8285          "UINT_TO_FP is supported only with FPCVT");
8286 
8287   if (Src.getValueType() == MVT::i64) {
8288     SDValue SINT = Src;
8289     // When converting to single-precision, we actually need to convert
8290     // to double-precision first and then round to single-precision.
8291     // To avoid double-rounding effects during that operation, we have
8292     // to prepare the input operand.  Bits that might be truncated when
8293     // converting to double-precision are replaced by a bit that won't
8294     // be lost at this stage, but is below the single-precision rounding
8295     // position.
8296     //
8297     // However, if -enable-unsafe-fp-math is in effect, accept double
8298     // rounding to avoid the extra overhead.
8299     if (Op.getValueType() == MVT::f32 &&
8300         !Subtarget.hasFPCVT() &&
8301         !DAG.getTarget().Options.UnsafeFPMath) {
8302 
8303       // Twiddle input to make sure the low 11 bits are zero.  (If this
8304       // is the case, we are guaranteed the value will fit into the 53 bit
8305       // mantissa of an IEEE double-precision value without rounding.)
8306       // If any of those low 11 bits were not zero originally, make sure
8307       // bit 12 (value 2048) is set instead, so that the final rounding
8308       // to single-precision gets the correct result.
8309       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8310                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8311       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8312                           Round, DAG.getConstant(2047, dl, MVT::i64));
8313       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8314       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8315                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8316 
8317       // However, we cannot use that value unconditionally: if the magnitude
8318       // of the input value is small, the bit-twiddling we did above might
8319       // end up visibly changing the output.  Fortunately, in that case, we
8320       // don't need to twiddle bits since the original input will convert
8321       // exactly to double-precision floating-point already.  Therefore,
8322       // construct a conditional to use the original value if the top 11
8323       // bits are all sign-bit copies, and use the rounded value computed
8324       // above otherwise.
8325       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8326                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8327       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8328                          Cond, DAG.getConstant(1, dl, MVT::i64));
8329       Cond = DAG.getSetCC(
8330           dl,
8331           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8332           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8333 
8334       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8335     }
8336 
8337     ReuseLoadInfo RLI;
8338     SDValue Bits;
8339 
8340     MachineFunction &MF = DAG.getMachineFunction();
8341     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8342       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8343                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8344       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8345     } else if (Subtarget.hasLFIWAX() &&
8346                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8347       MachineMemOperand *MMO =
8348         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8349                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8350       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8351       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8352                                      DAG.getVTList(MVT::f64, MVT::Other),
8353                                      Ops, MVT::i32, MMO);
8354       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8355     } else if (Subtarget.hasFPCVT() &&
8356                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8357       MachineMemOperand *MMO =
8358         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8359                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8360       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8361       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8362                                      DAG.getVTList(MVT::f64, MVT::Other),
8363                                      Ops, MVT::i32, MMO);
8364       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8365     } else if (((Subtarget.hasLFIWAX() &&
8366                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8367                 (Subtarget.hasFPCVT() &&
8368                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8369                SINT.getOperand(0).getValueType() == MVT::i32) {
8370       MachineFrameInfo &MFI = MF.getFrameInfo();
8371       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8372 
8373       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8374       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8375 
8376       SDValue Store =
8377           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8378                        MachinePointerInfo::getFixedStack(
8379                            DAG.getMachineFunction(), FrameIdx));
8380 
8381       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8382              "Expected an i32 store");
8383 
8384       RLI.Ptr = FIdx;
8385       RLI.Chain = Store;
8386       RLI.MPI =
8387           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8388       RLI.Alignment = Align(4);
8389 
8390       MachineMemOperand *MMO =
8391         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8392                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8393       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8394       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8395                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8396                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8397                                      Ops, MVT::i32, MMO);
8398     } else
8399       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8400 
8401     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget);
8402 
8403     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8404       FP = DAG.getNode(ISD::FP_ROUND, dl,
8405                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8406     return FP;
8407   }
8408 
8409   assert(Src.getValueType() == MVT::i32 &&
8410          "Unhandled INT_TO_FP type in custom expander!");
8411   // Since we only generate this in 64-bit mode, we can take advantage of
8412   // 64-bit registers.  In particular, sign extend the input value into the
8413   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8414   // then lfd it and fcfid it.
8415   MachineFunction &MF = DAG.getMachineFunction();
8416   MachineFrameInfo &MFI = MF.getFrameInfo();
8417   EVT PtrVT = getPointerTy(MF.getDataLayout());
8418 
8419   SDValue Ld;
8420   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8421     ReuseLoadInfo RLI;
8422     bool ReusingLoad;
8423     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8424       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8425       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8426 
8427       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Src, FIdx,
8428                                    MachinePointerInfo::getFixedStack(
8429                                        DAG.getMachineFunction(), FrameIdx));
8430 
8431       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8432              "Expected an i32 store");
8433 
8434       RLI.Ptr = FIdx;
8435       RLI.Chain = Store;
8436       RLI.MPI =
8437           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8438       RLI.Alignment = Align(4);
8439     }
8440 
8441     MachineMemOperand *MMO =
8442       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8443                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8444     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8445     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8446                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8447                                  MVT::i32, MMO);
8448     if (ReusingLoad)
8449       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8450   } else {
8451     assert(Subtarget.isPPC64() &&
8452            "i32->FP without LFIWAX supported only on PPC64");
8453 
8454     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8455     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8456 
8457     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8458 
8459     // STD the extended value into the stack slot.
8460     SDValue Store = DAG.getStore(
8461         DAG.getEntryNode(), dl, Ext64, FIdx,
8462         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8463 
8464     // Load the value as a double.
8465     Ld = DAG.getLoad(
8466         MVT::f64, dl, Store, FIdx,
8467         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8468   }
8469 
8470   // FCFID it and return it.
8471   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget);
8472   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8473     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8474                      DAG.getIntPtrConstant(0, dl));
8475   return FP;
8476 }
8477 
8478 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8479                                             SelectionDAG &DAG) const {
8480   SDLoc dl(Op);
8481   /*
8482    The rounding mode is in bits 30:31 of FPSR, and has the following
8483    settings:
8484      00 Round to nearest
8485      01 Round to 0
8486      10 Round to +inf
8487      11 Round to -inf
8488 
8489   FLT_ROUNDS, on the other hand, expects the following:
8490     -1 Undefined
8491      0 Round to 0
8492      1 Round to nearest
8493      2 Round to +inf
8494      3 Round to -inf
8495 
8496   To perform the conversion, we do:
8497     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8498   */
8499 
8500   MachineFunction &MF = DAG.getMachineFunction();
8501   EVT VT = Op.getValueType();
8502   EVT PtrVT = getPointerTy(MF.getDataLayout());
8503 
8504   // Save FP Control Word to register
8505   SDValue Chain = Op.getOperand(0);
8506   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8507   Chain = MFFS.getValue(1);
8508 
8509   // Save FP register to stack slot
8510   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8511   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8512   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8513 
8514   // Load FP Control Word from low 32 bits of stack slot.
8515   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8516   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8517   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8518   Chain = CWD.getValue(1);
8519 
8520   // Transform as necessary
8521   SDValue CWD1 =
8522     DAG.getNode(ISD::AND, dl, MVT::i32,
8523                 CWD, DAG.getConstant(3, dl, MVT::i32));
8524   SDValue CWD2 =
8525     DAG.getNode(ISD::SRL, dl, MVT::i32,
8526                 DAG.getNode(ISD::AND, dl, MVT::i32,
8527                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8528                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8529                             DAG.getConstant(3, dl, MVT::i32)),
8530                 DAG.getConstant(1, dl, MVT::i32));
8531 
8532   SDValue RetVal =
8533     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8534 
8535   RetVal =
8536       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8537                   dl, VT, RetVal);
8538 
8539   return DAG.getMergeValues({RetVal, Chain}, dl);
8540 }
8541 
8542 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8543   EVT VT = Op.getValueType();
8544   unsigned BitWidth = VT.getSizeInBits();
8545   SDLoc dl(Op);
8546   assert(Op.getNumOperands() == 3 &&
8547          VT == Op.getOperand(1).getValueType() &&
8548          "Unexpected SHL!");
8549 
8550   // Expand into a bunch of logical ops.  Note that these ops
8551   // depend on the PPC behavior for oversized shift amounts.
8552   SDValue Lo = Op.getOperand(0);
8553   SDValue Hi = Op.getOperand(1);
8554   SDValue Amt = Op.getOperand(2);
8555   EVT AmtVT = Amt.getValueType();
8556 
8557   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8558                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8559   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8560   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8561   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8562   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8563                              DAG.getConstant(-BitWidth, dl, AmtVT));
8564   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8565   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8566   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8567   SDValue OutOps[] = { OutLo, OutHi };
8568   return DAG.getMergeValues(OutOps, dl);
8569 }
8570 
8571 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8572   EVT VT = Op.getValueType();
8573   SDLoc dl(Op);
8574   unsigned BitWidth = VT.getSizeInBits();
8575   assert(Op.getNumOperands() == 3 &&
8576          VT == Op.getOperand(1).getValueType() &&
8577          "Unexpected SRL!");
8578 
8579   // Expand into a bunch of logical ops.  Note that these ops
8580   // depend on the PPC behavior for oversized shift amounts.
8581   SDValue Lo = Op.getOperand(0);
8582   SDValue Hi = Op.getOperand(1);
8583   SDValue Amt = Op.getOperand(2);
8584   EVT AmtVT = Amt.getValueType();
8585 
8586   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8587                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8588   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8589   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8590   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8591   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8592                              DAG.getConstant(-BitWidth, dl, AmtVT));
8593   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8594   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8595   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8596   SDValue OutOps[] = { OutLo, OutHi };
8597   return DAG.getMergeValues(OutOps, dl);
8598 }
8599 
8600 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8601   SDLoc dl(Op);
8602   EVT VT = Op.getValueType();
8603   unsigned BitWidth = VT.getSizeInBits();
8604   assert(Op.getNumOperands() == 3 &&
8605          VT == Op.getOperand(1).getValueType() &&
8606          "Unexpected SRA!");
8607 
8608   // Expand into a bunch of logical ops, followed by a select_cc.
8609   SDValue Lo = Op.getOperand(0);
8610   SDValue Hi = Op.getOperand(1);
8611   SDValue Amt = Op.getOperand(2);
8612   EVT AmtVT = Amt.getValueType();
8613 
8614   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8615                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8616   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8617   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8618   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8619   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8620                              DAG.getConstant(-BitWidth, dl, AmtVT));
8621   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8622   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8623   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8624                                   Tmp4, Tmp6, ISD::SETLE);
8625   SDValue OutOps[] = { OutLo, OutHi };
8626   return DAG.getMergeValues(OutOps, dl);
8627 }
8628 
8629 //===----------------------------------------------------------------------===//
8630 // Vector related lowering.
8631 //
8632 
8633 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8634 /// element size of SplatSize. Cast the result to VT.
8635 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8636                                       SelectionDAG &DAG, const SDLoc &dl) {
8637   static const MVT VTys[] = { // canonical VT to use for each size.
8638     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8639   };
8640 
8641   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8642 
8643   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8644   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
8645     SplatSize = 1;
8646     Val = 0xFF;
8647   }
8648 
8649   EVT CanonicalVT = VTys[SplatSize-1];
8650 
8651   // Build a canonical splat for this value.
8652   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8653 }
8654 
8655 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8656 /// specified intrinsic ID.
8657 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8658                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8659   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8660   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8661                      DAG.getConstant(IID, dl, MVT::i32), Op);
8662 }
8663 
8664 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8665 /// specified intrinsic ID.
8666 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8667                                 SelectionDAG &DAG, const SDLoc &dl,
8668                                 EVT DestVT = MVT::Other) {
8669   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8670   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8671                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8672 }
8673 
8674 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8675 /// specified intrinsic ID.
8676 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8677                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8678                                 EVT DestVT = MVT::Other) {
8679   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8680   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8681                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8682 }
8683 
8684 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8685 /// amount.  The result has the specified value type.
8686 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8687                            SelectionDAG &DAG, const SDLoc &dl) {
8688   // Force LHS/RHS to be the right type.
8689   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8690   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8691 
8692   int Ops[16];
8693   for (unsigned i = 0; i != 16; ++i)
8694     Ops[i] = i + Amt;
8695   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8696   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8697 }
8698 
8699 /// Do we have an efficient pattern in a .td file for this node?
8700 ///
8701 /// \param V - pointer to the BuildVectorSDNode being matched
8702 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8703 ///
8704 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8705 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8706 /// the opposite is true (expansion is beneficial) are:
8707 /// - The node builds a vector out of integers that are not 32 or 64-bits
8708 /// - The node builds a vector out of constants
8709 /// - The node is a "load-and-splat"
8710 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8711 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8712                                             bool HasDirectMove,
8713                                             bool HasP8Vector) {
8714   EVT VecVT = V->getValueType(0);
8715   bool RightType = VecVT == MVT::v2f64 ||
8716     (HasP8Vector && VecVT == MVT::v4f32) ||
8717     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8718   if (!RightType)
8719     return false;
8720 
8721   bool IsSplat = true;
8722   bool IsLoad = false;
8723   SDValue Op0 = V->getOperand(0);
8724 
8725   // This function is called in a block that confirms the node is not a constant
8726   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8727   // different constants.
8728   if (V->isConstant())
8729     return false;
8730   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8731     if (V->getOperand(i).isUndef())
8732       return false;
8733     // We want to expand nodes that represent load-and-splat even if the
8734     // loaded value is a floating point truncation or conversion to int.
8735     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8736         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8737          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8738         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8739          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8740         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8741          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8742       IsLoad = true;
8743     // If the operands are different or the input is not a load and has more
8744     // uses than just this BV node, then it isn't a splat.
8745     if (V->getOperand(i) != Op0 ||
8746         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8747       IsSplat = false;
8748   }
8749   return !(IsSplat && IsLoad);
8750 }
8751 
8752 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8753 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8754 
8755   SDLoc dl(Op);
8756   SDValue Op0 = Op->getOperand(0);
8757 
8758   if ((Op.getValueType() != MVT::f128) ||
8759       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8760       (Op0.getOperand(0).getValueType() != MVT::i64) ||
8761       (Op0.getOperand(1).getValueType() != MVT::i64))
8762     return SDValue();
8763 
8764   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8765                      Op0.getOperand(1));
8766 }
8767 
8768 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
8769   const SDValue *InputLoad = &Op;
8770   if (InputLoad->getOpcode() == ISD::BITCAST)
8771     InputLoad = &InputLoad->getOperand(0);
8772   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
8773       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
8774     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
8775     InputLoad = &InputLoad->getOperand(0);
8776   }
8777   if (InputLoad->getOpcode() != ISD::LOAD)
8778     return nullptr;
8779   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8780   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8781 }
8782 
8783 // Convert the argument APFloat to a single precision APFloat if there is no
8784 // loss in information during the conversion to single precision APFloat and the
8785 // resulting number is not a denormal number. Return true if successful.
8786 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
8787   APFloat APFloatToConvert = ArgAPFloat;
8788   bool LosesInfo = true;
8789   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
8790                            &LosesInfo);
8791   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
8792   if (Success)
8793     ArgAPFloat = APFloatToConvert;
8794   return Success;
8795 }
8796 
8797 // Bitcast the argument APInt to a double and convert it to a single precision
8798 // APFloat, bitcast the APFloat to an APInt and assign it to the original
8799 // argument if there is no loss in information during the conversion from
8800 // double to single precision APFloat and the resulting number is not a denormal
8801 // number. Return true if successful.
8802 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
8803   double DpValue = ArgAPInt.bitsToDouble();
8804   APFloat APFloatDp(DpValue);
8805   bool Success = convertToNonDenormSingle(APFloatDp);
8806   if (Success)
8807     ArgAPInt = APFloatDp.bitcastToAPInt();
8808   return Success;
8809 }
8810 
8811 // If this is a case we can't handle, return null and let the default
8812 // expansion code take care of it.  If we CAN select this case, and if it
8813 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8814 // this case more efficiently than a constant pool load, lower it to the
8815 // sequence of ops that should be used.
8816 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8817                                              SelectionDAG &DAG) const {
8818   SDLoc dl(Op);
8819   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8820   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8821 
8822   // Check if this is a splat of a constant value.
8823   APInt APSplatBits, APSplatUndef;
8824   unsigned SplatBitSize;
8825   bool HasAnyUndefs;
8826   bool BVNIsConstantSplat =
8827       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8828                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
8829 
8830   // If it is a splat of a double, check if we can shrink it to a 32 bit
8831   // non-denormal float which when converted back to double gives us the same
8832   // double. This is to exploit the XXSPLTIDP instruction.
8833   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
8834       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
8835       convertToNonDenormSingle(APSplatBits)) {
8836     SDValue SplatNode = DAG.getNode(
8837         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
8838         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
8839     return DAG.getBitcast(Op.getValueType(), SplatNode);
8840   }
8841 
8842   if (!BVNIsConstantSplat || SplatBitSize > 32) {
8843 
8844     bool IsPermutedLoad = false;
8845     const SDValue *InputLoad =
8846         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
8847     // Handle load-and-splat patterns as we have instructions that will do this
8848     // in one go.
8849     if (InputLoad && DAG.isSplatValue(Op, true)) {
8850       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8851 
8852       // We have handling for 4 and 8 byte elements.
8853       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8854 
8855       // Checking for a single use of this load, we have to check for vector
8856       // width (128 bits) / ElementSize uses (since each operand of the
8857       // BUILD_VECTOR is a separate use of the value.
8858       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8859           ((Subtarget.hasVSX() && ElementSize == 64) ||
8860            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8861         SDValue Ops[] = {
8862           LD->getChain(),    // Chain
8863           LD->getBasePtr(),  // Ptr
8864           DAG.getValueType(Op.getValueType()) // VT
8865         };
8866         return
8867           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8868                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8869                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8870       }
8871     }
8872 
8873     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8874     // lowered to VSX instructions under certain conditions.
8875     // Without VSX, there is no pattern more efficient than expanding the node.
8876     if (Subtarget.hasVSX() &&
8877         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8878                                         Subtarget.hasP8Vector()))
8879       return Op;
8880     return SDValue();
8881   }
8882 
8883   uint64_t SplatBits = APSplatBits.getZExtValue();
8884   uint64_t SplatUndef = APSplatUndef.getZExtValue();
8885   unsigned SplatSize = SplatBitSize / 8;
8886 
8887   // First, handle single instruction cases.
8888 
8889   // All zeros?
8890   if (SplatBits == 0) {
8891     // Canonicalize all zero vectors to be v4i32.
8892     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8893       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8894       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8895     }
8896     return Op;
8897   }
8898 
8899   // We have XXSPLTIW for constant splats four bytes wide.
8900   // Given vector length is a multiple of 4, 2-byte splats can be replaced
8901   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
8902   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
8903   // turned into a 4-byte splat of 0xABABABAB.
8904   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
8905     return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2,
8906                                   Op.getValueType(), DAG, dl);
8907 
8908   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
8909     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
8910                                   dl);
8911 
8912   // We have XXSPLTIB for constant splats one byte wide.
8913   if (Subtarget.hasP9Vector() && SplatSize == 1)
8914     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
8915                                   dl);
8916 
8917   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8918   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8919                     (32-SplatBitSize));
8920   if (SextVal >= -16 && SextVal <= 15)
8921     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
8922                                   dl);
8923 
8924   // Two instruction sequences.
8925 
8926   // If this value is in the range [-32,30] and is even, use:
8927   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8928   // If this value is in the range [17,31] and is odd, use:
8929   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8930   // If this value is in the range [-31,-17] and is odd, use:
8931   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8932   // Note the last two are three-instruction sequences.
8933   if (SextVal >= -32 && SextVal <= 31) {
8934     // To avoid having these optimizations undone by constant folding,
8935     // we convert to a pseudo that will be expanded later into one of
8936     // the above forms.
8937     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8938     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8939               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8940     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8941     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8942     if (VT == Op.getValueType())
8943       return RetVal;
8944     else
8945       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8946   }
8947 
8948   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8949   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8950   // for fneg/fabs.
8951   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8952     // Make -1 and vspltisw -1:
8953     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
8954 
8955     // Make the VSLW intrinsic, computing 0x8000_0000.
8956     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8957                                    OnesV, DAG, dl);
8958 
8959     // xor by OnesV to invert it.
8960     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8961     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8962   }
8963 
8964   // Check to see if this is a wide variety of vsplti*, binop self cases.
8965   static const signed char SplatCsts[] = {
8966     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8967     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8968   };
8969 
8970   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8971     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8972     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8973     int i = SplatCsts[idx];
8974 
8975     // Figure out what shift amount will be used by altivec if shifted by i in
8976     // this splat size.
8977     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8978 
8979     // vsplti + shl self.
8980     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8981       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
8982       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8983         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8984         Intrinsic::ppc_altivec_vslw
8985       };
8986       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8987       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8988     }
8989 
8990     // vsplti + srl self.
8991     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8992       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
8993       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8994         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8995         Intrinsic::ppc_altivec_vsrw
8996       };
8997       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8998       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8999     }
9000 
9001     // vsplti + sra self.
9002     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9003       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9004       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9005         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9006         Intrinsic::ppc_altivec_vsraw
9007       };
9008       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9009       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9010     }
9011 
9012     // vsplti + rol self.
9013     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9014                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9015       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9016       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9017         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9018         Intrinsic::ppc_altivec_vrlw
9019       };
9020       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9021       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9022     }
9023 
9024     // t = vsplti c, result = vsldoi t, t, 1
9025     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9026       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9027       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9028       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9029     }
9030     // t = vsplti c, result = vsldoi t, t, 2
9031     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9032       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9033       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9034       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9035     }
9036     // t = vsplti c, result = vsldoi t, t, 3
9037     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9038       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9039       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9040       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9041     }
9042   }
9043 
9044   return SDValue();
9045 }
9046 
9047 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9048 /// the specified operations to build the shuffle.
9049 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9050                                       SDValue RHS, SelectionDAG &DAG,
9051                                       const SDLoc &dl) {
9052   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9053   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9054   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9055 
9056   enum {
9057     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9058     OP_VMRGHW,
9059     OP_VMRGLW,
9060     OP_VSPLTISW0,
9061     OP_VSPLTISW1,
9062     OP_VSPLTISW2,
9063     OP_VSPLTISW3,
9064     OP_VSLDOI4,
9065     OP_VSLDOI8,
9066     OP_VSLDOI12
9067   };
9068 
9069   if (OpNum == OP_COPY) {
9070     if (LHSID == (1*9+2)*9+3) return LHS;
9071     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9072     return RHS;
9073   }
9074 
9075   SDValue OpLHS, OpRHS;
9076   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9077   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9078 
9079   int ShufIdxs[16];
9080   switch (OpNum) {
9081   default: llvm_unreachable("Unknown i32 permute!");
9082   case OP_VMRGHW:
9083     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9084     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9085     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9086     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9087     break;
9088   case OP_VMRGLW:
9089     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9090     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9091     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9092     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9093     break;
9094   case OP_VSPLTISW0:
9095     for (unsigned i = 0; i != 16; ++i)
9096       ShufIdxs[i] = (i&3)+0;
9097     break;
9098   case OP_VSPLTISW1:
9099     for (unsigned i = 0; i != 16; ++i)
9100       ShufIdxs[i] = (i&3)+4;
9101     break;
9102   case OP_VSPLTISW2:
9103     for (unsigned i = 0; i != 16; ++i)
9104       ShufIdxs[i] = (i&3)+8;
9105     break;
9106   case OP_VSPLTISW3:
9107     for (unsigned i = 0; i != 16; ++i)
9108       ShufIdxs[i] = (i&3)+12;
9109     break;
9110   case OP_VSLDOI4:
9111     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9112   case OP_VSLDOI8:
9113     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9114   case OP_VSLDOI12:
9115     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9116   }
9117   EVT VT = OpLHS.getValueType();
9118   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9119   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9120   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9121   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9122 }
9123 
9124 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9125 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9126 /// SDValue.
9127 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9128                                            SelectionDAG &DAG) const {
9129   const unsigned BytesInVector = 16;
9130   bool IsLE = Subtarget.isLittleEndian();
9131   SDLoc dl(N);
9132   SDValue V1 = N->getOperand(0);
9133   SDValue V2 = N->getOperand(1);
9134   unsigned ShiftElts = 0, InsertAtByte = 0;
9135   bool Swap = false;
9136 
9137   // Shifts required to get the byte we want at element 7.
9138   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9139                                    0, 15, 14, 13, 12, 11, 10, 9};
9140   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9141                                 1, 2,  3,  4,  5,  6,  7,  8};
9142 
9143   ArrayRef<int> Mask = N->getMask();
9144   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9145 
9146   // For each mask element, find out if we're just inserting something
9147   // from V2 into V1 or vice versa.
9148   // Possible permutations inserting an element from V2 into V1:
9149   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9150   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9151   //   ...
9152   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9153   // Inserting from V1 into V2 will be similar, except mask range will be
9154   // [16,31].
9155 
9156   bool FoundCandidate = false;
9157   // If both vector operands for the shuffle are the same vector, the mask
9158   // will contain only elements from the first one and the second one will be
9159   // undef.
9160   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9161   // Go through the mask of half-words to find an element that's being moved
9162   // from one vector to the other.
9163   for (unsigned i = 0; i < BytesInVector; ++i) {
9164     unsigned CurrentElement = Mask[i];
9165     // If 2nd operand is undefined, we should only look for element 7 in the
9166     // Mask.
9167     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9168       continue;
9169 
9170     bool OtherElementsInOrder = true;
9171     // Examine the other elements in the Mask to see if they're in original
9172     // order.
9173     for (unsigned j = 0; j < BytesInVector; ++j) {
9174       if (j == i)
9175         continue;
9176       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9177       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9178       // in which we always assume we're always picking from the 1st operand.
9179       int MaskOffset =
9180           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9181       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9182         OtherElementsInOrder = false;
9183         break;
9184       }
9185     }
9186     // If other elements are in original order, we record the number of shifts
9187     // we need to get the element we want into element 7. Also record which byte
9188     // in the vector we should insert into.
9189     if (OtherElementsInOrder) {
9190       // If 2nd operand is undefined, we assume no shifts and no swapping.
9191       if (V2.isUndef()) {
9192         ShiftElts = 0;
9193         Swap = false;
9194       } else {
9195         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9196         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9197                          : BigEndianShifts[CurrentElement & 0xF];
9198         Swap = CurrentElement < BytesInVector;
9199       }
9200       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9201       FoundCandidate = true;
9202       break;
9203     }
9204   }
9205 
9206   if (!FoundCandidate)
9207     return SDValue();
9208 
9209   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9210   // optionally with VECSHL if shift is required.
9211   if (Swap)
9212     std::swap(V1, V2);
9213   if (V2.isUndef())
9214     V2 = V1;
9215   if (ShiftElts) {
9216     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9217                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9218     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9219                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9220   }
9221   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9222                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9223 }
9224 
9225 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9226 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9227 /// SDValue.
9228 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9229                                            SelectionDAG &DAG) const {
9230   const unsigned NumHalfWords = 8;
9231   const unsigned BytesInVector = NumHalfWords * 2;
9232   // Check that the shuffle is on half-words.
9233   if (!isNByteElemShuffleMask(N, 2, 1))
9234     return SDValue();
9235 
9236   bool IsLE = Subtarget.isLittleEndian();
9237   SDLoc dl(N);
9238   SDValue V1 = N->getOperand(0);
9239   SDValue V2 = N->getOperand(1);
9240   unsigned ShiftElts = 0, InsertAtByte = 0;
9241   bool Swap = false;
9242 
9243   // Shifts required to get the half-word we want at element 3.
9244   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9245   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9246 
9247   uint32_t Mask = 0;
9248   uint32_t OriginalOrderLow = 0x1234567;
9249   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9250   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9251   // 32-bit space, only need 4-bit nibbles per element.
9252   for (unsigned i = 0; i < NumHalfWords; ++i) {
9253     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9254     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9255   }
9256 
9257   // For each mask element, find out if we're just inserting something
9258   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9259   // from V2 into V1:
9260   //   X, 1, 2, 3, 4, 5, 6, 7
9261   //   0, X, 2, 3, 4, 5, 6, 7
9262   //   0, 1, X, 3, 4, 5, 6, 7
9263   //   0, 1, 2, X, 4, 5, 6, 7
9264   //   0, 1, 2, 3, X, 5, 6, 7
9265   //   0, 1, 2, 3, 4, X, 6, 7
9266   //   0, 1, 2, 3, 4, 5, X, 7
9267   //   0, 1, 2, 3, 4, 5, 6, X
9268   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9269 
9270   bool FoundCandidate = false;
9271   // Go through the mask of half-words to find an element that's being moved
9272   // from one vector to the other.
9273   for (unsigned i = 0; i < NumHalfWords; ++i) {
9274     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9275     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9276     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9277     uint32_t TargetOrder = 0x0;
9278 
9279     // If both vector operands for the shuffle are the same vector, the mask
9280     // will contain only elements from the first one and the second one will be
9281     // undef.
9282     if (V2.isUndef()) {
9283       ShiftElts = 0;
9284       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9285       TargetOrder = OriginalOrderLow;
9286       Swap = false;
9287       // Skip if not the correct element or mask of other elements don't equal
9288       // to our expected order.
9289       if (MaskOneElt == VINSERTHSrcElem &&
9290           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9291         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9292         FoundCandidate = true;
9293         break;
9294       }
9295     } else { // If both operands are defined.
9296       // Target order is [8,15] if the current mask is between [0,7].
9297       TargetOrder =
9298           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9299       // Skip if mask of other elements don't equal our expected order.
9300       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9301         // We only need the last 3 bits for the number of shifts.
9302         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9303                          : BigEndianShifts[MaskOneElt & 0x7];
9304         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9305         Swap = MaskOneElt < NumHalfWords;
9306         FoundCandidate = true;
9307         break;
9308       }
9309     }
9310   }
9311 
9312   if (!FoundCandidate)
9313     return SDValue();
9314 
9315   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9316   // optionally with VECSHL if shift is required.
9317   if (Swap)
9318     std::swap(V1, V2);
9319   if (V2.isUndef())
9320     V2 = V1;
9321   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9322   if (ShiftElts) {
9323     // Double ShiftElts because we're left shifting on v16i8 type.
9324     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9325                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9326     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9327     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9328                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9329     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9330   }
9331   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9332   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9333                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9334   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9335 }
9336 
9337 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9338 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9339 /// return the default SDValue.
9340 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9341                                               SelectionDAG &DAG) const {
9342   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9343   // to v16i8. Peek through the bitcasts to get the actual operands.
9344   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9345   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9346 
9347   auto ShuffleMask = SVN->getMask();
9348   SDValue VecShuffle(SVN, 0);
9349   SDLoc DL(SVN);
9350 
9351   // Check that we have a four byte shuffle.
9352   if (!isNByteElemShuffleMask(SVN, 4, 1))
9353     return SDValue();
9354 
9355   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9356   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9357     std::swap(LHS, RHS);
9358     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9359     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9360   }
9361 
9362   // Ensure that the RHS is a vector of constants.
9363   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9364   if (!BVN)
9365     return SDValue();
9366 
9367   // Check if RHS is a splat of 4-bytes (or smaller).
9368   APInt APSplatValue, APSplatUndef;
9369   unsigned SplatBitSize;
9370   bool HasAnyUndefs;
9371   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9372                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9373       SplatBitSize > 32)
9374     return SDValue();
9375 
9376   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9377   // The instruction splats a constant C into two words of the source vector
9378   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9379   // Thus we check that the shuffle mask is the equivalent  of
9380   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9381   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9382   // within each word are consecutive, so we only need to check the first byte.
9383   SDValue Index;
9384   bool IsLE = Subtarget.isLittleEndian();
9385   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9386       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9387        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9388     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9389   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9390            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9391             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9392     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9393   else
9394     return SDValue();
9395 
9396   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9397   // for XXSPLTI32DX.
9398   unsigned SplatVal = APSplatValue.getZExtValue();
9399   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9400     SplatVal |= (SplatVal << SplatBitSize);
9401 
9402   SDValue SplatNode = DAG.getNode(
9403       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9404       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9405   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9406 }
9407 
9408 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9409 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9410 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9411 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9412 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9413   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9414   assert(Op.getValueType() == MVT::v1i128 &&
9415          "Only set v1i128 as custom, other type shouldn't reach here!");
9416   SDLoc dl(Op);
9417   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9418   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9419   unsigned SHLAmt = N1.getConstantOperandVal(0);
9420   if (SHLAmt % 8 == 0) {
9421     SmallVector<int, 16> Mask(16, 0);
9422     std::iota(Mask.begin(), Mask.end(), 0);
9423     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9424     if (SDValue Shuffle =
9425             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9426                                  DAG.getUNDEF(MVT::v16i8), Mask))
9427       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9428   }
9429   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9430   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9431                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9432   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9433                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9434   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9435   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9436 }
9437 
9438 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9439 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9440 /// return the code it can be lowered into.  Worst case, it can always be
9441 /// lowered into a vperm.
9442 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9443                                                SelectionDAG &DAG) const {
9444   SDLoc dl(Op);
9445   SDValue V1 = Op.getOperand(0);
9446   SDValue V2 = Op.getOperand(1);
9447   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9448 
9449   // Any nodes that were combined in the target-independent combiner prior
9450   // to vector legalization will not be sent to the target combine. Try to
9451   // combine it here.
9452   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9453     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9454       return NewShuffle;
9455     Op = NewShuffle;
9456     SVOp = cast<ShuffleVectorSDNode>(Op);
9457     V1 = Op.getOperand(0);
9458     V2 = Op.getOperand(1);
9459   }
9460   EVT VT = Op.getValueType();
9461   bool isLittleEndian = Subtarget.isLittleEndian();
9462 
9463   unsigned ShiftElts, InsertAtByte;
9464   bool Swap = false;
9465 
9466   // If this is a load-and-splat, we can do that with a single instruction
9467   // in some cases. However if the load has multiple uses, we don't want to
9468   // combine it because that will just produce multiple loads.
9469   bool IsPermutedLoad = false;
9470   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9471   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9472       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9473       InputLoad->hasOneUse()) {
9474     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9475     int SplatIdx =
9476       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9477 
9478     // The splat index for permuted loads will be in the left half of the vector
9479     // which is strictly wider than the loaded value by 8 bytes. So we need to
9480     // adjust the splat index to point to the correct address in memory.
9481     if (IsPermutedLoad) {
9482       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9483       SplatIdx += IsFourByte ? 2 : 1;
9484       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9485              "Splat of a value outside of the loaded memory");
9486     }
9487 
9488     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9489     // For 4-byte load-and-splat, we need Power9.
9490     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9491       uint64_t Offset = 0;
9492       if (IsFourByte)
9493         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9494       else
9495         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9496 
9497       SDValue BasePtr = LD->getBasePtr();
9498       if (Offset != 0)
9499         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9500                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9501       SDValue Ops[] = {
9502         LD->getChain(),    // Chain
9503         BasePtr,           // BasePtr
9504         DAG.getValueType(Op.getValueType()) // VT
9505       };
9506       SDVTList VTL =
9507         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9508       SDValue LdSplt =
9509         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9510                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9511       if (LdSplt.getValueType() != SVOp->getValueType(0))
9512         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9513       return LdSplt;
9514     }
9515   }
9516   if (Subtarget.hasP9Vector() &&
9517       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9518                            isLittleEndian)) {
9519     if (Swap)
9520       std::swap(V1, V2);
9521     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9522     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9523     if (ShiftElts) {
9524       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9525                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9526       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9527                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9528       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9529     }
9530     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9531                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9532     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9533   }
9534 
9535   if (Subtarget.hasPrefixInstrs()) {
9536     SDValue SplatInsertNode;
9537     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9538       return SplatInsertNode;
9539   }
9540 
9541   if (Subtarget.hasP9Altivec()) {
9542     SDValue NewISDNode;
9543     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9544       return NewISDNode;
9545 
9546     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9547       return NewISDNode;
9548   }
9549 
9550   if (Subtarget.hasVSX() &&
9551       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9552     if (Swap)
9553       std::swap(V1, V2);
9554     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9555     SDValue Conv2 =
9556         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9557 
9558     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9559                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9560     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9561   }
9562 
9563   if (Subtarget.hasVSX() &&
9564     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9565     if (Swap)
9566       std::swap(V1, V2);
9567     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9568     SDValue Conv2 =
9569         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9570 
9571     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9572                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9573     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9574   }
9575 
9576   if (Subtarget.hasP9Vector()) {
9577      if (PPC::isXXBRHShuffleMask(SVOp)) {
9578       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9579       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9580       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9581     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9582       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9583       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9584       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9585     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9586       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9587       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9588       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9589     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9590       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9591       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9592       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9593     }
9594   }
9595 
9596   if (Subtarget.hasVSX()) {
9597     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9598       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9599 
9600       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9601       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9602                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9603       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9604     }
9605 
9606     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9607     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9608       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9609       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9610       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9611     }
9612   }
9613 
9614   // Cases that are handled by instructions that take permute immediates
9615   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9616   // selected by the instruction selector.
9617   if (V2.isUndef()) {
9618     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9619         PPC::isSplatShuffleMask(SVOp, 2) ||
9620         PPC::isSplatShuffleMask(SVOp, 4) ||
9621         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9622         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9623         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9624         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9625         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9626         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9627         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9628         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9629         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9630         (Subtarget.hasP8Altivec() && (
9631          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9632          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9633          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9634       return Op;
9635     }
9636   }
9637 
9638   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9639   // and produce a fixed permutation.  If any of these match, do not lower to
9640   // VPERM.
9641   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9642   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9643       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9644       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9645       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9646       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9647       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9648       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9649       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9650       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9651       (Subtarget.hasP8Altivec() && (
9652        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9653        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9654        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9655     return Op;
9656 
9657   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9658   // perfect shuffle table to emit an optimal matching sequence.
9659   ArrayRef<int> PermMask = SVOp->getMask();
9660 
9661   unsigned PFIndexes[4];
9662   bool isFourElementShuffle = true;
9663   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9664     unsigned EltNo = 8;   // Start out undef.
9665     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9666       if (PermMask[i*4+j] < 0)
9667         continue;   // Undef, ignore it.
9668 
9669       unsigned ByteSource = PermMask[i*4+j];
9670       if ((ByteSource & 3) != j) {
9671         isFourElementShuffle = false;
9672         break;
9673       }
9674 
9675       if (EltNo == 8) {
9676         EltNo = ByteSource/4;
9677       } else if (EltNo != ByteSource/4) {
9678         isFourElementShuffle = false;
9679         break;
9680       }
9681     }
9682     PFIndexes[i] = EltNo;
9683   }
9684 
9685   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9686   // perfect shuffle vector to determine if it is cost effective to do this as
9687   // discrete instructions, or whether we should use a vperm.
9688   // For now, we skip this for little endian until such time as we have a
9689   // little-endian perfect shuffle table.
9690   if (isFourElementShuffle && !isLittleEndian) {
9691     // Compute the index in the perfect shuffle table.
9692     unsigned PFTableIndex =
9693       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9694 
9695     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9696     unsigned Cost  = (PFEntry >> 30);
9697 
9698     // Determining when to avoid vperm is tricky.  Many things affect the cost
9699     // of vperm, particularly how many times the perm mask needs to be computed.
9700     // For example, if the perm mask can be hoisted out of a loop or is already
9701     // used (perhaps because there are multiple permutes with the same shuffle
9702     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9703     // the loop requires an extra register.
9704     //
9705     // As a compromise, we only emit discrete instructions if the shuffle can be
9706     // generated in 3 or fewer operations.  When we have loop information
9707     // available, if this block is within a loop, we should avoid using vperm
9708     // for 3-operation perms and use a constant pool load instead.
9709     if (Cost < 3)
9710       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9711   }
9712 
9713   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9714   // vector that will get spilled to the constant pool.
9715   if (V2.isUndef()) V2 = V1;
9716 
9717   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9718   // that it is in input element units, not in bytes.  Convert now.
9719 
9720   // For little endian, the order of the input vectors is reversed, and
9721   // the permutation mask is complemented with respect to 31.  This is
9722   // necessary to produce proper semantics with the big-endian-biased vperm
9723   // instruction.
9724   EVT EltVT = V1.getValueType().getVectorElementType();
9725   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9726 
9727   SmallVector<SDValue, 16> ResultMask;
9728   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9729     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9730 
9731     for (unsigned j = 0; j != BytesPerElement; ++j)
9732       if (isLittleEndian)
9733         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9734                                              dl, MVT::i32));
9735       else
9736         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9737                                              MVT::i32));
9738   }
9739 
9740   ShufflesHandledWithVPERM++;
9741   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9742   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
9743   LLVM_DEBUG(SVOp->dump());
9744   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
9745   LLVM_DEBUG(VPermMask.dump());
9746 
9747   if (isLittleEndian)
9748     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9749                        V2, V1, VPermMask);
9750   else
9751     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9752                        V1, V2, VPermMask);
9753 }
9754 
9755 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9756 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9757 /// information about the intrinsic.
9758 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9759                                  bool &isDot, const PPCSubtarget &Subtarget) {
9760   unsigned IntrinsicID =
9761       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9762   CompareOpc = -1;
9763   isDot = false;
9764   switch (IntrinsicID) {
9765   default:
9766     return false;
9767   // Comparison predicates.
9768   case Intrinsic::ppc_altivec_vcmpbfp_p:
9769     CompareOpc = 966;
9770     isDot = true;
9771     break;
9772   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9773     CompareOpc = 198;
9774     isDot = true;
9775     break;
9776   case Intrinsic::ppc_altivec_vcmpequb_p:
9777     CompareOpc = 6;
9778     isDot = true;
9779     break;
9780   case Intrinsic::ppc_altivec_vcmpequh_p:
9781     CompareOpc = 70;
9782     isDot = true;
9783     break;
9784   case Intrinsic::ppc_altivec_vcmpequw_p:
9785     CompareOpc = 134;
9786     isDot = true;
9787     break;
9788   case Intrinsic::ppc_altivec_vcmpequd_p:
9789     if (Subtarget.hasP8Altivec()) {
9790       CompareOpc = 199;
9791       isDot = true;
9792     } else
9793       return false;
9794     break;
9795   case Intrinsic::ppc_altivec_vcmpneb_p:
9796   case Intrinsic::ppc_altivec_vcmpneh_p:
9797   case Intrinsic::ppc_altivec_vcmpnew_p:
9798   case Intrinsic::ppc_altivec_vcmpnezb_p:
9799   case Intrinsic::ppc_altivec_vcmpnezh_p:
9800   case Intrinsic::ppc_altivec_vcmpnezw_p:
9801     if (Subtarget.hasP9Altivec()) {
9802       switch (IntrinsicID) {
9803       default:
9804         llvm_unreachable("Unknown comparison intrinsic.");
9805       case Intrinsic::ppc_altivec_vcmpneb_p:
9806         CompareOpc = 7;
9807         break;
9808       case Intrinsic::ppc_altivec_vcmpneh_p:
9809         CompareOpc = 71;
9810         break;
9811       case Intrinsic::ppc_altivec_vcmpnew_p:
9812         CompareOpc = 135;
9813         break;
9814       case Intrinsic::ppc_altivec_vcmpnezb_p:
9815         CompareOpc = 263;
9816         break;
9817       case Intrinsic::ppc_altivec_vcmpnezh_p:
9818         CompareOpc = 327;
9819         break;
9820       case Intrinsic::ppc_altivec_vcmpnezw_p:
9821         CompareOpc = 391;
9822         break;
9823       }
9824       isDot = true;
9825     } else
9826       return false;
9827     break;
9828   case Intrinsic::ppc_altivec_vcmpgefp_p:
9829     CompareOpc = 454;
9830     isDot = true;
9831     break;
9832   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9833     CompareOpc = 710;
9834     isDot = true;
9835     break;
9836   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9837     CompareOpc = 774;
9838     isDot = true;
9839     break;
9840   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9841     CompareOpc = 838;
9842     isDot = true;
9843     break;
9844   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9845     CompareOpc = 902;
9846     isDot = true;
9847     break;
9848   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9849     if (Subtarget.hasP8Altivec()) {
9850       CompareOpc = 967;
9851       isDot = true;
9852     } else
9853       return false;
9854     break;
9855   case Intrinsic::ppc_altivec_vcmpgtub_p:
9856     CompareOpc = 518;
9857     isDot = true;
9858     break;
9859   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9860     CompareOpc = 582;
9861     isDot = true;
9862     break;
9863   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9864     CompareOpc = 646;
9865     isDot = true;
9866     break;
9867   case Intrinsic::ppc_altivec_vcmpgtud_p:
9868     if (Subtarget.hasP8Altivec()) {
9869       CompareOpc = 711;
9870       isDot = true;
9871     } else
9872       return false;
9873     break;
9874 
9875   // VSX predicate comparisons use the same infrastructure
9876   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9877   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9878   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9879   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9880   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9881   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9882     if (Subtarget.hasVSX()) {
9883       switch (IntrinsicID) {
9884       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9885         CompareOpc = 99;
9886         break;
9887       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9888         CompareOpc = 115;
9889         break;
9890       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9891         CompareOpc = 107;
9892         break;
9893       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9894         CompareOpc = 67;
9895         break;
9896       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9897         CompareOpc = 83;
9898         break;
9899       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9900         CompareOpc = 75;
9901         break;
9902       }
9903       isDot = true;
9904     } else
9905       return false;
9906     break;
9907 
9908   // Normal Comparisons.
9909   case Intrinsic::ppc_altivec_vcmpbfp:
9910     CompareOpc = 966;
9911     break;
9912   case Intrinsic::ppc_altivec_vcmpeqfp:
9913     CompareOpc = 198;
9914     break;
9915   case Intrinsic::ppc_altivec_vcmpequb:
9916     CompareOpc = 6;
9917     break;
9918   case Intrinsic::ppc_altivec_vcmpequh:
9919     CompareOpc = 70;
9920     break;
9921   case Intrinsic::ppc_altivec_vcmpequw:
9922     CompareOpc = 134;
9923     break;
9924   case Intrinsic::ppc_altivec_vcmpequd:
9925     if (Subtarget.hasP8Altivec())
9926       CompareOpc = 199;
9927     else
9928       return false;
9929     break;
9930   case Intrinsic::ppc_altivec_vcmpneb:
9931   case Intrinsic::ppc_altivec_vcmpneh:
9932   case Intrinsic::ppc_altivec_vcmpnew:
9933   case Intrinsic::ppc_altivec_vcmpnezb:
9934   case Intrinsic::ppc_altivec_vcmpnezh:
9935   case Intrinsic::ppc_altivec_vcmpnezw:
9936     if (Subtarget.hasP9Altivec())
9937       switch (IntrinsicID) {
9938       default:
9939         llvm_unreachable("Unknown comparison intrinsic.");
9940       case Intrinsic::ppc_altivec_vcmpneb:
9941         CompareOpc = 7;
9942         break;
9943       case Intrinsic::ppc_altivec_vcmpneh:
9944         CompareOpc = 71;
9945         break;
9946       case Intrinsic::ppc_altivec_vcmpnew:
9947         CompareOpc = 135;
9948         break;
9949       case Intrinsic::ppc_altivec_vcmpnezb:
9950         CompareOpc = 263;
9951         break;
9952       case Intrinsic::ppc_altivec_vcmpnezh:
9953         CompareOpc = 327;
9954         break;
9955       case Intrinsic::ppc_altivec_vcmpnezw:
9956         CompareOpc = 391;
9957         break;
9958       }
9959     else
9960       return false;
9961     break;
9962   case Intrinsic::ppc_altivec_vcmpgefp:
9963     CompareOpc = 454;
9964     break;
9965   case Intrinsic::ppc_altivec_vcmpgtfp:
9966     CompareOpc = 710;
9967     break;
9968   case Intrinsic::ppc_altivec_vcmpgtsb:
9969     CompareOpc = 774;
9970     break;
9971   case Intrinsic::ppc_altivec_vcmpgtsh:
9972     CompareOpc = 838;
9973     break;
9974   case Intrinsic::ppc_altivec_vcmpgtsw:
9975     CompareOpc = 902;
9976     break;
9977   case Intrinsic::ppc_altivec_vcmpgtsd:
9978     if (Subtarget.hasP8Altivec())
9979       CompareOpc = 967;
9980     else
9981       return false;
9982     break;
9983   case Intrinsic::ppc_altivec_vcmpgtub:
9984     CompareOpc = 518;
9985     break;
9986   case Intrinsic::ppc_altivec_vcmpgtuh:
9987     CompareOpc = 582;
9988     break;
9989   case Intrinsic::ppc_altivec_vcmpgtuw:
9990     CompareOpc = 646;
9991     break;
9992   case Intrinsic::ppc_altivec_vcmpgtud:
9993     if (Subtarget.hasP8Altivec())
9994       CompareOpc = 711;
9995     else
9996       return false;
9997     break;
9998   }
9999   return true;
10000 }
10001 
10002 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10003 /// lower, do it, otherwise return null.
10004 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10005                                                    SelectionDAG &DAG) const {
10006   unsigned IntrinsicID =
10007     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10008 
10009   SDLoc dl(Op);
10010 
10011   if (IntrinsicID == Intrinsic::thread_pointer) {
10012     // Reads the thread pointer register, used for __builtin_thread_pointer.
10013     if (Subtarget.isPPC64())
10014       return DAG.getRegister(PPC::X13, MVT::i64);
10015     return DAG.getRegister(PPC::R2, MVT::i32);
10016   }
10017 
10018   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10019   // opcode number of the comparison.
10020   int CompareOpc;
10021   bool isDot;
10022   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10023     return SDValue();    // Don't custom lower most intrinsics.
10024 
10025   // If this is a non-dot comparison, make the VCMP node and we are done.
10026   if (!isDot) {
10027     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10028                               Op.getOperand(1), Op.getOperand(2),
10029                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10030     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10031   }
10032 
10033   // Create the PPCISD altivec 'dot' comparison node.
10034   SDValue Ops[] = {
10035     Op.getOperand(2),  // LHS
10036     Op.getOperand(3),  // RHS
10037     DAG.getConstant(CompareOpc, dl, MVT::i32)
10038   };
10039   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10040   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10041 
10042   // Now that we have the comparison, emit a copy from the CR to a GPR.
10043   // This is flagged to the above dot comparison.
10044   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10045                                 DAG.getRegister(PPC::CR6, MVT::i32),
10046                                 CompNode.getValue(1));
10047 
10048   // Unpack the result based on how the target uses it.
10049   unsigned BitNo;   // Bit # of CR6.
10050   bool InvertBit;   // Invert result?
10051   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10052   default:  // Can't happen, don't crash on invalid number though.
10053   case 0:   // Return the value of the EQ bit of CR6.
10054     BitNo = 0; InvertBit = false;
10055     break;
10056   case 1:   // Return the inverted value of the EQ bit of CR6.
10057     BitNo = 0; InvertBit = true;
10058     break;
10059   case 2:   // Return the value of the LT bit of CR6.
10060     BitNo = 2; InvertBit = false;
10061     break;
10062   case 3:   // Return the inverted value of the LT bit of CR6.
10063     BitNo = 2; InvertBit = true;
10064     break;
10065   }
10066 
10067   // Shift the bit into the low position.
10068   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10069                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10070   // Isolate the bit.
10071   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10072                       DAG.getConstant(1, dl, MVT::i32));
10073 
10074   // If we are supposed to, toggle the bit.
10075   if (InvertBit)
10076     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10077                         DAG.getConstant(1, dl, MVT::i32));
10078   return Flags;
10079 }
10080 
10081 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10082                                                SelectionDAG &DAG) const {
10083   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10084   // the beginning of the argument list.
10085   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10086   SDLoc DL(Op);
10087   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10088   case Intrinsic::ppc_cfence: {
10089     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10090     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10091     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10092                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10093                                                   Op.getOperand(ArgStart + 1)),
10094                                       Op.getOperand(0)),
10095                    0);
10096   }
10097   default:
10098     break;
10099   }
10100   return SDValue();
10101 }
10102 
10103 // Lower scalar BSWAP64 to xxbrd.
10104 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10105   SDLoc dl(Op);
10106   // MTVSRDD
10107   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10108                    Op.getOperand(0));
10109   // XXBRD
10110   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10111   // MFVSRD
10112   int VectorIndex = 0;
10113   if (Subtarget.isLittleEndian())
10114     VectorIndex = 1;
10115   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10116                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10117   return Op;
10118 }
10119 
10120 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10121 // compared to a value that is atomically loaded (atomic loads zero-extend).
10122 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10123                                                 SelectionDAG &DAG) const {
10124   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10125          "Expecting an atomic compare-and-swap here.");
10126   SDLoc dl(Op);
10127   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10128   EVT MemVT = AtomicNode->getMemoryVT();
10129   if (MemVT.getSizeInBits() >= 32)
10130     return Op;
10131 
10132   SDValue CmpOp = Op.getOperand(2);
10133   // If this is already correctly zero-extended, leave it alone.
10134   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10135   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10136     return Op;
10137 
10138   // Clear the high bits of the compare operand.
10139   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10140   SDValue NewCmpOp =
10141     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10142                 DAG.getConstant(MaskVal, dl, MVT::i32));
10143 
10144   // Replace the existing compare operand with the properly zero-extended one.
10145   SmallVector<SDValue, 4> Ops;
10146   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10147     Ops.push_back(AtomicNode->getOperand(i));
10148   Ops[2] = NewCmpOp;
10149   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10150   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10151   auto NodeTy =
10152     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10153   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10154 }
10155 
10156 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10157                                                  SelectionDAG &DAG) const {
10158   SDLoc dl(Op);
10159   // Create a stack slot that is 16-byte aligned.
10160   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10161   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10162   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10163   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10164 
10165   // Store the input value into Value#0 of the stack slot.
10166   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10167                                MachinePointerInfo());
10168   // Load it out.
10169   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10170 }
10171 
10172 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10173                                                   SelectionDAG &DAG) const {
10174   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10175          "Should only be called for ISD::INSERT_VECTOR_ELT");
10176 
10177   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10178   // We have legal lowering for constant indices but not for variable ones.
10179   if (!C)
10180     return SDValue();
10181 
10182   EVT VT = Op.getValueType();
10183   SDLoc dl(Op);
10184   SDValue V1 = Op.getOperand(0);
10185   SDValue V2 = Op.getOperand(1);
10186   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10187   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10188     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10189     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10190     unsigned InsertAtElement = C->getZExtValue();
10191     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10192     if (Subtarget.isLittleEndian()) {
10193       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10194     }
10195     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10196                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10197   }
10198   return Op;
10199 }
10200 
10201 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10202   SDLoc dl(Op);
10203   if (Op.getValueType() == MVT::v4i32) {
10204     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10205 
10206     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10207     // +16 as shift amt.
10208     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10209     SDValue RHSSwap =   // = vrlw RHS, 16
10210       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10211 
10212     // Shrinkify inputs to v8i16.
10213     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10214     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10215     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10216 
10217     // Low parts multiplied together, generating 32-bit results (we ignore the
10218     // top parts).
10219     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10220                                         LHS, RHS, DAG, dl, MVT::v4i32);
10221 
10222     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10223                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10224     // Shift the high parts up 16 bits.
10225     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10226                               Neg16, DAG, dl);
10227     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10228   } else if (Op.getValueType() == MVT::v16i8) {
10229     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10230     bool isLittleEndian = Subtarget.isLittleEndian();
10231 
10232     // Multiply the even 8-bit parts, producing 16-bit sums.
10233     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10234                                            LHS, RHS, DAG, dl, MVT::v8i16);
10235     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10236 
10237     // Multiply the odd 8-bit parts, producing 16-bit sums.
10238     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10239                                           LHS, RHS, DAG, dl, MVT::v8i16);
10240     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10241 
10242     // Merge the results together.  Because vmuleub and vmuloub are
10243     // instructions with a big-endian bias, we must reverse the
10244     // element numbering and reverse the meaning of "odd" and "even"
10245     // when generating little endian code.
10246     int Ops[16];
10247     for (unsigned i = 0; i != 8; ++i) {
10248       if (isLittleEndian) {
10249         Ops[i*2  ] = 2*i;
10250         Ops[i*2+1] = 2*i+16;
10251       } else {
10252         Ops[i*2  ] = 2*i+1;
10253         Ops[i*2+1] = 2*i+1+16;
10254       }
10255     }
10256     if (isLittleEndian)
10257       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10258     else
10259       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10260   } else {
10261     llvm_unreachable("Unknown mul to lower!");
10262   }
10263 }
10264 
10265 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10266 
10267   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10268 
10269   EVT VT = Op.getValueType();
10270   assert(VT.isVector() &&
10271          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10272   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10273           VT == MVT::v16i8) &&
10274          "Unexpected vector element type!");
10275   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10276          "Current subtarget doesn't support smax v2i64!");
10277 
10278   // For vector abs, it can be lowered to:
10279   // abs x
10280   // ==>
10281   // y = -x
10282   // smax(x, y)
10283 
10284   SDLoc dl(Op);
10285   SDValue X = Op.getOperand(0);
10286   SDValue Zero = DAG.getConstant(0, dl, VT);
10287   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10288 
10289   // SMAX patch https://reviews.llvm.org/D47332
10290   // hasn't landed yet, so use intrinsic first here.
10291   // TODO: Should use SMAX directly once SMAX patch landed
10292   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10293   if (VT == MVT::v2i64)
10294     BifID = Intrinsic::ppc_altivec_vmaxsd;
10295   else if (VT == MVT::v8i16)
10296     BifID = Intrinsic::ppc_altivec_vmaxsh;
10297   else if (VT == MVT::v16i8)
10298     BifID = Intrinsic::ppc_altivec_vmaxsb;
10299 
10300   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10301 }
10302 
10303 // Custom lowering for fpext vf32 to v2f64
10304 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10305 
10306   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10307          "Should only be called for ISD::FP_EXTEND");
10308 
10309   // FIXME: handle extends from half precision float vectors on P9.
10310   // We only want to custom lower an extend from v2f32 to v2f64.
10311   if (Op.getValueType() != MVT::v2f64 ||
10312       Op.getOperand(0).getValueType() != MVT::v2f32)
10313     return SDValue();
10314 
10315   SDLoc dl(Op);
10316   SDValue Op0 = Op.getOperand(0);
10317 
10318   switch (Op0.getOpcode()) {
10319   default:
10320     return SDValue();
10321   case ISD::EXTRACT_SUBVECTOR: {
10322     assert(Op0.getNumOperands() == 2 &&
10323            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10324            "Node should have 2 operands with second one being a constant!");
10325 
10326     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10327       return SDValue();
10328 
10329     // Custom lower is only done for high or low doubleword.
10330     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10331     if (Idx % 2 != 0)
10332       return SDValue();
10333 
10334     // Since input is v4f32, at this point Idx is either 0 or 2.
10335     // Shift to get the doubleword position we want.
10336     int DWord = Idx >> 1;
10337 
10338     // High and low word positions are different on little endian.
10339     if (Subtarget.isLittleEndian())
10340       DWord ^= 0x1;
10341 
10342     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10343                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10344   }
10345   case ISD::FADD:
10346   case ISD::FMUL:
10347   case ISD::FSUB: {
10348     SDValue NewLoad[2];
10349     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10350       // Ensure both input are loads.
10351       SDValue LdOp = Op0.getOperand(i);
10352       if (LdOp.getOpcode() != ISD::LOAD)
10353         return SDValue();
10354       // Generate new load node.
10355       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10356       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10357       NewLoad[i] = DAG.getMemIntrinsicNode(
10358           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10359           LD->getMemoryVT(), LD->getMemOperand());
10360     }
10361     SDValue NewOp =
10362         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10363                     NewLoad[1], Op0.getNode()->getFlags());
10364     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10365                        DAG.getConstant(0, dl, MVT::i32));
10366   }
10367   case ISD::LOAD: {
10368     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10369     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10370     SDValue NewLd = DAG.getMemIntrinsicNode(
10371         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10372         LD->getMemoryVT(), LD->getMemOperand());
10373     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10374                        DAG.getConstant(0, dl, MVT::i32));
10375   }
10376   }
10377   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10378 }
10379 
10380 /// LowerOperation - Provide custom lowering hooks for some operations.
10381 ///
10382 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10383   switch (Op.getOpcode()) {
10384   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10385   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10386   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10387   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10388   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10389   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10390   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10391   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10392   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10393 
10394   // Variable argument lowering.
10395   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10396   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10397   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10398 
10399   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10400   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10401   case ISD::GET_DYNAMIC_AREA_OFFSET:
10402     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10403 
10404   // Exception handling lowering.
10405   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10406   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10407   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10408 
10409   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10410   case ISD::STORE:              return LowerSTORE(Op, DAG);
10411   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10412   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10413   case ISD::FP_TO_UINT:
10414   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10415   case ISD::UINT_TO_FP:
10416   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10417   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10418 
10419   // Lower 64-bit shifts.
10420   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10421   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10422   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10423 
10424   // Vector-related lowering.
10425   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10426   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10427   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10428   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10429   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10430   case ISD::MUL:                return LowerMUL(Op, DAG);
10431   case ISD::ABS:                return LowerABS(Op, DAG);
10432   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10433   case ISD::ROTL:               return LowerROTL(Op, DAG);
10434 
10435   // For counter-based loop handling.
10436   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10437 
10438   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10439 
10440   // Frame & Return address.
10441   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10442   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10443 
10444   case ISD::INTRINSIC_VOID:
10445     return LowerINTRINSIC_VOID(Op, DAG);
10446   case ISD::BSWAP:
10447     return LowerBSWAP(Op, DAG);
10448   case ISD::ATOMIC_CMP_SWAP:
10449     return LowerATOMIC_CMP_SWAP(Op, DAG);
10450   }
10451 }
10452 
10453 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10454                                            SmallVectorImpl<SDValue>&Results,
10455                                            SelectionDAG &DAG) const {
10456   SDLoc dl(N);
10457   switch (N->getOpcode()) {
10458   default:
10459     llvm_unreachable("Do not know how to custom type legalize this operation!");
10460   case ISD::READCYCLECOUNTER: {
10461     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10462     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10463 
10464     Results.push_back(
10465         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10466     Results.push_back(RTB.getValue(2));
10467     break;
10468   }
10469   case ISD::INTRINSIC_W_CHAIN: {
10470     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10471         Intrinsic::loop_decrement)
10472       break;
10473 
10474     assert(N->getValueType(0) == MVT::i1 &&
10475            "Unexpected result type for CTR decrement intrinsic");
10476     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10477                                  N->getValueType(0));
10478     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10479     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10480                                  N->getOperand(1));
10481 
10482     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10483     Results.push_back(NewInt.getValue(1));
10484     break;
10485   }
10486   case ISD::VAARG: {
10487     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10488       return;
10489 
10490     EVT VT = N->getValueType(0);
10491 
10492     if (VT == MVT::i64) {
10493       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10494 
10495       Results.push_back(NewNode);
10496       Results.push_back(NewNode.getValue(1));
10497     }
10498     return;
10499   }
10500   case ISD::FP_TO_SINT:
10501   case ISD::FP_TO_UINT:
10502     // LowerFP_TO_INT() can only handle f32 and f64.
10503     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10504       return;
10505     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10506     return;
10507   case ISD::TRUNCATE: {
10508     EVT TrgVT = N->getValueType(0);
10509     EVT OpVT = N->getOperand(0).getValueType();
10510     if (TrgVT.isVector() &&
10511         isOperationCustom(N->getOpcode(), TrgVT) &&
10512         OpVT.getSizeInBits() <= 128 &&
10513         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10514       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10515     return;
10516   }
10517   case ISD::BITCAST:
10518     // Don't handle bitcast here.
10519     return;
10520   case ISD::FP_EXTEND:
10521     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10522     if (Lowered)
10523       Results.push_back(Lowered);
10524     return;
10525   }
10526 }
10527 
10528 //===----------------------------------------------------------------------===//
10529 //  Other Lowering Code
10530 //===----------------------------------------------------------------------===//
10531 
10532 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10533   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10534   Function *Func = Intrinsic::getDeclaration(M, Id);
10535   return Builder.CreateCall(Func, {});
10536 }
10537 
10538 // The mappings for emitLeading/TrailingFence is taken from
10539 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10540 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10541                                                  Instruction *Inst,
10542                                                  AtomicOrdering Ord) const {
10543   if (Ord == AtomicOrdering::SequentiallyConsistent)
10544     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10545   if (isReleaseOrStronger(Ord))
10546     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10547   return nullptr;
10548 }
10549 
10550 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10551                                                   Instruction *Inst,
10552                                                   AtomicOrdering Ord) const {
10553   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10554     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10555     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10556     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10557     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10558       return Builder.CreateCall(
10559           Intrinsic::getDeclaration(
10560               Builder.GetInsertBlock()->getParent()->getParent(),
10561               Intrinsic::ppc_cfence, {Inst->getType()}),
10562           {Inst});
10563     // FIXME: Can use isync for rmw operation.
10564     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10565   }
10566   return nullptr;
10567 }
10568 
10569 MachineBasicBlock *
10570 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10571                                     unsigned AtomicSize,
10572                                     unsigned BinOpcode,
10573                                     unsigned CmpOpcode,
10574                                     unsigned CmpPred) const {
10575   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10576   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10577 
10578   auto LoadMnemonic = PPC::LDARX;
10579   auto StoreMnemonic = PPC::STDCX;
10580   switch (AtomicSize) {
10581   default:
10582     llvm_unreachable("Unexpected size of atomic entity");
10583   case 1:
10584     LoadMnemonic = PPC::LBARX;
10585     StoreMnemonic = PPC::STBCX;
10586     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10587     break;
10588   case 2:
10589     LoadMnemonic = PPC::LHARX;
10590     StoreMnemonic = PPC::STHCX;
10591     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10592     break;
10593   case 4:
10594     LoadMnemonic = PPC::LWARX;
10595     StoreMnemonic = PPC::STWCX;
10596     break;
10597   case 8:
10598     LoadMnemonic = PPC::LDARX;
10599     StoreMnemonic = PPC::STDCX;
10600     break;
10601   }
10602 
10603   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10604   MachineFunction *F = BB->getParent();
10605   MachineFunction::iterator It = ++BB->getIterator();
10606 
10607   Register dest = MI.getOperand(0).getReg();
10608   Register ptrA = MI.getOperand(1).getReg();
10609   Register ptrB = MI.getOperand(2).getReg();
10610   Register incr = MI.getOperand(3).getReg();
10611   DebugLoc dl = MI.getDebugLoc();
10612 
10613   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10614   MachineBasicBlock *loop2MBB =
10615     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10616   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10617   F->insert(It, loopMBB);
10618   if (CmpOpcode)
10619     F->insert(It, loop2MBB);
10620   F->insert(It, exitMBB);
10621   exitMBB->splice(exitMBB->begin(), BB,
10622                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10623   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10624 
10625   MachineRegisterInfo &RegInfo = F->getRegInfo();
10626   Register TmpReg = (!BinOpcode) ? incr :
10627     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10628                                            : &PPC::GPRCRegClass);
10629 
10630   //  thisMBB:
10631   //   ...
10632   //   fallthrough --> loopMBB
10633   BB->addSuccessor(loopMBB);
10634 
10635   //  loopMBB:
10636   //   l[wd]arx dest, ptr
10637   //   add r0, dest, incr
10638   //   st[wd]cx. r0, ptr
10639   //   bne- loopMBB
10640   //   fallthrough --> exitMBB
10641 
10642   // For max/min...
10643   //  loopMBB:
10644   //   l[wd]arx dest, ptr
10645   //   cmpl?[wd] incr, dest
10646   //   bgt exitMBB
10647   //  loop2MBB:
10648   //   st[wd]cx. dest, ptr
10649   //   bne- loopMBB
10650   //   fallthrough --> exitMBB
10651 
10652   BB = loopMBB;
10653   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10654     .addReg(ptrA).addReg(ptrB);
10655   if (BinOpcode)
10656     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10657   if (CmpOpcode) {
10658     // Signed comparisons of byte or halfword values must be sign-extended.
10659     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10660       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10661       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10662               ExtReg).addReg(dest);
10663       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10664         .addReg(incr).addReg(ExtReg);
10665     } else
10666       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10667         .addReg(incr).addReg(dest);
10668 
10669     BuildMI(BB, dl, TII->get(PPC::BCC))
10670       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10671     BB->addSuccessor(loop2MBB);
10672     BB->addSuccessor(exitMBB);
10673     BB = loop2MBB;
10674   }
10675   BuildMI(BB, dl, TII->get(StoreMnemonic))
10676     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10677   BuildMI(BB, dl, TII->get(PPC::BCC))
10678     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10679   BB->addSuccessor(loopMBB);
10680   BB->addSuccessor(exitMBB);
10681 
10682   //  exitMBB:
10683   //   ...
10684   BB = exitMBB;
10685   return BB;
10686 }
10687 
10688 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10689     MachineInstr &MI, MachineBasicBlock *BB,
10690     bool is8bit, // operation
10691     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10692   // If we support part-word atomic mnemonics, just use them
10693   if (Subtarget.hasPartwordAtomics())
10694     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10695                             CmpPred);
10696 
10697   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10698   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10699   // In 64 bit mode we have to use 64 bits for addresses, even though the
10700   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10701   // registers without caring whether they're 32 or 64, but here we're
10702   // doing actual arithmetic on the addresses.
10703   bool is64bit = Subtarget.isPPC64();
10704   bool isLittleEndian = Subtarget.isLittleEndian();
10705   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10706 
10707   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10708   MachineFunction *F = BB->getParent();
10709   MachineFunction::iterator It = ++BB->getIterator();
10710 
10711   Register dest = MI.getOperand(0).getReg();
10712   Register ptrA = MI.getOperand(1).getReg();
10713   Register ptrB = MI.getOperand(2).getReg();
10714   Register incr = MI.getOperand(3).getReg();
10715   DebugLoc dl = MI.getDebugLoc();
10716 
10717   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10718   MachineBasicBlock *loop2MBB =
10719       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10720   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10721   F->insert(It, loopMBB);
10722   if (CmpOpcode)
10723     F->insert(It, loop2MBB);
10724   F->insert(It, exitMBB);
10725   exitMBB->splice(exitMBB->begin(), BB,
10726                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10727   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10728 
10729   MachineRegisterInfo &RegInfo = F->getRegInfo();
10730   const TargetRegisterClass *RC =
10731       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10732   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10733 
10734   Register PtrReg = RegInfo.createVirtualRegister(RC);
10735   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10736   Register ShiftReg =
10737       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10738   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10739   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10740   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10741   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10742   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10743   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10744   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10745   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10746   Register Ptr1Reg;
10747   Register TmpReg =
10748       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10749 
10750   //  thisMBB:
10751   //   ...
10752   //   fallthrough --> loopMBB
10753   BB->addSuccessor(loopMBB);
10754 
10755   // The 4-byte load must be aligned, while a char or short may be
10756   // anywhere in the word.  Hence all this nasty bookkeeping code.
10757   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10758   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10759   //   xori shift, shift1, 24 [16]
10760   //   rlwinm ptr, ptr1, 0, 0, 29
10761   //   slw incr2, incr, shift
10762   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10763   //   slw mask, mask2, shift
10764   //  loopMBB:
10765   //   lwarx tmpDest, ptr
10766   //   add tmp, tmpDest, incr2
10767   //   andc tmp2, tmpDest, mask
10768   //   and tmp3, tmp, mask
10769   //   or tmp4, tmp3, tmp2
10770   //   stwcx. tmp4, ptr
10771   //   bne- loopMBB
10772   //   fallthrough --> exitMBB
10773   //   srw dest, tmpDest, shift
10774   if (ptrA != ZeroReg) {
10775     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10776     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10777         .addReg(ptrA)
10778         .addReg(ptrB);
10779   } else {
10780     Ptr1Reg = ptrB;
10781   }
10782   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10783   // mode.
10784   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10785       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10786       .addImm(3)
10787       .addImm(27)
10788       .addImm(is8bit ? 28 : 27);
10789   if (!isLittleEndian)
10790     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10791         .addReg(Shift1Reg)
10792         .addImm(is8bit ? 24 : 16);
10793   if (is64bit)
10794     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10795         .addReg(Ptr1Reg)
10796         .addImm(0)
10797         .addImm(61);
10798   else
10799     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10800         .addReg(Ptr1Reg)
10801         .addImm(0)
10802         .addImm(0)
10803         .addImm(29);
10804   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10805   if (is8bit)
10806     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10807   else {
10808     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10809     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10810         .addReg(Mask3Reg)
10811         .addImm(65535);
10812   }
10813   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10814       .addReg(Mask2Reg)
10815       .addReg(ShiftReg);
10816 
10817   BB = loopMBB;
10818   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10819       .addReg(ZeroReg)
10820       .addReg(PtrReg);
10821   if (BinOpcode)
10822     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10823         .addReg(Incr2Reg)
10824         .addReg(TmpDestReg);
10825   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10826       .addReg(TmpDestReg)
10827       .addReg(MaskReg);
10828   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10829   if (CmpOpcode) {
10830     // For unsigned comparisons, we can directly compare the shifted values.
10831     // For signed comparisons we shift and sign extend.
10832     Register SReg = RegInfo.createVirtualRegister(GPRC);
10833     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10834         .addReg(TmpDestReg)
10835         .addReg(MaskReg);
10836     unsigned ValueReg = SReg;
10837     unsigned CmpReg = Incr2Reg;
10838     if (CmpOpcode == PPC::CMPW) {
10839       ValueReg = RegInfo.createVirtualRegister(GPRC);
10840       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10841           .addReg(SReg)
10842           .addReg(ShiftReg);
10843       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10844       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10845           .addReg(ValueReg);
10846       ValueReg = ValueSReg;
10847       CmpReg = incr;
10848     }
10849     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10850         .addReg(CmpReg)
10851         .addReg(ValueReg);
10852     BuildMI(BB, dl, TII->get(PPC::BCC))
10853         .addImm(CmpPred)
10854         .addReg(PPC::CR0)
10855         .addMBB(exitMBB);
10856     BB->addSuccessor(loop2MBB);
10857     BB->addSuccessor(exitMBB);
10858     BB = loop2MBB;
10859   }
10860   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10861   BuildMI(BB, dl, TII->get(PPC::STWCX))
10862       .addReg(Tmp4Reg)
10863       .addReg(ZeroReg)
10864       .addReg(PtrReg);
10865   BuildMI(BB, dl, TII->get(PPC::BCC))
10866       .addImm(PPC::PRED_NE)
10867       .addReg(PPC::CR0)
10868       .addMBB(loopMBB);
10869   BB->addSuccessor(loopMBB);
10870   BB->addSuccessor(exitMBB);
10871 
10872   //  exitMBB:
10873   //   ...
10874   BB = exitMBB;
10875   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10876       .addReg(TmpDestReg)
10877       .addReg(ShiftReg);
10878   return BB;
10879 }
10880 
10881 llvm::MachineBasicBlock *
10882 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10883                                     MachineBasicBlock *MBB) const {
10884   DebugLoc DL = MI.getDebugLoc();
10885   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10886   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10887 
10888   MachineFunction *MF = MBB->getParent();
10889   MachineRegisterInfo &MRI = MF->getRegInfo();
10890 
10891   const BasicBlock *BB = MBB->getBasicBlock();
10892   MachineFunction::iterator I = ++MBB->getIterator();
10893 
10894   Register DstReg = MI.getOperand(0).getReg();
10895   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10896   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10897   Register mainDstReg = MRI.createVirtualRegister(RC);
10898   Register restoreDstReg = MRI.createVirtualRegister(RC);
10899 
10900   MVT PVT = getPointerTy(MF->getDataLayout());
10901   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10902          "Invalid Pointer Size!");
10903   // For v = setjmp(buf), we generate
10904   //
10905   // thisMBB:
10906   //  SjLjSetup mainMBB
10907   //  bl mainMBB
10908   //  v_restore = 1
10909   //  b sinkMBB
10910   //
10911   // mainMBB:
10912   //  buf[LabelOffset] = LR
10913   //  v_main = 0
10914   //
10915   // sinkMBB:
10916   //  v = phi(main, restore)
10917   //
10918 
10919   MachineBasicBlock *thisMBB = MBB;
10920   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10921   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10922   MF->insert(I, mainMBB);
10923   MF->insert(I, sinkMBB);
10924 
10925   MachineInstrBuilder MIB;
10926 
10927   // Transfer the remainder of BB and its successor edges to sinkMBB.
10928   sinkMBB->splice(sinkMBB->begin(), MBB,
10929                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10930   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10931 
10932   // Note that the structure of the jmp_buf used here is not compatible
10933   // with that used by libc, and is not designed to be. Specifically, it
10934   // stores only those 'reserved' registers that LLVM does not otherwise
10935   // understand how to spill. Also, by convention, by the time this
10936   // intrinsic is called, Clang has already stored the frame address in the
10937   // first slot of the buffer and stack address in the third. Following the
10938   // X86 target code, we'll store the jump address in the second slot. We also
10939   // need to save the TOC pointer (R2) to handle jumps between shared
10940   // libraries, and that will be stored in the fourth slot. The thread
10941   // identifier (R13) is not affected.
10942 
10943   // thisMBB:
10944   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10945   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10946   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10947 
10948   // Prepare IP either in reg.
10949   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10950   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10951   Register BufReg = MI.getOperand(1).getReg();
10952 
10953   if (Subtarget.is64BitELFABI()) {
10954     setUsesTOCBasePtr(*MBB->getParent());
10955     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10956               .addReg(PPC::X2)
10957               .addImm(TOCOffset)
10958               .addReg(BufReg)
10959               .cloneMemRefs(MI);
10960   }
10961 
10962   // Naked functions never have a base pointer, and so we use r1. For all
10963   // other functions, this decision must be delayed until during PEI.
10964   unsigned BaseReg;
10965   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10966     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10967   else
10968     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10969 
10970   MIB = BuildMI(*thisMBB, MI, DL,
10971                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10972             .addReg(BaseReg)
10973             .addImm(BPOffset)
10974             .addReg(BufReg)
10975             .cloneMemRefs(MI);
10976 
10977   // Setup
10978   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10979   MIB.addRegMask(TRI->getNoPreservedMask());
10980 
10981   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10982 
10983   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10984           .addMBB(mainMBB);
10985   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10986 
10987   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10988   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10989 
10990   // mainMBB:
10991   //  mainDstReg = 0
10992   MIB =
10993       BuildMI(mainMBB, DL,
10994               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10995 
10996   // Store IP
10997   if (Subtarget.isPPC64()) {
10998     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10999             .addReg(LabelReg)
11000             .addImm(LabelOffset)
11001             .addReg(BufReg);
11002   } else {
11003     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11004             .addReg(LabelReg)
11005             .addImm(LabelOffset)
11006             .addReg(BufReg);
11007   }
11008   MIB.cloneMemRefs(MI);
11009 
11010   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11011   mainMBB->addSuccessor(sinkMBB);
11012 
11013   // sinkMBB:
11014   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11015           TII->get(PPC::PHI), DstReg)
11016     .addReg(mainDstReg).addMBB(mainMBB)
11017     .addReg(restoreDstReg).addMBB(thisMBB);
11018 
11019   MI.eraseFromParent();
11020   return sinkMBB;
11021 }
11022 
11023 MachineBasicBlock *
11024 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11025                                      MachineBasicBlock *MBB) const {
11026   DebugLoc DL = MI.getDebugLoc();
11027   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11028 
11029   MachineFunction *MF = MBB->getParent();
11030   MachineRegisterInfo &MRI = MF->getRegInfo();
11031 
11032   MVT PVT = getPointerTy(MF->getDataLayout());
11033   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11034          "Invalid Pointer Size!");
11035 
11036   const TargetRegisterClass *RC =
11037     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11038   Register Tmp = MRI.createVirtualRegister(RC);
11039   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11040   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11041   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11042   unsigned BP =
11043       (PVT == MVT::i64)
11044           ? PPC::X30
11045           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11046                                                               : PPC::R30);
11047 
11048   MachineInstrBuilder MIB;
11049 
11050   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11051   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11052   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11053   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11054 
11055   Register BufReg = MI.getOperand(0).getReg();
11056 
11057   // Reload FP (the jumped-to function may not have had a
11058   // frame pointer, and if so, then its r31 will be restored
11059   // as necessary).
11060   if (PVT == MVT::i64) {
11061     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11062             .addImm(0)
11063             .addReg(BufReg);
11064   } else {
11065     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11066             .addImm(0)
11067             .addReg(BufReg);
11068   }
11069   MIB.cloneMemRefs(MI);
11070 
11071   // Reload IP
11072   if (PVT == MVT::i64) {
11073     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11074             .addImm(LabelOffset)
11075             .addReg(BufReg);
11076   } else {
11077     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11078             .addImm(LabelOffset)
11079             .addReg(BufReg);
11080   }
11081   MIB.cloneMemRefs(MI);
11082 
11083   // Reload SP
11084   if (PVT == MVT::i64) {
11085     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11086             .addImm(SPOffset)
11087             .addReg(BufReg);
11088   } else {
11089     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11090             .addImm(SPOffset)
11091             .addReg(BufReg);
11092   }
11093   MIB.cloneMemRefs(MI);
11094 
11095   // Reload BP
11096   if (PVT == MVT::i64) {
11097     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11098             .addImm(BPOffset)
11099             .addReg(BufReg);
11100   } else {
11101     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11102             .addImm(BPOffset)
11103             .addReg(BufReg);
11104   }
11105   MIB.cloneMemRefs(MI);
11106 
11107   // Reload TOC
11108   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11109     setUsesTOCBasePtr(*MBB->getParent());
11110     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11111               .addImm(TOCOffset)
11112               .addReg(BufReg)
11113               .cloneMemRefs(MI);
11114   }
11115 
11116   // Jump
11117   BuildMI(*MBB, MI, DL,
11118           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11119   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11120 
11121   MI.eraseFromParent();
11122   return MBB;
11123 }
11124 
11125 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11126   // If the function specifically requests inline stack probes, emit them.
11127   if (MF.getFunction().hasFnAttribute("probe-stack"))
11128     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11129            "inline-asm";
11130   return false;
11131 }
11132 
11133 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11134   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11135   unsigned StackAlign = TFI->getStackAlignment();
11136   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11137          "Unexpected stack alignment");
11138   // The default stack probe size is 4096 if the function has no
11139   // stack-probe-size attribute.
11140   unsigned StackProbeSize = 4096;
11141   const Function &Fn = MF.getFunction();
11142   if (Fn.hasFnAttribute("stack-probe-size"))
11143     Fn.getFnAttribute("stack-probe-size")
11144         .getValueAsString()
11145         .getAsInteger(0, StackProbeSize);
11146   // Round down to the stack alignment.
11147   StackProbeSize &= ~(StackAlign - 1);
11148   return StackProbeSize ? StackProbeSize : StackAlign;
11149 }
11150 
11151 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11152 // into three phases. In the first phase, it uses pseudo instruction
11153 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11154 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11155 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11156 // MaxCallFrameSize so that it can calculate correct data area pointer.
11157 MachineBasicBlock *
11158 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11159                                     MachineBasicBlock *MBB) const {
11160   const bool isPPC64 = Subtarget.isPPC64();
11161   MachineFunction *MF = MBB->getParent();
11162   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11163   DebugLoc DL = MI.getDebugLoc();
11164   const unsigned ProbeSize = getStackProbeSize(*MF);
11165   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11166   MachineRegisterInfo &MRI = MF->getRegInfo();
11167   // The CFG of probing stack looks as
11168   //         +-----+
11169   //         | MBB |
11170   //         +--+--+
11171   //            |
11172   //       +----v----+
11173   //  +--->+ TestMBB +---+
11174   //  |    +----+----+   |
11175   //  |         |        |
11176   //  |   +-----v----+   |
11177   //  +---+ BlockMBB |   |
11178   //      +----------+   |
11179   //                     |
11180   //       +---------+   |
11181   //       | TailMBB +<--+
11182   //       +---------+
11183   // In MBB, calculate previous frame pointer and final stack pointer.
11184   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11185   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11186   // TailMBB is spliced via \p MI.
11187   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11188   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11189   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11190 
11191   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11192   MF->insert(MBBIter, TestMBB);
11193   MF->insert(MBBIter, BlockMBB);
11194   MF->insert(MBBIter, TailMBB);
11195 
11196   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11197   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11198 
11199   Register DstReg = MI.getOperand(0).getReg();
11200   Register NegSizeReg = MI.getOperand(1).getReg();
11201   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11202   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11203   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11204   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11205 
11206   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11207   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11208   // NegSize.
11209   unsigned ProbeOpc;
11210   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11211     ProbeOpc =
11212         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11213   else
11214     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11215     // and NegSizeReg will be allocated in the same phyreg to avoid
11216     // redundant copy when NegSizeReg has only one use which is current MI and
11217     // will be replaced by PREPARE_PROBED_ALLOCA then.
11218     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11219                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11220   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11221       .addDef(ActualNegSizeReg)
11222       .addReg(NegSizeReg)
11223       .add(MI.getOperand(2))
11224       .add(MI.getOperand(3));
11225 
11226   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11227   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11228           FinalStackPtr)
11229       .addReg(SPReg)
11230       .addReg(ActualNegSizeReg);
11231 
11232   // Materialize a scratch register for update.
11233   int64_t NegProbeSize = -(int64_t)ProbeSize;
11234   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11235   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11236   if (!isInt<16>(NegProbeSize)) {
11237     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11238     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11239         .addImm(NegProbeSize >> 16);
11240     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11241             ScratchReg)
11242         .addReg(TempReg)
11243         .addImm(NegProbeSize & 0xFFFF);
11244   } else
11245     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11246         .addImm(NegProbeSize);
11247 
11248   {
11249     // Probing leading residual part.
11250     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11251     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11252         .addReg(ActualNegSizeReg)
11253         .addReg(ScratchReg);
11254     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11255     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11256         .addReg(Div)
11257         .addReg(ScratchReg);
11258     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11259     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11260         .addReg(Mul)
11261         .addReg(ActualNegSizeReg);
11262     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11263         .addReg(FramePointer)
11264         .addReg(SPReg)
11265         .addReg(NegMod);
11266   }
11267 
11268   {
11269     // Remaining part should be multiple of ProbeSize.
11270     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11271     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11272         .addReg(SPReg)
11273         .addReg(FinalStackPtr);
11274     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11275         .addImm(PPC::PRED_EQ)
11276         .addReg(CmpResult)
11277         .addMBB(TailMBB);
11278     TestMBB->addSuccessor(BlockMBB);
11279     TestMBB->addSuccessor(TailMBB);
11280   }
11281 
11282   {
11283     // Touch the block.
11284     // |P...|P...|P...
11285     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11286         .addReg(FramePointer)
11287         .addReg(SPReg)
11288         .addReg(ScratchReg);
11289     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11290     BlockMBB->addSuccessor(TestMBB);
11291   }
11292 
11293   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11294   // DYNAREAOFFSET pseudo instruction to get the future result.
11295   Register MaxCallFrameSizeReg =
11296       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11297   BuildMI(TailMBB, DL,
11298           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11299           MaxCallFrameSizeReg)
11300       .add(MI.getOperand(2))
11301       .add(MI.getOperand(3));
11302   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11303       .addReg(SPReg)
11304       .addReg(MaxCallFrameSizeReg);
11305 
11306   // Splice instructions after MI to TailMBB.
11307   TailMBB->splice(TailMBB->end(), MBB,
11308                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11309   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11310   MBB->addSuccessor(TestMBB);
11311 
11312   // Delete the pseudo instruction.
11313   MI.eraseFromParent();
11314 
11315   ++NumDynamicAllocaProbed;
11316   return TailMBB;
11317 }
11318 
11319 MachineBasicBlock *
11320 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11321                                                MachineBasicBlock *BB) const {
11322   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11323       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11324     if (Subtarget.is64BitELFABI() &&
11325         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11326         !Subtarget.isUsingPCRelativeCalls()) {
11327       // Call lowering should have added an r2 operand to indicate a dependence
11328       // on the TOC base pointer value. It can't however, because there is no
11329       // way to mark the dependence as implicit there, and so the stackmap code
11330       // will confuse it with a regular operand. Instead, add the dependence
11331       // here.
11332       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11333     }
11334 
11335     return emitPatchPoint(MI, BB);
11336   }
11337 
11338   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11339       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11340     return emitEHSjLjSetJmp(MI, BB);
11341   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11342              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11343     return emitEHSjLjLongJmp(MI, BB);
11344   }
11345 
11346   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11347 
11348   // To "insert" these instructions we actually have to insert their
11349   // control-flow patterns.
11350   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11351   MachineFunction::iterator It = ++BB->getIterator();
11352 
11353   MachineFunction *F = BB->getParent();
11354 
11355   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11356       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11357       MI.getOpcode() == PPC::SELECT_I8) {
11358     SmallVector<MachineOperand, 2> Cond;
11359     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11360         MI.getOpcode() == PPC::SELECT_CC_I8)
11361       Cond.push_back(MI.getOperand(4));
11362     else
11363       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11364     Cond.push_back(MI.getOperand(1));
11365 
11366     DebugLoc dl = MI.getDebugLoc();
11367     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11368                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11369   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11370              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11371              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11372              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11373              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11374              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11375              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11376              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11377              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11378              MI.getOpcode() == PPC::SELECT_F4 ||
11379              MI.getOpcode() == PPC::SELECT_F8 ||
11380              MI.getOpcode() == PPC::SELECT_F16 ||
11381              MI.getOpcode() == PPC::SELECT_SPE ||
11382              MI.getOpcode() == PPC::SELECT_SPE4 ||
11383              MI.getOpcode() == PPC::SELECT_VRRC ||
11384              MI.getOpcode() == PPC::SELECT_VSFRC ||
11385              MI.getOpcode() == PPC::SELECT_VSSRC ||
11386              MI.getOpcode() == PPC::SELECT_VSRC) {
11387     // The incoming instruction knows the destination vreg to set, the
11388     // condition code register to branch on, the true/false values to
11389     // select between, and a branch opcode to use.
11390 
11391     //  thisMBB:
11392     //  ...
11393     //   TrueVal = ...
11394     //   cmpTY ccX, r1, r2
11395     //   bCC copy1MBB
11396     //   fallthrough --> copy0MBB
11397     MachineBasicBlock *thisMBB = BB;
11398     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11399     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11400     DebugLoc dl = MI.getDebugLoc();
11401     F->insert(It, copy0MBB);
11402     F->insert(It, sinkMBB);
11403 
11404     // Transfer the remainder of BB and its successor edges to sinkMBB.
11405     sinkMBB->splice(sinkMBB->begin(), BB,
11406                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11407     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11408 
11409     // Next, add the true and fallthrough blocks as its successors.
11410     BB->addSuccessor(copy0MBB);
11411     BB->addSuccessor(sinkMBB);
11412 
11413     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11414         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11415         MI.getOpcode() == PPC::SELECT_F16 ||
11416         MI.getOpcode() == PPC::SELECT_SPE4 ||
11417         MI.getOpcode() == PPC::SELECT_SPE ||
11418         MI.getOpcode() == PPC::SELECT_VRRC ||
11419         MI.getOpcode() == PPC::SELECT_VSFRC ||
11420         MI.getOpcode() == PPC::SELECT_VSSRC ||
11421         MI.getOpcode() == PPC::SELECT_VSRC) {
11422       BuildMI(BB, dl, TII->get(PPC::BC))
11423           .addReg(MI.getOperand(1).getReg())
11424           .addMBB(sinkMBB);
11425     } else {
11426       unsigned SelectPred = MI.getOperand(4).getImm();
11427       BuildMI(BB, dl, TII->get(PPC::BCC))
11428           .addImm(SelectPred)
11429           .addReg(MI.getOperand(1).getReg())
11430           .addMBB(sinkMBB);
11431     }
11432 
11433     //  copy0MBB:
11434     //   %FalseValue = ...
11435     //   # fallthrough to sinkMBB
11436     BB = copy0MBB;
11437 
11438     // Update machine-CFG edges
11439     BB->addSuccessor(sinkMBB);
11440 
11441     //  sinkMBB:
11442     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11443     //  ...
11444     BB = sinkMBB;
11445     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11446         .addReg(MI.getOperand(3).getReg())
11447         .addMBB(copy0MBB)
11448         .addReg(MI.getOperand(2).getReg())
11449         .addMBB(thisMBB);
11450   } else if (MI.getOpcode() == PPC::ReadTB) {
11451     // To read the 64-bit time-base register on a 32-bit target, we read the
11452     // two halves. Should the counter have wrapped while it was being read, we
11453     // need to try again.
11454     // ...
11455     // readLoop:
11456     // mfspr Rx,TBU # load from TBU
11457     // mfspr Ry,TB  # load from TB
11458     // mfspr Rz,TBU # load from TBU
11459     // cmpw crX,Rx,Rz # check if 'old'='new'
11460     // bne readLoop   # branch if they're not equal
11461     // ...
11462 
11463     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11464     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11465     DebugLoc dl = MI.getDebugLoc();
11466     F->insert(It, readMBB);
11467     F->insert(It, sinkMBB);
11468 
11469     // Transfer the remainder of BB and its successor edges to sinkMBB.
11470     sinkMBB->splice(sinkMBB->begin(), BB,
11471                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11472     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11473 
11474     BB->addSuccessor(readMBB);
11475     BB = readMBB;
11476 
11477     MachineRegisterInfo &RegInfo = F->getRegInfo();
11478     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11479     Register LoReg = MI.getOperand(0).getReg();
11480     Register HiReg = MI.getOperand(1).getReg();
11481 
11482     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11483     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11484     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11485 
11486     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11487 
11488     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11489         .addReg(HiReg)
11490         .addReg(ReadAgainReg);
11491     BuildMI(BB, dl, TII->get(PPC::BCC))
11492         .addImm(PPC::PRED_NE)
11493         .addReg(CmpReg)
11494         .addMBB(readMBB);
11495 
11496     BB->addSuccessor(readMBB);
11497     BB->addSuccessor(sinkMBB);
11498   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11499     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11500   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11501     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11502   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11503     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11504   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11505     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11506 
11507   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11508     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11509   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11510     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11511   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11512     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11513   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11514     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11515 
11516   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11517     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11518   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11519     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11520   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11521     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11522   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11523     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11524 
11525   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11526     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11527   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11528     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11529   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11530     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11531   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11532     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11533 
11534   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11535     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11536   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11537     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11538   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11539     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11540   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11541     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11542 
11543   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11544     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11545   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11546     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11547   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11548     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11549   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11550     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11551 
11552   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11553     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11554   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11555     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11556   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11557     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11558   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11559     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11560 
11561   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11562     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11563   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11564     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11565   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11566     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11567   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11568     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11569 
11570   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11571     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11572   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11573     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11574   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11575     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11576   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11577     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11578 
11579   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11580     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11581   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11582     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11583   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11584     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11585   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11586     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11587 
11588   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11589     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11590   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11591     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11592   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11593     BB = EmitAtomicBinary(MI, BB, 4, 0);
11594   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11595     BB = EmitAtomicBinary(MI, BB, 8, 0);
11596   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11597            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11598            (Subtarget.hasPartwordAtomics() &&
11599             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11600            (Subtarget.hasPartwordAtomics() &&
11601             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11602     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11603 
11604     auto LoadMnemonic = PPC::LDARX;
11605     auto StoreMnemonic = PPC::STDCX;
11606     switch (MI.getOpcode()) {
11607     default:
11608       llvm_unreachable("Compare and swap of unknown size");
11609     case PPC::ATOMIC_CMP_SWAP_I8:
11610       LoadMnemonic = PPC::LBARX;
11611       StoreMnemonic = PPC::STBCX;
11612       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11613       break;
11614     case PPC::ATOMIC_CMP_SWAP_I16:
11615       LoadMnemonic = PPC::LHARX;
11616       StoreMnemonic = PPC::STHCX;
11617       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11618       break;
11619     case PPC::ATOMIC_CMP_SWAP_I32:
11620       LoadMnemonic = PPC::LWARX;
11621       StoreMnemonic = PPC::STWCX;
11622       break;
11623     case PPC::ATOMIC_CMP_SWAP_I64:
11624       LoadMnemonic = PPC::LDARX;
11625       StoreMnemonic = PPC::STDCX;
11626       break;
11627     }
11628     Register dest = MI.getOperand(0).getReg();
11629     Register ptrA = MI.getOperand(1).getReg();
11630     Register ptrB = MI.getOperand(2).getReg();
11631     Register oldval = MI.getOperand(3).getReg();
11632     Register newval = MI.getOperand(4).getReg();
11633     DebugLoc dl = MI.getDebugLoc();
11634 
11635     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11636     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11637     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11638     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11639     F->insert(It, loop1MBB);
11640     F->insert(It, loop2MBB);
11641     F->insert(It, midMBB);
11642     F->insert(It, exitMBB);
11643     exitMBB->splice(exitMBB->begin(), BB,
11644                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11645     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11646 
11647     //  thisMBB:
11648     //   ...
11649     //   fallthrough --> loopMBB
11650     BB->addSuccessor(loop1MBB);
11651 
11652     // loop1MBB:
11653     //   l[bhwd]arx dest, ptr
11654     //   cmp[wd] dest, oldval
11655     //   bne- midMBB
11656     // loop2MBB:
11657     //   st[bhwd]cx. newval, ptr
11658     //   bne- loopMBB
11659     //   b exitBB
11660     // midMBB:
11661     //   st[bhwd]cx. dest, ptr
11662     // exitBB:
11663     BB = loop1MBB;
11664     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11665     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11666         .addReg(oldval)
11667         .addReg(dest);
11668     BuildMI(BB, dl, TII->get(PPC::BCC))
11669         .addImm(PPC::PRED_NE)
11670         .addReg(PPC::CR0)
11671         .addMBB(midMBB);
11672     BB->addSuccessor(loop2MBB);
11673     BB->addSuccessor(midMBB);
11674 
11675     BB = loop2MBB;
11676     BuildMI(BB, dl, TII->get(StoreMnemonic))
11677         .addReg(newval)
11678         .addReg(ptrA)
11679         .addReg(ptrB);
11680     BuildMI(BB, dl, TII->get(PPC::BCC))
11681         .addImm(PPC::PRED_NE)
11682         .addReg(PPC::CR0)
11683         .addMBB(loop1MBB);
11684     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11685     BB->addSuccessor(loop1MBB);
11686     BB->addSuccessor(exitMBB);
11687 
11688     BB = midMBB;
11689     BuildMI(BB, dl, TII->get(StoreMnemonic))
11690         .addReg(dest)
11691         .addReg(ptrA)
11692         .addReg(ptrB);
11693     BB->addSuccessor(exitMBB);
11694 
11695     //  exitMBB:
11696     //   ...
11697     BB = exitMBB;
11698   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11699              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11700     // We must use 64-bit registers for addresses when targeting 64-bit,
11701     // since we're actually doing arithmetic on them.  Other registers
11702     // can be 32-bit.
11703     bool is64bit = Subtarget.isPPC64();
11704     bool isLittleEndian = Subtarget.isLittleEndian();
11705     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11706 
11707     Register dest = MI.getOperand(0).getReg();
11708     Register ptrA = MI.getOperand(1).getReg();
11709     Register ptrB = MI.getOperand(2).getReg();
11710     Register oldval = MI.getOperand(3).getReg();
11711     Register newval = MI.getOperand(4).getReg();
11712     DebugLoc dl = MI.getDebugLoc();
11713 
11714     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11715     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11716     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11717     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11718     F->insert(It, loop1MBB);
11719     F->insert(It, loop2MBB);
11720     F->insert(It, midMBB);
11721     F->insert(It, exitMBB);
11722     exitMBB->splice(exitMBB->begin(), BB,
11723                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11724     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11725 
11726     MachineRegisterInfo &RegInfo = F->getRegInfo();
11727     const TargetRegisterClass *RC =
11728         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11729     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11730 
11731     Register PtrReg = RegInfo.createVirtualRegister(RC);
11732     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11733     Register ShiftReg =
11734         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11735     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11736     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11737     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11738     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11739     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11740     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11741     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11742     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11743     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11744     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11745     Register Ptr1Reg;
11746     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11747     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11748     //  thisMBB:
11749     //   ...
11750     //   fallthrough --> loopMBB
11751     BB->addSuccessor(loop1MBB);
11752 
11753     // The 4-byte load must be aligned, while a char or short may be
11754     // anywhere in the word.  Hence all this nasty bookkeeping code.
11755     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11756     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11757     //   xori shift, shift1, 24 [16]
11758     //   rlwinm ptr, ptr1, 0, 0, 29
11759     //   slw newval2, newval, shift
11760     //   slw oldval2, oldval,shift
11761     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11762     //   slw mask, mask2, shift
11763     //   and newval3, newval2, mask
11764     //   and oldval3, oldval2, mask
11765     // loop1MBB:
11766     //   lwarx tmpDest, ptr
11767     //   and tmp, tmpDest, mask
11768     //   cmpw tmp, oldval3
11769     //   bne- midMBB
11770     // loop2MBB:
11771     //   andc tmp2, tmpDest, mask
11772     //   or tmp4, tmp2, newval3
11773     //   stwcx. tmp4, ptr
11774     //   bne- loop1MBB
11775     //   b exitBB
11776     // midMBB:
11777     //   stwcx. tmpDest, ptr
11778     // exitBB:
11779     //   srw dest, tmpDest, shift
11780     if (ptrA != ZeroReg) {
11781       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11782       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11783           .addReg(ptrA)
11784           .addReg(ptrB);
11785     } else {
11786       Ptr1Reg = ptrB;
11787     }
11788 
11789     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11790     // mode.
11791     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11792         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11793         .addImm(3)
11794         .addImm(27)
11795         .addImm(is8bit ? 28 : 27);
11796     if (!isLittleEndian)
11797       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11798           .addReg(Shift1Reg)
11799           .addImm(is8bit ? 24 : 16);
11800     if (is64bit)
11801       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11802           .addReg(Ptr1Reg)
11803           .addImm(0)
11804           .addImm(61);
11805     else
11806       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11807           .addReg(Ptr1Reg)
11808           .addImm(0)
11809           .addImm(0)
11810           .addImm(29);
11811     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11812         .addReg(newval)
11813         .addReg(ShiftReg);
11814     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11815         .addReg(oldval)
11816         .addReg(ShiftReg);
11817     if (is8bit)
11818       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11819     else {
11820       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11821       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11822           .addReg(Mask3Reg)
11823           .addImm(65535);
11824     }
11825     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11826         .addReg(Mask2Reg)
11827         .addReg(ShiftReg);
11828     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11829         .addReg(NewVal2Reg)
11830         .addReg(MaskReg);
11831     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11832         .addReg(OldVal2Reg)
11833         .addReg(MaskReg);
11834 
11835     BB = loop1MBB;
11836     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11837         .addReg(ZeroReg)
11838         .addReg(PtrReg);
11839     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11840         .addReg(TmpDestReg)
11841         .addReg(MaskReg);
11842     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11843         .addReg(TmpReg)
11844         .addReg(OldVal3Reg);
11845     BuildMI(BB, dl, TII->get(PPC::BCC))
11846         .addImm(PPC::PRED_NE)
11847         .addReg(PPC::CR0)
11848         .addMBB(midMBB);
11849     BB->addSuccessor(loop2MBB);
11850     BB->addSuccessor(midMBB);
11851 
11852     BB = loop2MBB;
11853     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11854         .addReg(TmpDestReg)
11855         .addReg(MaskReg);
11856     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11857         .addReg(Tmp2Reg)
11858         .addReg(NewVal3Reg);
11859     BuildMI(BB, dl, TII->get(PPC::STWCX))
11860         .addReg(Tmp4Reg)
11861         .addReg(ZeroReg)
11862         .addReg(PtrReg);
11863     BuildMI(BB, dl, TII->get(PPC::BCC))
11864         .addImm(PPC::PRED_NE)
11865         .addReg(PPC::CR0)
11866         .addMBB(loop1MBB);
11867     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11868     BB->addSuccessor(loop1MBB);
11869     BB->addSuccessor(exitMBB);
11870 
11871     BB = midMBB;
11872     BuildMI(BB, dl, TII->get(PPC::STWCX))
11873         .addReg(TmpDestReg)
11874         .addReg(ZeroReg)
11875         .addReg(PtrReg);
11876     BB->addSuccessor(exitMBB);
11877 
11878     //  exitMBB:
11879     //   ...
11880     BB = exitMBB;
11881     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11882         .addReg(TmpReg)
11883         .addReg(ShiftReg);
11884   } else if (MI.getOpcode() == PPC::FADDrtz) {
11885     // This pseudo performs an FADD with rounding mode temporarily forced
11886     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11887     // is not modeled at the SelectionDAG level.
11888     Register Dest = MI.getOperand(0).getReg();
11889     Register Src1 = MI.getOperand(1).getReg();
11890     Register Src2 = MI.getOperand(2).getReg();
11891     DebugLoc dl = MI.getDebugLoc();
11892 
11893     MachineRegisterInfo &RegInfo = F->getRegInfo();
11894     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11895 
11896     // Save FPSCR value.
11897     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11898 
11899     // Set rounding mode to round-to-zero.
11900     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
11901         .addImm(31)
11902         .addReg(PPC::RM, RegState::ImplicitDefine);
11903 
11904     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
11905         .addImm(30)
11906         .addReg(PPC::RM, RegState::ImplicitDefine);
11907 
11908     // Perform addition.
11909     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11910 
11911     // Restore FPSCR value.
11912     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11913   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11914              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
11915              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11916              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
11917     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11918                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
11919                           ? PPC::ANDI8_rec
11920                           : PPC::ANDI_rec;
11921     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11922                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
11923 
11924     MachineRegisterInfo &RegInfo = F->getRegInfo();
11925     Register Dest = RegInfo.createVirtualRegister(
11926         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11927 
11928     DebugLoc Dl = MI.getDebugLoc();
11929     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
11930         .addReg(MI.getOperand(1).getReg())
11931         .addImm(1);
11932     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11933             MI.getOperand(0).getReg())
11934         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
11935   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11936     DebugLoc Dl = MI.getDebugLoc();
11937     MachineRegisterInfo &RegInfo = F->getRegInfo();
11938     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11939     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11940     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11941             MI.getOperand(0).getReg())
11942         .addReg(CRReg);
11943   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11944     DebugLoc Dl = MI.getDebugLoc();
11945     unsigned Imm = MI.getOperand(1).getImm();
11946     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11947     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11948             MI.getOperand(0).getReg())
11949         .addReg(PPC::CR0EQ);
11950   } else if (MI.getOpcode() == PPC::SETRNDi) {
11951     DebugLoc dl = MI.getDebugLoc();
11952     Register OldFPSCRReg = MI.getOperand(0).getReg();
11953 
11954     // Save FPSCR value.
11955     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11956 
11957     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11958     // the following settings:
11959     //   00 Round to nearest
11960     //   01 Round to 0
11961     //   10 Round to +inf
11962     //   11 Round to -inf
11963 
11964     // When the operand is immediate, using the two least significant bits of
11965     // the immediate to set the bits 62:63 of FPSCR.
11966     unsigned Mode = MI.getOperand(1).getImm();
11967     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11968         .addImm(31)
11969         .addReg(PPC::RM, RegState::ImplicitDefine);
11970 
11971     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11972         .addImm(30)
11973         .addReg(PPC::RM, RegState::ImplicitDefine);
11974   } else if (MI.getOpcode() == PPC::SETRND) {
11975     DebugLoc dl = MI.getDebugLoc();
11976 
11977     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11978     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11979     // If the target doesn't have DirectMove, we should use stack to do the
11980     // conversion, because the target doesn't have the instructions like mtvsrd
11981     // or mfvsrd to do this conversion directly.
11982     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11983       if (Subtarget.hasDirectMove()) {
11984         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11985           .addReg(SrcReg);
11986       } else {
11987         // Use stack to do the register copy.
11988         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11989         MachineRegisterInfo &RegInfo = F->getRegInfo();
11990         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11991         if (RC == &PPC::F8RCRegClass) {
11992           // Copy register from F8RCRegClass to G8RCRegclass.
11993           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11994                  "Unsupported RegClass.");
11995 
11996           StoreOp = PPC::STFD;
11997           LoadOp = PPC::LD;
11998         } else {
11999           // Copy register from G8RCRegClass to F8RCRegclass.
12000           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12001                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12002                  "Unsupported RegClass.");
12003         }
12004 
12005         MachineFrameInfo &MFI = F->getFrameInfo();
12006         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12007 
12008         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12009             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12010             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12011             MFI.getObjectAlign(FrameIdx));
12012 
12013         // Store the SrcReg into the stack.
12014         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12015           .addReg(SrcReg)
12016           .addImm(0)
12017           .addFrameIndex(FrameIdx)
12018           .addMemOperand(MMOStore);
12019 
12020         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12021             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12022             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12023             MFI.getObjectAlign(FrameIdx));
12024 
12025         // Load from the stack where SrcReg is stored, and save to DestReg,
12026         // so we have done the RegClass conversion from RegClass::SrcReg to
12027         // RegClass::DestReg.
12028         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12029           .addImm(0)
12030           .addFrameIndex(FrameIdx)
12031           .addMemOperand(MMOLoad);
12032       }
12033     };
12034 
12035     Register OldFPSCRReg = MI.getOperand(0).getReg();
12036 
12037     // Save FPSCR value.
12038     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12039 
12040     // When the operand is gprc register, use two least significant bits of the
12041     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12042     //
12043     // copy OldFPSCRTmpReg, OldFPSCRReg
12044     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12045     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12046     // copy NewFPSCRReg, NewFPSCRTmpReg
12047     // mtfsf 255, NewFPSCRReg
12048     MachineOperand SrcOp = MI.getOperand(1);
12049     MachineRegisterInfo &RegInfo = F->getRegInfo();
12050     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12051 
12052     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12053 
12054     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12055     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12056 
12057     // The first operand of INSERT_SUBREG should be a register which has
12058     // subregisters, we only care about its RegClass, so we should use an
12059     // IMPLICIT_DEF register.
12060     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12061     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12062       .addReg(ImDefReg)
12063       .add(SrcOp)
12064       .addImm(1);
12065 
12066     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12067     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12068       .addReg(OldFPSCRTmpReg)
12069       .addReg(ExtSrcReg)
12070       .addImm(0)
12071       .addImm(62);
12072 
12073     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12074     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12075 
12076     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12077     // bits of FPSCR.
12078     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12079       .addImm(255)
12080       .addReg(NewFPSCRReg)
12081       .addImm(0)
12082       .addImm(0);
12083   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12084              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12085     return emitProbedAlloca(MI, BB);
12086   } else {
12087     llvm_unreachable("Unexpected instr type to insert");
12088   }
12089 
12090   MI.eraseFromParent(); // The pseudo instruction is gone now.
12091   return BB;
12092 }
12093 
12094 //===----------------------------------------------------------------------===//
12095 // Target Optimization Hooks
12096 //===----------------------------------------------------------------------===//
12097 
12098 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12099   // For the estimates, convergence is quadratic, so we essentially double the
12100   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12101   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12102   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12103   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12104   if (VT.getScalarType() == MVT::f64)
12105     RefinementSteps++;
12106   return RefinementSteps;
12107 }
12108 
12109 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12110                                            int Enabled, int &RefinementSteps,
12111                                            bool &UseOneConstNR,
12112                                            bool Reciprocal) const {
12113   EVT VT = Operand.getValueType();
12114   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12115       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12116       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12117       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12118     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12119       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12120 
12121     // The Newton-Raphson computation with a single constant does not provide
12122     // enough accuracy on some CPUs.
12123     UseOneConstNR = !Subtarget.needsTwoConstNR();
12124     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12125   }
12126   return SDValue();
12127 }
12128 
12129 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12130                                             int Enabled,
12131                                             int &RefinementSteps) const {
12132   EVT VT = Operand.getValueType();
12133   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12134       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12135       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12136       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12137     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12138       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12139     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12140   }
12141   return SDValue();
12142 }
12143 
12144 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12145   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12146   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12147   // enabled for division), this functionality is redundant with the default
12148   // combiner logic (once the division -> reciprocal/multiply transformation
12149   // has taken place). As a result, this matters more for older cores than for
12150   // newer ones.
12151 
12152   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12153   // reciprocal if there are two or more FDIVs (for embedded cores with only
12154   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12155   switch (Subtarget.getCPUDirective()) {
12156   default:
12157     return 3;
12158   case PPC::DIR_440:
12159   case PPC::DIR_A2:
12160   case PPC::DIR_E500:
12161   case PPC::DIR_E500mc:
12162   case PPC::DIR_E5500:
12163     return 2;
12164   }
12165 }
12166 
12167 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12168 // collapsed, and so we need to look through chains of them.
12169 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12170                                      int64_t& Offset, SelectionDAG &DAG) {
12171   if (DAG.isBaseWithConstantOffset(Loc)) {
12172     Base = Loc.getOperand(0);
12173     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12174 
12175     // The base might itself be a base plus an offset, and if so, accumulate
12176     // that as well.
12177     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12178   }
12179 }
12180 
12181 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12182                             unsigned Bytes, int Dist,
12183                             SelectionDAG &DAG) {
12184   if (VT.getSizeInBits() / 8 != Bytes)
12185     return false;
12186 
12187   SDValue BaseLoc = Base->getBasePtr();
12188   if (Loc.getOpcode() == ISD::FrameIndex) {
12189     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12190       return false;
12191     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12192     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12193     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12194     int FS  = MFI.getObjectSize(FI);
12195     int BFS = MFI.getObjectSize(BFI);
12196     if (FS != BFS || FS != (int)Bytes) return false;
12197     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12198   }
12199 
12200   SDValue Base1 = Loc, Base2 = BaseLoc;
12201   int64_t Offset1 = 0, Offset2 = 0;
12202   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12203   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12204   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12205     return true;
12206 
12207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12208   const GlobalValue *GV1 = nullptr;
12209   const GlobalValue *GV2 = nullptr;
12210   Offset1 = 0;
12211   Offset2 = 0;
12212   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12213   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12214   if (isGA1 && isGA2 && GV1 == GV2)
12215     return Offset1 == (Offset2 + Dist*Bytes);
12216   return false;
12217 }
12218 
12219 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12220 // not enforce equality of the chain operands.
12221 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12222                             unsigned Bytes, int Dist,
12223                             SelectionDAG &DAG) {
12224   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12225     EVT VT = LS->getMemoryVT();
12226     SDValue Loc = LS->getBasePtr();
12227     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12228   }
12229 
12230   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12231     EVT VT;
12232     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12233     default: return false;
12234     case Intrinsic::ppc_altivec_lvx:
12235     case Intrinsic::ppc_altivec_lvxl:
12236     case Intrinsic::ppc_vsx_lxvw4x:
12237     case Intrinsic::ppc_vsx_lxvw4x_be:
12238       VT = MVT::v4i32;
12239       break;
12240     case Intrinsic::ppc_vsx_lxvd2x:
12241     case Intrinsic::ppc_vsx_lxvd2x_be:
12242       VT = MVT::v2f64;
12243       break;
12244     case Intrinsic::ppc_altivec_lvebx:
12245       VT = MVT::i8;
12246       break;
12247     case Intrinsic::ppc_altivec_lvehx:
12248       VT = MVT::i16;
12249       break;
12250     case Intrinsic::ppc_altivec_lvewx:
12251       VT = MVT::i32;
12252       break;
12253     }
12254 
12255     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12256   }
12257 
12258   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12259     EVT VT;
12260     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12261     default: return false;
12262     case Intrinsic::ppc_altivec_stvx:
12263     case Intrinsic::ppc_altivec_stvxl:
12264     case Intrinsic::ppc_vsx_stxvw4x:
12265       VT = MVT::v4i32;
12266       break;
12267     case Intrinsic::ppc_vsx_stxvd2x:
12268       VT = MVT::v2f64;
12269       break;
12270     case Intrinsic::ppc_vsx_stxvw4x_be:
12271       VT = MVT::v4i32;
12272       break;
12273     case Intrinsic::ppc_vsx_stxvd2x_be:
12274       VT = MVT::v2f64;
12275       break;
12276     case Intrinsic::ppc_altivec_stvebx:
12277       VT = MVT::i8;
12278       break;
12279     case Intrinsic::ppc_altivec_stvehx:
12280       VT = MVT::i16;
12281       break;
12282     case Intrinsic::ppc_altivec_stvewx:
12283       VT = MVT::i32;
12284       break;
12285     }
12286 
12287     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12288   }
12289 
12290   return false;
12291 }
12292 
12293 // Return true is there is a nearyby consecutive load to the one provided
12294 // (regardless of alignment). We search up and down the chain, looking though
12295 // token factors and other loads (but nothing else). As a result, a true result
12296 // indicates that it is safe to create a new consecutive load adjacent to the
12297 // load provided.
12298 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12299   SDValue Chain = LD->getChain();
12300   EVT VT = LD->getMemoryVT();
12301 
12302   SmallSet<SDNode *, 16> LoadRoots;
12303   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12304   SmallSet<SDNode *, 16> Visited;
12305 
12306   // First, search up the chain, branching to follow all token-factor operands.
12307   // If we find a consecutive load, then we're done, otherwise, record all
12308   // nodes just above the top-level loads and token factors.
12309   while (!Queue.empty()) {
12310     SDNode *ChainNext = Queue.pop_back_val();
12311     if (!Visited.insert(ChainNext).second)
12312       continue;
12313 
12314     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12315       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12316         return true;
12317 
12318       if (!Visited.count(ChainLD->getChain().getNode()))
12319         Queue.push_back(ChainLD->getChain().getNode());
12320     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12321       for (const SDUse &O : ChainNext->ops())
12322         if (!Visited.count(O.getNode()))
12323           Queue.push_back(O.getNode());
12324     } else
12325       LoadRoots.insert(ChainNext);
12326   }
12327 
12328   // Second, search down the chain, starting from the top-level nodes recorded
12329   // in the first phase. These top-level nodes are the nodes just above all
12330   // loads and token factors. Starting with their uses, recursively look though
12331   // all loads (just the chain uses) and token factors to find a consecutive
12332   // load.
12333   Visited.clear();
12334   Queue.clear();
12335 
12336   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12337        IE = LoadRoots.end(); I != IE; ++I) {
12338     Queue.push_back(*I);
12339 
12340     while (!Queue.empty()) {
12341       SDNode *LoadRoot = Queue.pop_back_val();
12342       if (!Visited.insert(LoadRoot).second)
12343         continue;
12344 
12345       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12346         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12347           return true;
12348 
12349       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12350            UE = LoadRoot->use_end(); UI != UE; ++UI)
12351         if (((isa<MemSDNode>(*UI) &&
12352             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12353             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12354           Queue.push_back(*UI);
12355     }
12356   }
12357 
12358   return false;
12359 }
12360 
12361 /// This function is called when we have proved that a SETCC node can be replaced
12362 /// by subtraction (and other supporting instructions) so that the result of
12363 /// comparison is kept in a GPR instead of CR. This function is purely for
12364 /// codegen purposes and has some flags to guide the codegen process.
12365 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12366                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12367   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12368 
12369   // Zero extend the operands to the largest legal integer. Originally, they
12370   // must be of a strictly smaller size.
12371   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12372                          DAG.getConstant(Size, DL, MVT::i32));
12373   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12374                          DAG.getConstant(Size, DL, MVT::i32));
12375 
12376   // Swap if needed. Depends on the condition code.
12377   if (Swap)
12378     std::swap(Op0, Op1);
12379 
12380   // Subtract extended integers.
12381   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12382 
12383   // Move the sign bit to the least significant position and zero out the rest.
12384   // Now the least significant bit carries the result of original comparison.
12385   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12386                              DAG.getConstant(Size - 1, DL, MVT::i32));
12387   auto Final = Shifted;
12388 
12389   // Complement the result if needed. Based on the condition code.
12390   if (Complement)
12391     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12392                         DAG.getConstant(1, DL, MVT::i64));
12393 
12394   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12395 }
12396 
12397 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12398                                                   DAGCombinerInfo &DCI) const {
12399   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12400 
12401   SelectionDAG &DAG = DCI.DAG;
12402   SDLoc DL(N);
12403 
12404   // Size of integers being compared has a critical role in the following
12405   // analysis, so we prefer to do this when all types are legal.
12406   if (!DCI.isAfterLegalizeDAG())
12407     return SDValue();
12408 
12409   // If all users of SETCC extend its value to a legal integer type
12410   // then we replace SETCC with a subtraction
12411   for (SDNode::use_iterator UI = N->use_begin(),
12412        UE = N->use_end(); UI != UE; ++UI) {
12413     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12414       return SDValue();
12415   }
12416 
12417   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12418   auto OpSize = N->getOperand(0).getValueSizeInBits();
12419 
12420   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12421 
12422   if (OpSize < Size) {
12423     switch (CC) {
12424     default: break;
12425     case ISD::SETULT:
12426       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12427     case ISD::SETULE:
12428       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12429     case ISD::SETUGT:
12430       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12431     case ISD::SETUGE:
12432       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12433     }
12434   }
12435 
12436   return SDValue();
12437 }
12438 
12439 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12440                                                   DAGCombinerInfo &DCI) const {
12441   SelectionDAG &DAG = DCI.DAG;
12442   SDLoc dl(N);
12443 
12444   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12445   // If we're tracking CR bits, we need to be careful that we don't have:
12446   //   trunc(binary-ops(zext(x), zext(y)))
12447   // or
12448   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12449   // such that we're unnecessarily moving things into GPRs when it would be
12450   // better to keep them in CR bits.
12451 
12452   // Note that trunc here can be an actual i1 trunc, or can be the effective
12453   // truncation that comes from a setcc or select_cc.
12454   if (N->getOpcode() == ISD::TRUNCATE &&
12455       N->getValueType(0) != MVT::i1)
12456     return SDValue();
12457 
12458   if (N->getOperand(0).getValueType() != MVT::i32 &&
12459       N->getOperand(0).getValueType() != MVT::i64)
12460     return SDValue();
12461 
12462   if (N->getOpcode() == ISD::SETCC ||
12463       N->getOpcode() == ISD::SELECT_CC) {
12464     // If we're looking at a comparison, then we need to make sure that the
12465     // high bits (all except for the first) don't matter the result.
12466     ISD::CondCode CC =
12467       cast<CondCodeSDNode>(N->getOperand(
12468         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12469     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12470 
12471     if (ISD::isSignedIntSetCC(CC)) {
12472       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12473           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12474         return SDValue();
12475     } else if (ISD::isUnsignedIntSetCC(CC)) {
12476       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12477                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12478           !DAG.MaskedValueIsZero(N->getOperand(1),
12479                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12480         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12481                                              : SDValue());
12482     } else {
12483       // This is neither a signed nor an unsigned comparison, just make sure
12484       // that the high bits are equal.
12485       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12486       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12487 
12488       // We don't really care about what is known about the first bit (if
12489       // anything), so clear it in all masks prior to comparing them.
12490       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12491       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12492 
12493       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12494         return SDValue();
12495     }
12496   }
12497 
12498   // We now know that the higher-order bits are irrelevant, we just need to
12499   // make sure that all of the intermediate operations are bit operations, and
12500   // all inputs are extensions.
12501   if (N->getOperand(0).getOpcode() != ISD::AND &&
12502       N->getOperand(0).getOpcode() != ISD::OR  &&
12503       N->getOperand(0).getOpcode() != ISD::XOR &&
12504       N->getOperand(0).getOpcode() != ISD::SELECT &&
12505       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12506       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12507       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12508       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12509       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12510     return SDValue();
12511 
12512   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12513       N->getOperand(1).getOpcode() != ISD::AND &&
12514       N->getOperand(1).getOpcode() != ISD::OR  &&
12515       N->getOperand(1).getOpcode() != ISD::XOR &&
12516       N->getOperand(1).getOpcode() != ISD::SELECT &&
12517       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12518       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12519       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12520       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12521       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12522     return SDValue();
12523 
12524   SmallVector<SDValue, 4> Inputs;
12525   SmallVector<SDValue, 8> BinOps, PromOps;
12526   SmallPtrSet<SDNode *, 16> Visited;
12527 
12528   for (unsigned i = 0; i < 2; ++i) {
12529     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12530           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12531           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12532           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12533         isa<ConstantSDNode>(N->getOperand(i)))
12534       Inputs.push_back(N->getOperand(i));
12535     else
12536       BinOps.push_back(N->getOperand(i));
12537 
12538     if (N->getOpcode() == ISD::TRUNCATE)
12539       break;
12540   }
12541 
12542   // Visit all inputs, collect all binary operations (and, or, xor and
12543   // select) that are all fed by extensions.
12544   while (!BinOps.empty()) {
12545     SDValue BinOp = BinOps.back();
12546     BinOps.pop_back();
12547 
12548     if (!Visited.insert(BinOp.getNode()).second)
12549       continue;
12550 
12551     PromOps.push_back(BinOp);
12552 
12553     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12554       // The condition of the select is not promoted.
12555       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12556         continue;
12557       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12558         continue;
12559 
12560       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12561             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12562             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12563            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12564           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12565         Inputs.push_back(BinOp.getOperand(i));
12566       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12567                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12568                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12569                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12570                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12571                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12572                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12573                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12574                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12575         BinOps.push_back(BinOp.getOperand(i));
12576       } else {
12577         // We have an input that is not an extension or another binary
12578         // operation; we'll abort this transformation.
12579         return SDValue();
12580       }
12581     }
12582   }
12583 
12584   // Make sure that this is a self-contained cluster of operations (which
12585   // is not quite the same thing as saying that everything has only one
12586   // use).
12587   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12588     if (isa<ConstantSDNode>(Inputs[i]))
12589       continue;
12590 
12591     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12592                               UE = Inputs[i].getNode()->use_end();
12593          UI != UE; ++UI) {
12594       SDNode *User = *UI;
12595       if (User != N && !Visited.count(User))
12596         return SDValue();
12597 
12598       // Make sure that we're not going to promote the non-output-value
12599       // operand(s) or SELECT or SELECT_CC.
12600       // FIXME: Although we could sometimes handle this, and it does occur in
12601       // practice that one of the condition inputs to the select is also one of
12602       // the outputs, we currently can't deal with this.
12603       if (User->getOpcode() == ISD::SELECT) {
12604         if (User->getOperand(0) == Inputs[i])
12605           return SDValue();
12606       } else if (User->getOpcode() == ISD::SELECT_CC) {
12607         if (User->getOperand(0) == Inputs[i] ||
12608             User->getOperand(1) == Inputs[i])
12609           return SDValue();
12610       }
12611     }
12612   }
12613 
12614   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12615     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12616                               UE = PromOps[i].getNode()->use_end();
12617          UI != UE; ++UI) {
12618       SDNode *User = *UI;
12619       if (User != N && !Visited.count(User))
12620         return SDValue();
12621 
12622       // Make sure that we're not going to promote the non-output-value
12623       // operand(s) or SELECT or SELECT_CC.
12624       // FIXME: Although we could sometimes handle this, and it does occur in
12625       // practice that one of the condition inputs to the select is also one of
12626       // the outputs, we currently can't deal with this.
12627       if (User->getOpcode() == ISD::SELECT) {
12628         if (User->getOperand(0) == PromOps[i])
12629           return SDValue();
12630       } else if (User->getOpcode() == ISD::SELECT_CC) {
12631         if (User->getOperand(0) == PromOps[i] ||
12632             User->getOperand(1) == PromOps[i])
12633           return SDValue();
12634       }
12635     }
12636   }
12637 
12638   // Replace all inputs with the extension operand.
12639   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12640     // Constants may have users outside the cluster of to-be-promoted nodes,
12641     // and so we need to replace those as we do the promotions.
12642     if (isa<ConstantSDNode>(Inputs[i]))
12643       continue;
12644     else
12645       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12646   }
12647 
12648   std::list<HandleSDNode> PromOpHandles;
12649   for (auto &PromOp : PromOps)
12650     PromOpHandles.emplace_back(PromOp);
12651 
12652   // Replace all operations (these are all the same, but have a different
12653   // (i1) return type). DAG.getNode will validate that the types of
12654   // a binary operator match, so go through the list in reverse so that
12655   // we've likely promoted both operands first. Any intermediate truncations or
12656   // extensions disappear.
12657   while (!PromOpHandles.empty()) {
12658     SDValue PromOp = PromOpHandles.back().getValue();
12659     PromOpHandles.pop_back();
12660 
12661     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12662         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12663         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12664         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12665       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12666           PromOp.getOperand(0).getValueType() != MVT::i1) {
12667         // The operand is not yet ready (see comment below).
12668         PromOpHandles.emplace_front(PromOp);
12669         continue;
12670       }
12671 
12672       SDValue RepValue = PromOp.getOperand(0);
12673       if (isa<ConstantSDNode>(RepValue))
12674         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12675 
12676       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12677       continue;
12678     }
12679 
12680     unsigned C;
12681     switch (PromOp.getOpcode()) {
12682     default:             C = 0; break;
12683     case ISD::SELECT:    C = 1; break;
12684     case ISD::SELECT_CC: C = 2; break;
12685     }
12686 
12687     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12688          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12689         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12690          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12691       // The to-be-promoted operands of this node have not yet been
12692       // promoted (this should be rare because we're going through the
12693       // list backward, but if one of the operands has several users in
12694       // this cluster of to-be-promoted nodes, it is possible).
12695       PromOpHandles.emplace_front(PromOp);
12696       continue;
12697     }
12698 
12699     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12700                                 PromOp.getNode()->op_end());
12701 
12702     // If there are any constant inputs, make sure they're replaced now.
12703     for (unsigned i = 0; i < 2; ++i)
12704       if (isa<ConstantSDNode>(Ops[C+i]))
12705         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12706 
12707     DAG.ReplaceAllUsesOfValueWith(PromOp,
12708       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12709   }
12710 
12711   // Now we're left with the initial truncation itself.
12712   if (N->getOpcode() == ISD::TRUNCATE)
12713     return N->getOperand(0);
12714 
12715   // Otherwise, this is a comparison. The operands to be compared have just
12716   // changed type (to i1), but everything else is the same.
12717   return SDValue(N, 0);
12718 }
12719 
12720 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12721                                                   DAGCombinerInfo &DCI) const {
12722   SelectionDAG &DAG = DCI.DAG;
12723   SDLoc dl(N);
12724 
12725   // If we're tracking CR bits, we need to be careful that we don't have:
12726   //   zext(binary-ops(trunc(x), trunc(y)))
12727   // or
12728   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12729   // such that we're unnecessarily moving things into CR bits that can more
12730   // efficiently stay in GPRs. Note that if we're not certain that the high
12731   // bits are set as required by the final extension, we still may need to do
12732   // some masking to get the proper behavior.
12733 
12734   // This same functionality is important on PPC64 when dealing with
12735   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12736   // the return values of functions. Because it is so similar, it is handled
12737   // here as well.
12738 
12739   if (N->getValueType(0) != MVT::i32 &&
12740       N->getValueType(0) != MVT::i64)
12741     return SDValue();
12742 
12743   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12744         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12745     return SDValue();
12746 
12747   if (N->getOperand(0).getOpcode() != ISD::AND &&
12748       N->getOperand(0).getOpcode() != ISD::OR  &&
12749       N->getOperand(0).getOpcode() != ISD::XOR &&
12750       N->getOperand(0).getOpcode() != ISD::SELECT &&
12751       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12752     return SDValue();
12753 
12754   SmallVector<SDValue, 4> Inputs;
12755   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12756   SmallPtrSet<SDNode *, 16> Visited;
12757 
12758   // Visit all inputs, collect all binary operations (and, or, xor and
12759   // select) that are all fed by truncations.
12760   while (!BinOps.empty()) {
12761     SDValue BinOp = BinOps.back();
12762     BinOps.pop_back();
12763 
12764     if (!Visited.insert(BinOp.getNode()).second)
12765       continue;
12766 
12767     PromOps.push_back(BinOp);
12768 
12769     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12770       // The condition of the select is not promoted.
12771       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12772         continue;
12773       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12774         continue;
12775 
12776       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12777           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12778         Inputs.push_back(BinOp.getOperand(i));
12779       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12780                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12781                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12782                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12783                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12784         BinOps.push_back(BinOp.getOperand(i));
12785       } else {
12786         // We have an input that is not a truncation or another binary
12787         // operation; we'll abort this transformation.
12788         return SDValue();
12789       }
12790     }
12791   }
12792 
12793   // The operands of a select that must be truncated when the select is
12794   // promoted because the operand is actually part of the to-be-promoted set.
12795   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12796 
12797   // Make sure that this is a self-contained cluster of operations (which
12798   // is not quite the same thing as saying that everything has only one
12799   // use).
12800   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12801     if (isa<ConstantSDNode>(Inputs[i]))
12802       continue;
12803 
12804     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12805                               UE = Inputs[i].getNode()->use_end();
12806          UI != UE; ++UI) {
12807       SDNode *User = *UI;
12808       if (User != N && !Visited.count(User))
12809         return SDValue();
12810 
12811       // If we're going to promote the non-output-value operand(s) or SELECT or
12812       // SELECT_CC, record them for truncation.
12813       if (User->getOpcode() == ISD::SELECT) {
12814         if (User->getOperand(0) == Inputs[i])
12815           SelectTruncOp[0].insert(std::make_pair(User,
12816                                     User->getOperand(0).getValueType()));
12817       } else if (User->getOpcode() == ISD::SELECT_CC) {
12818         if (User->getOperand(0) == Inputs[i])
12819           SelectTruncOp[0].insert(std::make_pair(User,
12820                                     User->getOperand(0).getValueType()));
12821         if (User->getOperand(1) == Inputs[i])
12822           SelectTruncOp[1].insert(std::make_pair(User,
12823                                     User->getOperand(1).getValueType()));
12824       }
12825     }
12826   }
12827 
12828   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12829     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12830                               UE = PromOps[i].getNode()->use_end();
12831          UI != UE; ++UI) {
12832       SDNode *User = *UI;
12833       if (User != N && !Visited.count(User))
12834         return SDValue();
12835 
12836       // If we're going to promote the non-output-value operand(s) or SELECT or
12837       // SELECT_CC, record them for truncation.
12838       if (User->getOpcode() == ISD::SELECT) {
12839         if (User->getOperand(0) == PromOps[i])
12840           SelectTruncOp[0].insert(std::make_pair(User,
12841                                     User->getOperand(0).getValueType()));
12842       } else if (User->getOpcode() == ISD::SELECT_CC) {
12843         if (User->getOperand(0) == PromOps[i])
12844           SelectTruncOp[0].insert(std::make_pair(User,
12845                                     User->getOperand(0).getValueType()));
12846         if (User->getOperand(1) == PromOps[i])
12847           SelectTruncOp[1].insert(std::make_pair(User,
12848                                     User->getOperand(1).getValueType()));
12849       }
12850     }
12851   }
12852 
12853   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12854   bool ReallyNeedsExt = false;
12855   if (N->getOpcode() != ISD::ANY_EXTEND) {
12856     // If all of the inputs are not already sign/zero extended, then
12857     // we'll still need to do that at the end.
12858     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12859       if (isa<ConstantSDNode>(Inputs[i]))
12860         continue;
12861 
12862       unsigned OpBits =
12863         Inputs[i].getOperand(0).getValueSizeInBits();
12864       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12865 
12866       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12867            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12868                                   APInt::getHighBitsSet(OpBits,
12869                                                         OpBits-PromBits))) ||
12870           (N->getOpcode() == ISD::SIGN_EXTEND &&
12871            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12872              (OpBits-(PromBits-1)))) {
12873         ReallyNeedsExt = true;
12874         break;
12875       }
12876     }
12877   }
12878 
12879   // Replace all inputs, either with the truncation operand, or a
12880   // truncation or extension to the final output type.
12881   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12882     // Constant inputs need to be replaced with the to-be-promoted nodes that
12883     // use them because they might have users outside of the cluster of
12884     // promoted nodes.
12885     if (isa<ConstantSDNode>(Inputs[i]))
12886       continue;
12887 
12888     SDValue InSrc = Inputs[i].getOperand(0);
12889     if (Inputs[i].getValueType() == N->getValueType(0))
12890       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12891     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12892       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12893         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12894     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12895       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12896         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12897     else
12898       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12899         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12900   }
12901 
12902   std::list<HandleSDNode> PromOpHandles;
12903   for (auto &PromOp : PromOps)
12904     PromOpHandles.emplace_back(PromOp);
12905 
12906   // Replace all operations (these are all the same, but have a different
12907   // (promoted) return type). DAG.getNode will validate that the types of
12908   // a binary operator match, so go through the list in reverse so that
12909   // we've likely promoted both operands first.
12910   while (!PromOpHandles.empty()) {
12911     SDValue PromOp = PromOpHandles.back().getValue();
12912     PromOpHandles.pop_back();
12913 
12914     unsigned C;
12915     switch (PromOp.getOpcode()) {
12916     default:             C = 0; break;
12917     case ISD::SELECT:    C = 1; break;
12918     case ISD::SELECT_CC: C = 2; break;
12919     }
12920 
12921     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12922          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12923         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12924          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12925       // The to-be-promoted operands of this node have not yet been
12926       // promoted (this should be rare because we're going through the
12927       // list backward, but if one of the operands has several users in
12928       // this cluster of to-be-promoted nodes, it is possible).
12929       PromOpHandles.emplace_front(PromOp);
12930       continue;
12931     }
12932 
12933     // For SELECT and SELECT_CC nodes, we do a similar check for any
12934     // to-be-promoted comparison inputs.
12935     if (PromOp.getOpcode() == ISD::SELECT ||
12936         PromOp.getOpcode() == ISD::SELECT_CC) {
12937       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12938            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12939           (SelectTruncOp[1].count(PromOp.getNode()) &&
12940            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12941         PromOpHandles.emplace_front(PromOp);
12942         continue;
12943       }
12944     }
12945 
12946     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12947                                 PromOp.getNode()->op_end());
12948 
12949     // If this node has constant inputs, then they'll need to be promoted here.
12950     for (unsigned i = 0; i < 2; ++i) {
12951       if (!isa<ConstantSDNode>(Ops[C+i]))
12952         continue;
12953       if (Ops[C+i].getValueType() == N->getValueType(0))
12954         continue;
12955 
12956       if (N->getOpcode() == ISD::SIGN_EXTEND)
12957         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12958       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12959         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12960       else
12961         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12962     }
12963 
12964     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12965     // truncate them again to the original value type.
12966     if (PromOp.getOpcode() == ISD::SELECT ||
12967         PromOp.getOpcode() == ISD::SELECT_CC) {
12968       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12969       if (SI0 != SelectTruncOp[0].end())
12970         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12971       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12972       if (SI1 != SelectTruncOp[1].end())
12973         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12974     }
12975 
12976     DAG.ReplaceAllUsesOfValueWith(PromOp,
12977       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12978   }
12979 
12980   // Now we're left with the initial extension itself.
12981   if (!ReallyNeedsExt)
12982     return N->getOperand(0);
12983 
12984   // To zero extend, just mask off everything except for the first bit (in the
12985   // i1 case).
12986   if (N->getOpcode() == ISD::ZERO_EXTEND)
12987     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12988                        DAG.getConstant(APInt::getLowBitsSet(
12989                                          N->getValueSizeInBits(0), PromBits),
12990                                        dl, N->getValueType(0)));
12991 
12992   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12993          "Invalid extension type");
12994   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12995   SDValue ShiftCst =
12996       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12997   return DAG.getNode(
12998       ISD::SRA, dl, N->getValueType(0),
12999       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13000       ShiftCst);
13001 }
13002 
13003 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13004                                         DAGCombinerInfo &DCI) const {
13005   assert(N->getOpcode() == ISD::SETCC &&
13006          "Should be called with a SETCC node");
13007 
13008   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13009   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13010     SDValue LHS = N->getOperand(0);
13011     SDValue RHS = N->getOperand(1);
13012 
13013     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13014     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13015         LHS.hasOneUse())
13016       std::swap(LHS, RHS);
13017 
13018     // x == 0-y --> x+y == 0
13019     // x != 0-y --> x+y != 0
13020     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13021         RHS.hasOneUse()) {
13022       SDLoc DL(N);
13023       SelectionDAG &DAG = DCI.DAG;
13024       EVT VT = N->getValueType(0);
13025       EVT OpVT = LHS.getValueType();
13026       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13027       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13028     }
13029   }
13030 
13031   return DAGCombineTruncBoolExt(N, DCI);
13032 }
13033 
13034 // Is this an extending load from an f32 to an f64?
13035 static bool isFPExtLoad(SDValue Op) {
13036   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13037     return LD->getExtensionType() == ISD::EXTLOAD &&
13038       Op.getValueType() == MVT::f64;
13039   return false;
13040 }
13041 
13042 /// Reduces the number of fp-to-int conversion when building a vector.
13043 ///
13044 /// If this vector is built out of floating to integer conversions,
13045 /// transform it to a vector built out of floating point values followed by a
13046 /// single floating to integer conversion of the vector.
13047 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13048 /// becomes (fptosi (build_vector ($A, $B, ...)))
13049 SDValue PPCTargetLowering::
13050 combineElementTruncationToVectorTruncation(SDNode *N,
13051                                            DAGCombinerInfo &DCI) const {
13052   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13053          "Should be called with a BUILD_VECTOR node");
13054 
13055   SelectionDAG &DAG = DCI.DAG;
13056   SDLoc dl(N);
13057 
13058   SDValue FirstInput = N->getOperand(0);
13059   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13060          "The input operand must be an fp-to-int conversion.");
13061 
13062   // This combine happens after legalization so the fp_to_[su]i nodes are
13063   // already converted to PPCSISD nodes.
13064   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13065   if (FirstConversion == PPCISD::FCTIDZ ||
13066       FirstConversion == PPCISD::FCTIDUZ ||
13067       FirstConversion == PPCISD::FCTIWZ ||
13068       FirstConversion == PPCISD::FCTIWUZ) {
13069     bool IsSplat = true;
13070     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13071       FirstConversion == PPCISD::FCTIWUZ;
13072     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13073     SmallVector<SDValue, 4> Ops;
13074     EVT TargetVT = N->getValueType(0);
13075     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13076       SDValue NextOp = N->getOperand(i);
13077       if (NextOp.getOpcode() != PPCISD::MFVSR)
13078         return SDValue();
13079       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13080       if (NextConversion != FirstConversion)
13081         return SDValue();
13082       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13083       // This is not valid if the input was originally double precision. It is
13084       // also not profitable to do unless this is an extending load in which
13085       // case doing this combine will allow us to combine consecutive loads.
13086       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13087         return SDValue();
13088       if (N->getOperand(i) != FirstInput)
13089         IsSplat = false;
13090     }
13091 
13092     // If this is a splat, we leave it as-is since there will be only a single
13093     // fp-to-int conversion followed by a splat of the integer. This is better
13094     // for 32-bit and smaller ints and neutral for 64-bit ints.
13095     if (IsSplat)
13096       return SDValue();
13097 
13098     // Now that we know we have the right type of node, get its operands
13099     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13100       SDValue In = N->getOperand(i).getOperand(0);
13101       if (Is32Bit) {
13102         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13103         // here, we know that all inputs are extending loads so this is safe).
13104         if (In.isUndef())
13105           Ops.push_back(DAG.getUNDEF(SrcVT));
13106         else {
13107           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13108                                       MVT::f32, In.getOperand(0),
13109                                       DAG.getIntPtrConstant(1, dl));
13110           Ops.push_back(Trunc);
13111         }
13112       } else
13113         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13114     }
13115 
13116     unsigned Opcode;
13117     if (FirstConversion == PPCISD::FCTIDZ ||
13118         FirstConversion == PPCISD::FCTIWZ)
13119       Opcode = ISD::FP_TO_SINT;
13120     else
13121       Opcode = ISD::FP_TO_UINT;
13122 
13123     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13124     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13125     return DAG.getNode(Opcode, dl, TargetVT, BV);
13126   }
13127   return SDValue();
13128 }
13129 
13130 /// Reduce the number of loads when building a vector.
13131 ///
13132 /// Building a vector out of multiple loads can be converted to a load
13133 /// of the vector type if the loads are consecutive. If the loads are
13134 /// consecutive but in descending order, a shuffle is added at the end
13135 /// to reorder the vector.
13136 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13137   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13138          "Should be called with a BUILD_VECTOR node");
13139 
13140   SDLoc dl(N);
13141 
13142   // Return early for non byte-sized type, as they can't be consecutive.
13143   if (!N->getValueType(0).getVectorElementType().isByteSized())
13144     return SDValue();
13145 
13146   bool InputsAreConsecutiveLoads = true;
13147   bool InputsAreReverseConsecutive = true;
13148   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13149   SDValue FirstInput = N->getOperand(0);
13150   bool IsRoundOfExtLoad = false;
13151 
13152   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13153       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13154     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13155     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13156   }
13157   // Not a build vector of (possibly fp_rounded) loads.
13158   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13159       N->getNumOperands() == 1)
13160     return SDValue();
13161 
13162   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13163     // If any inputs are fp_round(extload), they all must be.
13164     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13165       return SDValue();
13166 
13167     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13168       N->getOperand(i);
13169     if (NextInput.getOpcode() != ISD::LOAD)
13170       return SDValue();
13171 
13172     SDValue PreviousInput =
13173       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13174     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13175     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13176 
13177     // If any inputs are fp_round(extload), they all must be.
13178     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13179       return SDValue();
13180 
13181     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13182       InputsAreConsecutiveLoads = false;
13183     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13184       InputsAreReverseConsecutive = false;
13185 
13186     // Exit early if the loads are neither consecutive nor reverse consecutive.
13187     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13188       return SDValue();
13189   }
13190 
13191   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13192          "The loads cannot be both consecutive and reverse consecutive.");
13193 
13194   SDValue FirstLoadOp =
13195     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13196   SDValue LastLoadOp =
13197     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13198                        N->getOperand(N->getNumOperands()-1);
13199 
13200   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13201   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13202   if (InputsAreConsecutiveLoads) {
13203     assert(LD1 && "Input needs to be a LoadSDNode.");
13204     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13205                        LD1->getBasePtr(), LD1->getPointerInfo(),
13206                        LD1->getAlignment());
13207   }
13208   if (InputsAreReverseConsecutive) {
13209     assert(LDL && "Input needs to be a LoadSDNode.");
13210     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13211                                LDL->getBasePtr(), LDL->getPointerInfo(),
13212                                LDL->getAlignment());
13213     SmallVector<int, 16> Ops;
13214     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13215       Ops.push_back(i);
13216 
13217     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13218                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13219   }
13220   return SDValue();
13221 }
13222 
13223 // This function adds the required vector_shuffle needed to get
13224 // the elements of the vector extract in the correct position
13225 // as specified by the CorrectElems encoding.
13226 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13227                                       SDValue Input, uint64_t Elems,
13228                                       uint64_t CorrectElems) {
13229   SDLoc dl(N);
13230 
13231   unsigned NumElems = Input.getValueType().getVectorNumElements();
13232   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13233 
13234   // Knowing the element indices being extracted from the original
13235   // vector and the order in which they're being inserted, just put
13236   // them at element indices required for the instruction.
13237   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13238     if (DAG.getDataLayout().isLittleEndian())
13239       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13240     else
13241       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13242     CorrectElems = CorrectElems >> 8;
13243     Elems = Elems >> 8;
13244   }
13245 
13246   SDValue Shuffle =
13247       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13248                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13249 
13250   EVT VT = N->getValueType(0);
13251   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13252 
13253   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13254                                Input.getValueType().getVectorElementType(),
13255                                VT.getVectorNumElements());
13256   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13257                      DAG.getValueType(ExtVT));
13258 }
13259 
13260 // Look for build vector patterns where input operands come from sign
13261 // extended vector_extract elements of specific indices. If the correct indices
13262 // aren't used, add a vector shuffle to fix up the indices and create
13263 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13264 // during instruction selection.
13265 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13266   // This array encodes the indices that the vector sign extend instructions
13267   // extract from when extending from one type to another for both BE and LE.
13268   // The right nibble of each byte corresponds to the LE incides.
13269   // and the left nibble of each byte corresponds to the BE incides.
13270   // For example: 0x3074B8FC  byte->word
13271   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13272   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13273   // For example: 0x000070F8  byte->double word
13274   // For LE: the allowed indices are: 0x0,0x8
13275   // For BE: the allowed indices are: 0x7,0xF
13276   uint64_t TargetElems[] = {
13277       0x3074B8FC, // b->w
13278       0x000070F8, // b->d
13279       0x10325476, // h->w
13280       0x00003074, // h->d
13281       0x00001032, // w->d
13282   };
13283 
13284   uint64_t Elems = 0;
13285   int Index;
13286   SDValue Input;
13287 
13288   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13289     if (!Op)
13290       return false;
13291     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13292         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13293       return false;
13294 
13295     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13296     // of the right width.
13297     SDValue Extract = Op.getOperand(0);
13298     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13299       Extract = Extract.getOperand(0);
13300     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13301       return false;
13302 
13303     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13304     if (!ExtOp)
13305       return false;
13306 
13307     Index = ExtOp->getZExtValue();
13308     if (Input && Input != Extract.getOperand(0))
13309       return false;
13310 
13311     if (!Input)
13312       Input = Extract.getOperand(0);
13313 
13314     Elems = Elems << 8;
13315     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13316     Elems |= Index;
13317 
13318     return true;
13319   };
13320 
13321   // If the build vector operands aren't sign extended vector extracts,
13322   // of the same input vector, then return.
13323   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13324     if (!isSExtOfVecExtract(N->getOperand(i))) {
13325       return SDValue();
13326     }
13327   }
13328 
13329   // If the vector extract indicies are not correct, add the appropriate
13330   // vector_shuffle.
13331   int TgtElemArrayIdx;
13332   int InputSize = Input.getValueType().getScalarSizeInBits();
13333   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13334   if (InputSize + OutputSize == 40)
13335     TgtElemArrayIdx = 0;
13336   else if (InputSize + OutputSize == 72)
13337     TgtElemArrayIdx = 1;
13338   else if (InputSize + OutputSize == 48)
13339     TgtElemArrayIdx = 2;
13340   else if (InputSize + OutputSize == 80)
13341     TgtElemArrayIdx = 3;
13342   else if (InputSize + OutputSize == 96)
13343     TgtElemArrayIdx = 4;
13344   else
13345     return SDValue();
13346 
13347   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13348   CorrectElems = DAG.getDataLayout().isLittleEndian()
13349                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13350                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13351   if (Elems != CorrectElems) {
13352     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13353   }
13354 
13355   // Regular lowering will catch cases where a shuffle is not needed.
13356   return SDValue();
13357 }
13358 
13359 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13360                                                  DAGCombinerInfo &DCI) const {
13361   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13362          "Should be called with a BUILD_VECTOR node");
13363 
13364   SelectionDAG &DAG = DCI.DAG;
13365   SDLoc dl(N);
13366 
13367   if (!Subtarget.hasVSX())
13368     return SDValue();
13369 
13370   // The target independent DAG combiner will leave a build_vector of
13371   // float-to-int conversions intact. We can generate MUCH better code for
13372   // a float-to-int conversion of a vector of floats.
13373   SDValue FirstInput = N->getOperand(0);
13374   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13375     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13376     if (Reduced)
13377       return Reduced;
13378   }
13379 
13380   // If we're building a vector out of consecutive loads, just load that
13381   // vector type.
13382   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13383   if (Reduced)
13384     return Reduced;
13385 
13386   // If we're building a vector out of extended elements from another vector
13387   // we have P9 vector integer extend instructions. The code assumes legal
13388   // input types (i.e. it can't handle things like v4i16) so do not run before
13389   // legalization.
13390   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13391     Reduced = combineBVOfVecSExt(N, DAG);
13392     if (Reduced)
13393       return Reduced;
13394   }
13395 
13396 
13397   if (N->getValueType(0) != MVT::v2f64)
13398     return SDValue();
13399 
13400   // Looking for:
13401   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13402   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13403       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13404     return SDValue();
13405   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13406       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13407     return SDValue();
13408   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13409     return SDValue();
13410 
13411   SDValue Ext1 = FirstInput.getOperand(0);
13412   SDValue Ext2 = N->getOperand(1).getOperand(0);
13413   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13414      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13415     return SDValue();
13416 
13417   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13418   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13419   if (!Ext1Op || !Ext2Op)
13420     return SDValue();
13421   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13422       Ext1.getOperand(0) != Ext2.getOperand(0))
13423     return SDValue();
13424 
13425   int FirstElem = Ext1Op->getZExtValue();
13426   int SecondElem = Ext2Op->getZExtValue();
13427   int SubvecIdx;
13428   if (FirstElem == 0 && SecondElem == 1)
13429     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13430   else if (FirstElem == 2 && SecondElem == 3)
13431     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13432   else
13433     return SDValue();
13434 
13435   SDValue SrcVec = Ext1.getOperand(0);
13436   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13437     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13438   return DAG.getNode(NodeType, dl, MVT::v2f64,
13439                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13440 }
13441 
13442 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13443                                               DAGCombinerInfo &DCI) const {
13444   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13445           N->getOpcode() == ISD::UINT_TO_FP) &&
13446          "Need an int -> FP conversion node here");
13447 
13448   if (useSoftFloat() || !Subtarget.has64BitSupport())
13449     return SDValue();
13450 
13451   SelectionDAG &DAG = DCI.DAG;
13452   SDLoc dl(N);
13453   SDValue Op(N, 0);
13454 
13455   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13456   // from the hardware.
13457   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13458     return SDValue();
13459   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13460       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13461     return SDValue();
13462 
13463   SDValue FirstOperand(Op.getOperand(0));
13464   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13465     (FirstOperand.getValueType() == MVT::i8 ||
13466      FirstOperand.getValueType() == MVT::i16);
13467   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13468     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13469     bool DstDouble = Op.getValueType() == MVT::f64;
13470     unsigned ConvOp = Signed ?
13471       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13472       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13473     SDValue WidthConst =
13474       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13475                             dl, false);
13476     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13477     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13478     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13479                                          DAG.getVTList(MVT::f64, MVT::Other),
13480                                          Ops, MVT::i8, LDN->getMemOperand());
13481 
13482     // For signed conversion, we need to sign-extend the value in the VSR
13483     if (Signed) {
13484       SDValue ExtOps[] = { Ld, WidthConst };
13485       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13486       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13487     } else
13488       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13489   }
13490 
13491 
13492   // For i32 intermediate values, unfortunately, the conversion functions
13493   // leave the upper 32 bits of the value are undefined. Within the set of
13494   // scalar instructions, we have no method for zero- or sign-extending the
13495   // value. Thus, we cannot handle i32 intermediate values here.
13496   if (Op.getOperand(0).getValueType() == MVT::i32)
13497     return SDValue();
13498 
13499   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13500          "UINT_TO_FP is supported only with FPCVT");
13501 
13502   // If we have FCFIDS, then use it when converting to single-precision.
13503   // Otherwise, convert to double-precision and then round.
13504   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13505                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13506                                                             : PPCISD::FCFIDS)
13507                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13508                                                             : PPCISD::FCFID);
13509   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13510                   ? MVT::f32
13511                   : MVT::f64;
13512 
13513   // If we're converting from a float, to an int, and back to a float again,
13514   // then we don't need the store/load pair at all.
13515   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13516        Subtarget.hasFPCVT()) ||
13517       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13518     SDValue Src = Op.getOperand(0).getOperand(0);
13519     if (Src.getValueType() == MVT::f32) {
13520       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13521       DCI.AddToWorklist(Src.getNode());
13522     } else if (Src.getValueType() != MVT::f64) {
13523       // Make sure that we don't pick up a ppc_fp128 source value.
13524       return SDValue();
13525     }
13526 
13527     unsigned FCTOp =
13528       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13529                                                         PPCISD::FCTIDUZ;
13530 
13531     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13532     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13533 
13534     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13535       FP = DAG.getNode(ISD::FP_ROUND, dl,
13536                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13537       DCI.AddToWorklist(FP.getNode());
13538     }
13539 
13540     return FP;
13541   }
13542 
13543   return SDValue();
13544 }
13545 
13546 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13547 // builtins) into loads with swaps.
13548 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13549                                               DAGCombinerInfo &DCI) const {
13550   SelectionDAG &DAG = DCI.DAG;
13551   SDLoc dl(N);
13552   SDValue Chain;
13553   SDValue Base;
13554   MachineMemOperand *MMO;
13555 
13556   switch (N->getOpcode()) {
13557   default:
13558     llvm_unreachable("Unexpected opcode for little endian VSX load");
13559   case ISD::LOAD: {
13560     LoadSDNode *LD = cast<LoadSDNode>(N);
13561     Chain = LD->getChain();
13562     Base = LD->getBasePtr();
13563     MMO = LD->getMemOperand();
13564     // If the MMO suggests this isn't a load of a full vector, leave
13565     // things alone.  For a built-in, we have to make the change for
13566     // correctness, so if there is a size problem that will be a bug.
13567     if (MMO->getSize() < 16)
13568       return SDValue();
13569     break;
13570   }
13571   case ISD::INTRINSIC_W_CHAIN: {
13572     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13573     Chain = Intrin->getChain();
13574     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13575     // us what we want. Get operand 2 instead.
13576     Base = Intrin->getOperand(2);
13577     MMO = Intrin->getMemOperand();
13578     break;
13579   }
13580   }
13581 
13582   MVT VecTy = N->getValueType(0).getSimpleVT();
13583 
13584   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13585   // aligned and the type is a vector with elements up to 4 bytes
13586   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13587       VecTy.getScalarSizeInBits() <= 32) {
13588     return SDValue();
13589   }
13590 
13591   SDValue LoadOps[] = { Chain, Base };
13592   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13593                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13594                                          LoadOps, MVT::v2f64, MMO);
13595 
13596   DCI.AddToWorklist(Load.getNode());
13597   Chain = Load.getValue(1);
13598   SDValue Swap = DAG.getNode(
13599       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13600   DCI.AddToWorklist(Swap.getNode());
13601 
13602   // Add a bitcast if the resulting load type doesn't match v2f64.
13603   if (VecTy != MVT::v2f64) {
13604     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13605     DCI.AddToWorklist(N.getNode());
13606     // Package {bitcast value, swap's chain} to match Load's shape.
13607     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13608                        N, Swap.getValue(1));
13609   }
13610 
13611   return Swap;
13612 }
13613 
13614 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13615 // builtins) into stores with swaps.
13616 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13617                                                DAGCombinerInfo &DCI) const {
13618   SelectionDAG &DAG = DCI.DAG;
13619   SDLoc dl(N);
13620   SDValue Chain;
13621   SDValue Base;
13622   unsigned SrcOpnd;
13623   MachineMemOperand *MMO;
13624 
13625   switch (N->getOpcode()) {
13626   default:
13627     llvm_unreachable("Unexpected opcode for little endian VSX store");
13628   case ISD::STORE: {
13629     StoreSDNode *ST = cast<StoreSDNode>(N);
13630     Chain = ST->getChain();
13631     Base = ST->getBasePtr();
13632     MMO = ST->getMemOperand();
13633     SrcOpnd = 1;
13634     // If the MMO suggests this isn't a store of a full vector, leave
13635     // things alone.  For a built-in, we have to make the change for
13636     // correctness, so if there is a size problem that will be a bug.
13637     if (MMO->getSize() < 16)
13638       return SDValue();
13639     break;
13640   }
13641   case ISD::INTRINSIC_VOID: {
13642     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13643     Chain = Intrin->getChain();
13644     // Intrin->getBasePtr() oddly does not get what we want.
13645     Base = Intrin->getOperand(3);
13646     MMO = Intrin->getMemOperand();
13647     SrcOpnd = 2;
13648     break;
13649   }
13650   }
13651 
13652   SDValue Src = N->getOperand(SrcOpnd);
13653   MVT VecTy = Src.getValueType().getSimpleVT();
13654 
13655   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13656   // aligned and the type is a vector with elements up to 4 bytes
13657   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13658       VecTy.getScalarSizeInBits() <= 32) {
13659     return SDValue();
13660   }
13661 
13662   // All stores are done as v2f64 and possible bit cast.
13663   if (VecTy != MVT::v2f64) {
13664     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13665     DCI.AddToWorklist(Src.getNode());
13666   }
13667 
13668   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13669                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13670   DCI.AddToWorklist(Swap.getNode());
13671   Chain = Swap.getValue(1);
13672   SDValue StoreOps[] = { Chain, Swap, Base };
13673   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13674                                           DAG.getVTList(MVT::Other),
13675                                           StoreOps, VecTy, MMO);
13676   DCI.AddToWorklist(Store.getNode());
13677   return Store;
13678 }
13679 
13680 // Handle DAG combine for STORE (FP_TO_INT F).
13681 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13682                                                DAGCombinerInfo &DCI) const {
13683 
13684   SelectionDAG &DAG = DCI.DAG;
13685   SDLoc dl(N);
13686   unsigned Opcode = N->getOperand(1).getOpcode();
13687 
13688   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13689          && "Not a FP_TO_INT Instruction!");
13690 
13691   SDValue Val = N->getOperand(1).getOperand(0);
13692   EVT Op1VT = N->getOperand(1).getValueType();
13693   EVT ResVT = Val.getValueType();
13694 
13695   // Floating point types smaller than 32 bits are not legal on Power.
13696   if (ResVT.getScalarSizeInBits() < 32)
13697     return SDValue();
13698 
13699   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13700   bool ValidTypeForStoreFltAsInt =
13701         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13702          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13703 
13704   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13705       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13706     return SDValue();
13707 
13708   // Extend f32 values to f64
13709   if (ResVT.getScalarSizeInBits() == 32) {
13710     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13711     DCI.AddToWorklist(Val.getNode());
13712   }
13713 
13714   // Set signed or unsigned conversion opcode.
13715   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13716                           PPCISD::FP_TO_SINT_IN_VSR :
13717                           PPCISD::FP_TO_UINT_IN_VSR;
13718 
13719   Val = DAG.getNode(ConvOpcode,
13720                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13721   DCI.AddToWorklist(Val.getNode());
13722 
13723   // Set number of bytes being converted.
13724   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13725   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13726                     DAG.getIntPtrConstant(ByteSize, dl, false),
13727                     DAG.getValueType(Op1VT) };
13728 
13729   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13730           DAG.getVTList(MVT::Other), Ops,
13731           cast<StoreSDNode>(N)->getMemoryVT(),
13732           cast<StoreSDNode>(N)->getMemOperand());
13733 
13734   DCI.AddToWorklist(Val.getNode());
13735   return Val;
13736 }
13737 
13738 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
13739   // Check that the source of the element keeps flipping
13740   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
13741   bool PrevElemFromFirstVec = Mask[0] < NumElts;
13742   for (int i = 1, e = Mask.size(); i < e; i++) {
13743     if (PrevElemFromFirstVec && Mask[i] < NumElts)
13744       return false;
13745     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
13746       return false;
13747     PrevElemFromFirstVec = !PrevElemFromFirstVec;
13748   }
13749   return true;
13750 }
13751 
13752 static bool isSplatBV(SDValue Op) {
13753   if (Op.getOpcode() != ISD::BUILD_VECTOR)
13754     return false;
13755   SDValue FirstOp;
13756 
13757   // Find first non-undef input.
13758   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
13759     FirstOp = Op.getOperand(i);
13760     if (!FirstOp.isUndef())
13761       break;
13762   }
13763 
13764   // All inputs are undef or the same as the first non-undef input.
13765   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
13766     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
13767       return false;
13768   return true;
13769 }
13770 
13771 static SDValue isScalarToVec(SDValue Op) {
13772   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
13773     return Op;
13774   if (Op.getOpcode() != ISD::BITCAST)
13775     return SDValue();
13776   Op = Op.getOperand(0);
13777   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
13778     return Op;
13779   return SDValue();
13780 }
13781 
13782 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
13783                                             int LHSMaxIdx, int RHSMinIdx,
13784                                             int RHSMaxIdx, int HalfVec) {
13785   for (int i = 0, e = ShuffV.size(); i < e; i++) {
13786     int Idx = ShuffV[i];
13787     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
13788       ShuffV[i] += HalfVec;
13789   }
13790   return;
13791 }
13792 
13793 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
13794 // the original is:
13795 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
13796 // In such a case, just change the shuffle mask to extract the element
13797 // from the permuted index.
13798 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
13799   SDLoc dl(OrigSToV);
13800   EVT VT = OrigSToV.getValueType();
13801   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13802          "Expecting a SCALAR_TO_VECTOR here");
13803   SDValue Input = OrigSToV.getOperand(0);
13804 
13805   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13806     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
13807     SDValue OrigVector = Input.getOperand(0);
13808 
13809     // Can't handle non-const element indices or different vector types
13810     // for the input to the extract and the output of the scalar_to_vector.
13811     if (Idx && VT == OrigVector.getValueType()) {
13812       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
13813       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
13814       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
13815     }
13816   }
13817   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
13818                      OrigSToV.getOperand(0));
13819 }
13820 
13821 // On little endian subtargets, combine shuffles such as:
13822 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
13823 // into:
13824 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
13825 // because the latter can be matched to a single instruction merge.
13826 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
13827 // to put the value into element zero. Adjust the shuffle mask so that the
13828 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
13829 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
13830                                                 SelectionDAG &DAG) const {
13831   SDValue LHS = SVN->getOperand(0);
13832   SDValue RHS = SVN->getOperand(1);
13833   auto Mask = SVN->getMask();
13834   int NumElts = LHS.getValueType().getVectorNumElements();
13835   SDValue Res(SVN, 0);
13836   SDLoc dl(SVN);
13837 
13838   // None of these combines are useful on big endian systems since the ISA
13839   // already has a big endian bias.
13840   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13841     return Res;
13842 
13843   // If this is not a shuffle of a shuffle and the first element comes from
13844   // the second vector, canonicalize to the commuted form. This will make it
13845   // more likely to match one of the single instruction patterns.
13846   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13847       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
13848     std::swap(LHS, RHS);
13849     Res = DAG.getCommutedVectorShuffle(*SVN);
13850     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
13851   }
13852 
13853   // Adjust the shuffle mask if either input vector comes from a
13854   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
13855   // form (to prevent the need for a swap).
13856   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
13857   SDValue SToVLHS = isScalarToVec(LHS);
13858   SDValue SToVRHS = isScalarToVec(RHS);
13859   if (SToVLHS || SToVRHS) {
13860     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
13861                             : SToVRHS.getValueType().getVectorNumElements();
13862     int NumEltsOut = ShuffV.size();
13863 
13864     // Initially assume that neither input is permuted. These will be adjusted
13865     // accordingly if either input is.
13866     int LHSMaxIdx = -1;
13867     int RHSMinIdx = -1;
13868     int RHSMaxIdx = -1;
13869     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
13870 
13871     // Get the permuted scalar to vector nodes for the source(s) that come from
13872     // ISD::SCALAR_TO_VECTOR.
13873     if (SToVLHS) {
13874       // Set up the values for the shuffle vector fixup.
13875       LHSMaxIdx = NumEltsOut / NumEltsIn;
13876       SToVLHS = getSToVPermuted(SToVLHS, DAG);
13877       if (SToVLHS.getValueType() != LHS.getValueType())
13878         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
13879       LHS = SToVLHS;
13880     }
13881     if (SToVRHS) {
13882       RHSMinIdx = NumEltsOut;
13883       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
13884       SToVRHS = getSToVPermuted(SToVRHS, DAG);
13885       if (SToVRHS.getValueType() != RHS.getValueType())
13886         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
13887       RHS = SToVRHS;
13888     }
13889 
13890     // Fix up the shuffle mask to reflect where the desired element actually is.
13891     // The minimum and maximum indices that correspond to element zero for both
13892     // the LHS and RHS are computed and will control which shuffle mask entries
13893     // are to be changed. For example, if the RHS is permuted, any shuffle mask
13894     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
13895     // HalfVec to refer to the corresponding element in the permuted vector.
13896     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
13897                                     HalfVec);
13898     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
13899 
13900     // We may have simplified away the shuffle. We won't be able to do anything
13901     // further with it here.
13902     if (!isa<ShuffleVectorSDNode>(Res))
13903       return Res;
13904     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
13905   }
13906 
13907   // The common case after we commuted the shuffle is that the RHS is a splat
13908   // and we have elements coming in from the splat at indices that are not
13909   // conducive to using a merge.
13910   // Example:
13911   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
13912   if (!isSplatBV(RHS))
13913     return Res;
13914 
13915   // We are looking for a mask such that all even elements are from
13916   // one vector and all odd elements from the other.
13917   if (!isAlternatingShuffMask(Mask, NumElts))
13918     return Res;
13919 
13920   // Adjust the mask so we are pulling in the same index from the splat
13921   // as the index from the interesting vector in consecutive elements.
13922   // Example (even elements from first vector):
13923   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
13924   if (Mask[0] < NumElts)
13925     for (int i = 1, e = Mask.size(); i < e; i += 2)
13926       ShuffV[i] = (ShuffV[i - 1] + NumElts);
13927   // Example (odd elements from first vector):
13928   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
13929   else
13930     for (int i = 0, e = Mask.size(); i < e; i += 2)
13931       ShuffV[i] = (ShuffV[i + 1] + NumElts);
13932 
13933   // If the RHS has undefs, we need to remove them since we may have created
13934   // a shuffle that adds those instead of the splat value.
13935   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
13936   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
13937 
13938   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
13939   return Res;
13940 }
13941 
13942 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13943                                                 LSBaseSDNode *LSBase,
13944                                                 DAGCombinerInfo &DCI) const {
13945   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13946         "Not a reverse memop pattern!");
13947 
13948   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13949     auto Mask = SVN->getMask();
13950     int i = 0;
13951     auto I = Mask.rbegin();
13952     auto E = Mask.rend();
13953 
13954     for (; I != E; ++I) {
13955       if (*I != i)
13956         return false;
13957       i++;
13958     }
13959     return true;
13960   };
13961 
13962   SelectionDAG &DAG = DCI.DAG;
13963   EVT VT = SVN->getValueType(0);
13964 
13965   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13966     return SDValue();
13967 
13968   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13969   // See comment in PPCVSXSwapRemoval.cpp.
13970   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13971   if (!Subtarget.hasP9Vector())
13972     return SDValue();
13973 
13974   if(!IsElementReverse(SVN))
13975     return SDValue();
13976 
13977   if (LSBase->getOpcode() == ISD::LOAD) {
13978     SDLoc dl(SVN);
13979     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13980     return DAG.getMemIntrinsicNode(
13981         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13982         LSBase->getMemoryVT(), LSBase->getMemOperand());
13983   }
13984 
13985   if (LSBase->getOpcode() == ISD::STORE) {
13986     SDLoc dl(LSBase);
13987     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13988                           LSBase->getBasePtr()};
13989     return DAG.getMemIntrinsicNode(
13990         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13991         LSBase->getMemoryVT(), LSBase->getMemOperand());
13992   }
13993 
13994   llvm_unreachable("Expected a load or store node here");
13995 }
13996 
13997 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13998                                              DAGCombinerInfo &DCI) const {
13999   SelectionDAG &DAG = DCI.DAG;
14000   SDLoc dl(N);
14001   switch (N->getOpcode()) {
14002   default: break;
14003   case ISD::ADD:
14004     return combineADD(N, DCI);
14005   case ISD::SHL:
14006     return combineSHL(N, DCI);
14007   case ISD::SRA:
14008     return combineSRA(N, DCI);
14009   case ISD::SRL:
14010     return combineSRL(N, DCI);
14011   case ISD::MUL:
14012     return combineMUL(N, DCI);
14013   case ISD::FMA:
14014   case PPCISD::FNMSUB:
14015     return combineFMALike(N, DCI);
14016   case PPCISD::SHL:
14017     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14018         return N->getOperand(0);
14019     break;
14020   case PPCISD::SRL:
14021     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14022         return N->getOperand(0);
14023     break;
14024   case PPCISD::SRA:
14025     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14026       if (C->isNullValue() ||   //  0 >>s V -> 0.
14027           C->isAllOnesValue())    // -1 >>s V -> -1.
14028         return N->getOperand(0);
14029     }
14030     break;
14031   case ISD::SIGN_EXTEND:
14032   case ISD::ZERO_EXTEND:
14033   case ISD::ANY_EXTEND:
14034     return DAGCombineExtBoolTrunc(N, DCI);
14035   case ISD::TRUNCATE:
14036     return combineTRUNCATE(N, DCI);
14037   case ISD::SETCC:
14038     if (SDValue CSCC = combineSetCC(N, DCI))
14039       return CSCC;
14040     LLVM_FALLTHROUGH;
14041   case ISD::SELECT_CC:
14042     return DAGCombineTruncBoolExt(N, DCI);
14043   case ISD::SINT_TO_FP:
14044   case ISD::UINT_TO_FP:
14045     return combineFPToIntToFP(N, DCI);
14046   case ISD::VECTOR_SHUFFLE:
14047     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14048       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14049       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14050     }
14051     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14052   case ISD::STORE: {
14053 
14054     EVT Op1VT = N->getOperand(1).getValueType();
14055     unsigned Opcode = N->getOperand(1).getOpcode();
14056 
14057     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14058       SDValue Val= combineStoreFPToInt(N, DCI);
14059       if (Val)
14060         return Val;
14061     }
14062 
14063     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14064       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14065       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14066       if (Val)
14067         return Val;
14068     }
14069 
14070     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14071     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14072         N->getOperand(1).getNode()->hasOneUse() &&
14073         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14074          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14075 
14076       // STBRX can only handle simple types and it makes no sense to store less
14077       // two bytes in byte-reversed order.
14078       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14079       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14080         break;
14081 
14082       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14083       // Do an any-extend to 32-bits if this is a half-word input.
14084       if (BSwapOp.getValueType() == MVT::i16)
14085         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14086 
14087       // If the type of BSWAP operand is wider than stored memory width
14088       // it need to be shifted to the right side before STBRX.
14089       if (Op1VT.bitsGT(mVT)) {
14090         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14091         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14092                               DAG.getConstant(Shift, dl, MVT::i32));
14093         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14094         if (Op1VT == MVT::i64)
14095           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14096       }
14097 
14098       SDValue Ops[] = {
14099         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14100       };
14101       return
14102         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14103                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14104                                 cast<StoreSDNode>(N)->getMemOperand());
14105     }
14106 
14107     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14108     // So it can increase the chance of CSE constant construction.
14109     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14110         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14111       // Need to sign-extended to 64-bits to handle negative values.
14112       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14113       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14114                                     MemVT.getSizeInBits());
14115       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14116 
14117       // DAG.getTruncStore() can't be used here because it doesn't accept
14118       // the general (base + offset) addressing mode.
14119       // So we use UpdateNodeOperands and setTruncatingStore instead.
14120       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14121                              N->getOperand(3));
14122       cast<StoreSDNode>(N)->setTruncatingStore(true);
14123       return SDValue(N, 0);
14124     }
14125 
14126     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14127     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14128     if (Op1VT.isSimple()) {
14129       MVT StoreVT = Op1VT.getSimpleVT();
14130       if (Subtarget.needsSwapsForVSXMemOps() &&
14131           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14132            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14133         return expandVSXStoreForLE(N, DCI);
14134     }
14135     break;
14136   }
14137   case ISD::LOAD: {
14138     LoadSDNode *LD = cast<LoadSDNode>(N);
14139     EVT VT = LD->getValueType(0);
14140 
14141     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14142     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14143     if (VT.isSimple()) {
14144       MVT LoadVT = VT.getSimpleVT();
14145       if (Subtarget.needsSwapsForVSXMemOps() &&
14146           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14147            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14148         return expandVSXLoadForLE(N, DCI);
14149     }
14150 
14151     // We sometimes end up with a 64-bit integer load, from which we extract
14152     // two single-precision floating-point numbers. This happens with
14153     // std::complex<float>, and other similar structures, because of the way we
14154     // canonicalize structure copies. However, if we lack direct moves,
14155     // then the final bitcasts from the extracted integer values to the
14156     // floating-point numbers turn into store/load pairs. Even with direct moves,
14157     // just loading the two floating-point numbers is likely better.
14158     auto ReplaceTwoFloatLoad = [&]() {
14159       if (VT != MVT::i64)
14160         return false;
14161 
14162       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14163           LD->isVolatile())
14164         return false;
14165 
14166       //  We're looking for a sequence like this:
14167       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14168       //      t16: i64 = srl t13, Constant:i32<32>
14169       //    t17: i32 = truncate t16
14170       //  t18: f32 = bitcast t17
14171       //    t19: i32 = truncate t13
14172       //  t20: f32 = bitcast t19
14173 
14174       if (!LD->hasNUsesOfValue(2, 0))
14175         return false;
14176 
14177       auto UI = LD->use_begin();
14178       while (UI.getUse().getResNo() != 0) ++UI;
14179       SDNode *Trunc = *UI++;
14180       while (UI.getUse().getResNo() != 0) ++UI;
14181       SDNode *RightShift = *UI;
14182       if (Trunc->getOpcode() != ISD::TRUNCATE)
14183         std::swap(Trunc, RightShift);
14184 
14185       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14186           Trunc->getValueType(0) != MVT::i32 ||
14187           !Trunc->hasOneUse())
14188         return false;
14189       if (RightShift->getOpcode() != ISD::SRL ||
14190           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14191           RightShift->getConstantOperandVal(1) != 32 ||
14192           !RightShift->hasOneUse())
14193         return false;
14194 
14195       SDNode *Trunc2 = *RightShift->use_begin();
14196       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14197           Trunc2->getValueType(0) != MVT::i32 ||
14198           !Trunc2->hasOneUse())
14199         return false;
14200 
14201       SDNode *Bitcast = *Trunc->use_begin();
14202       SDNode *Bitcast2 = *Trunc2->use_begin();
14203 
14204       if (Bitcast->getOpcode() != ISD::BITCAST ||
14205           Bitcast->getValueType(0) != MVT::f32)
14206         return false;
14207       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14208           Bitcast2->getValueType(0) != MVT::f32)
14209         return false;
14210 
14211       if (Subtarget.isLittleEndian())
14212         std::swap(Bitcast, Bitcast2);
14213 
14214       // Bitcast has the second float (in memory-layout order) and Bitcast2
14215       // has the first one.
14216 
14217       SDValue BasePtr = LD->getBasePtr();
14218       if (LD->isIndexed()) {
14219         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14220                "Non-pre-inc AM on PPC?");
14221         BasePtr =
14222           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14223                       LD->getOffset());
14224       }
14225 
14226       auto MMOFlags =
14227           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14228       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14229                                       LD->getPointerInfo(), LD->getAlignment(),
14230                                       MMOFlags, LD->getAAInfo());
14231       SDValue AddPtr =
14232         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14233                     BasePtr, DAG.getIntPtrConstant(4, dl));
14234       SDValue FloatLoad2 = DAG.getLoad(
14235           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14236           LD->getPointerInfo().getWithOffset(4),
14237           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14238 
14239       if (LD->isIndexed()) {
14240         // Note that DAGCombine should re-form any pre-increment load(s) from
14241         // what is produced here if that makes sense.
14242         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14243       }
14244 
14245       DCI.CombineTo(Bitcast2, FloatLoad);
14246       DCI.CombineTo(Bitcast, FloatLoad2);
14247 
14248       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14249                                     SDValue(FloatLoad2.getNode(), 1));
14250       return true;
14251     };
14252 
14253     if (ReplaceTwoFloatLoad())
14254       return SDValue(N, 0);
14255 
14256     EVT MemVT = LD->getMemoryVT();
14257     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14258     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14259     if (LD->isUnindexed() && VT.isVector() &&
14260         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14261           // P8 and later hardware should just use LOAD.
14262           !Subtarget.hasP8Vector() &&
14263           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14264            VT == MVT::v4f32))) &&
14265         LD->getAlign() < ABIAlignment) {
14266       // This is a type-legal unaligned Altivec load.
14267       SDValue Chain = LD->getChain();
14268       SDValue Ptr = LD->getBasePtr();
14269       bool isLittleEndian = Subtarget.isLittleEndian();
14270 
14271       // This implements the loading of unaligned vectors as described in
14272       // the venerable Apple Velocity Engine overview. Specifically:
14273       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14274       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14275       //
14276       // The general idea is to expand a sequence of one or more unaligned
14277       // loads into an alignment-based permutation-control instruction (lvsl
14278       // or lvsr), a series of regular vector loads (which always truncate
14279       // their input address to an aligned address), and a series of
14280       // permutations.  The results of these permutations are the requested
14281       // loaded values.  The trick is that the last "extra" load is not taken
14282       // from the address you might suspect (sizeof(vector) bytes after the
14283       // last requested load), but rather sizeof(vector) - 1 bytes after the
14284       // last requested vector. The point of this is to avoid a page fault if
14285       // the base address happened to be aligned. This works because if the
14286       // base address is aligned, then adding less than a full vector length
14287       // will cause the last vector in the sequence to be (re)loaded.
14288       // Otherwise, the next vector will be fetched as you might suspect was
14289       // necessary.
14290 
14291       // We might be able to reuse the permutation generation from
14292       // a different base address offset from this one by an aligned amount.
14293       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14294       // optimization later.
14295       Intrinsic::ID Intr, IntrLD, IntrPerm;
14296       MVT PermCntlTy, PermTy, LDTy;
14297       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14298                             : Intrinsic::ppc_altivec_lvsl;
14299       IntrLD = Intrinsic::ppc_altivec_lvx;
14300       IntrPerm = Intrinsic::ppc_altivec_vperm;
14301       PermCntlTy = MVT::v16i8;
14302       PermTy = MVT::v4i32;
14303       LDTy = MVT::v4i32;
14304 
14305       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14306 
14307       // Create the new MMO for the new base load. It is like the original MMO,
14308       // but represents an area in memory almost twice the vector size centered
14309       // on the original address. If the address is unaligned, we might start
14310       // reading up to (sizeof(vector)-1) bytes below the address of the
14311       // original unaligned load.
14312       MachineFunction &MF = DAG.getMachineFunction();
14313       MachineMemOperand *BaseMMO =
14314         MF.getMachineMemOperand(LD->getMemOperand(),
14315                                 -(long)MemVT.getStoreSize()+1,
14316                                 2*MemVT.getStoreSize()-1);
14317 
14318       // Create the new base load.
14319       SDValue LDXIntID =
14320           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14321       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14322       SDValue BaseLoad =
14323         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14324                                 DAG.getVTList(PermTy, MVT::Other),
14325                                 BaseLoadOps, LDTy, BaseMMO);
14326 
14327       // Note that the value of IncOffset (which is provided to the next
14328       // load's pointer info offset value, and thus used to calculate the
14329       // alignment), and the value of IncValue (which is actually used to
14330       // increment the pointer value) are different! This is because we
14331       // require the next load to appear to be aligned, even though it
14332       // is actually offset from the base pointer by a lesser amount.
14333       int IncOffset = VT.getSizeInBits() / 8;
14334       int IncValue = IncOffset;
14335 
14336       // Walk (both up and down) the chain looking for another load at the real
14337       // (aligned) offset (the alignment of the other load does not matter in
14338       // this case). If found, then do not use the offset reduction trick, as
14339       // that will prevent the loads from being later combined (as they would
14340       // otherwise be duplicates).
14341       if (!findConsecutiveLoad(LD, DAG))
14342         --IncValue;
14343 
14344       SDValue Increment =
14345           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14346       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14347 
14348       MachineMemOperand *ExtraMMO =
14349         MF.getMachineMemOperand(LD->getMemOperand(),
14350                                 1, 2*MemVT.getStoreSize()-1);
14351       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14352       SDValue ExtraLoad =
14353         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14354                                 DAG.getVTList(PermTy, MVT::Other),
14355                                 ExtraLoadOps, LDTy, ExtraMMO);
14356 
14357       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14358         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14359 
14360       // Because vperm has a big-endian bias, we must reverse the order
14361       // of the input vectors and complement the permute control vector
14362       // when generating little endian code.  We have already handled the
14363       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14364       // and ExtraLoad here.
14365       SDValue Perm;
14366       if (isLittleEndian)
14367         Perm = BuildIntrinsicOp(IntrPerm,
14368                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14369       else
14370         Perm = BuildIntrinsicOp(IntrPerm,
14371                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14372 
14373       if (VT != PermTy)
14374         Perm = Subtarget.hasAltivec()
14375                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14376                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14377                                  DAG.getTargetConstant(1, dl, MVT::i64));
14378                                // second argument is 1 because this rounding
14379                                // is always exact.
14380 
14381       // The output of the permutation is our loaded result, the TokenFactor is
14382       // our new chain.
14383       DCI.CombineTo(N, Perm, TF);
14384       return SDValue(N, 0);
14385     }
14386     }
14387     break;
14388     case ISD::INTRINSIC_WO_CHAIN: {
14389       bool isLittleEndian = Subtarget.isLittleEndian();
14390       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14391       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14392                                            : Intrinsic::ppc_altivec_lvsl);
14393       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
14394         SDValue Add = N->getOperand(1);
14395 
14396         int Bits = 4 /* 16 byte alignment */;
14397 
14398         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14399                                   APInt::getAllOnesValue(Bits /* alignment */)
14400                                       .zext(Add.getScalarValueSizeInBits()))) {
14401           SDNode *BasePtr = Add->getOperand(0).getNode();
14402           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14403                                     UE = BasePtr->use_end();
14404                UI != UE; ++UI) {
14405             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14406                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
14407                     IID) {
14408               // We've found another LVSL/LVSR, and this address is an aligned
14409               // multiple of that one. The results will be the same, so use the
14410               // one we've just found instead.
14411 
14412               return SDValue(*UI, 0);
14413             }
14414           }
14415         }
14416 
14417         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14418           SDNode *BasePtr = Add->getOperand(0).getNode();
14419           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14420                UE = BasePtr->use_end(); UI != UE; ++UI) {
14421             if (UI->getOpcode() == ISD::ADD &&
14422                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14423                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14424                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14425                 (1ULL << Bits) == 0) {
14426               SDNode *OtherAdd = *UI;
14427               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14428                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14429                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14430                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14431                   return SDValue(*VI, 0);
14432                 }
14433               }
14434             }
14435           }
14436         }
14437       }
14438 
14439       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14440       // Expose the vabsduw/h/b opportunity for down stream
14441       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14442           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14443            IID == Intrinsic::ppc_altivec_vmaxsh ||
14444            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14445         SDValue V1 = N->getOperand(1);
14446         SDValue V2 = N->getOperand(2);
14447         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14448              V1.getSimpleValueType() == MVT::v8i16 ||
14449              V1.getSimpleValueType() == MVT::v16i8) &&
14450             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14451           // (0-a, a)
14452           if (V1.getOpcode() == ISD::SUB &&
14453               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14454               V1.getOperand(1) == V2) {
14455             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14456           }
14457           // (a, 0-a)
14458           if (V2.getOpcode() == ISD::SUB &&
14459               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14460               V2.getOperand(1) == V1) {
14461             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14462           }
14463           // (x-y, y-x)
14464           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14465               V1.getOperand(0) == V2.getOperand(1) &&
14466               V1.getOperand(1) == V2.getOperand(0)) {
14467             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14468           }
14469         }
14470       }
14471     }
14472 
14473     break;
14474   case ISD::INTRINSIC_W_CHAIN:
14475     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14476     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14477     if (Subtarget.needsSwapsForVSXMemOps()) {
14478       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14479       default:
14480         break;
14481       case Intrinsic::ppc_vsx_lxvw4x:
14482       case Intrinsic::ppc_vsx_lxvd2x:
14483         return expandVSXLoadForLE(N, DCI);
14484       }
14485     }
14486     break;
14487   case ISD::INTRINSIC_VOID:
14488     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14489     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14490     if (Subtarget.needsSwapsForVSXMemOps()) {
14491       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14492       default:
14493         break;
14494       case Intrinsic::ppc_vsx_stxvw4x:
14495       case Intrinsic::ppc_vsx_stxvd2x:
14496         return expandVSXStoreForLE(N, DCI);
14497       }
14498     }
14499     break;
14500   case ISD::BSWAP:
14501     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14502     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14503         N->getOperand(0).hasOneUse() &&
14504         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14505          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14506           N->getValueType(0) == MVT::i64))) {
14507       SDValue Load = N->getOperand(0);
14508       LoadSDNode *LD = cast<LoadSDNode>(Load);
14509       // Create the byte-swapping load.
14510       SDValue Ops[] = {
14511         LD->getChain(),    // Chain
14512         LD->getBasePtr(),  // Ptr
14513         DAG.getValueType(N->getValueType(0)) // VT
14514       };
14515       SDValue BSLoad =
14516         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14517                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14518                                               MVT::i64 : MVT::i32, MVT::Other),
14519                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14520 
14521       // If this is an i16 load, insert the truncate.
14522       SDValue ResVal = BSLoad;
14523       if (N->getValueType(0) == MVT::i16)
14524         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14525 
14526       // First, combine the bswap away.  This makes the value produced by the
14527       // load dead.
14528       DCI.CombineTo(N, ResVal);
14529 
14530       // Next, combine the load away, we give it a bogus result value but a real
14531       // chain result.  The result value is dead because the bswap is dead.
14532       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14533 
14534       // Return N so it doesn't get rechecked!
14535       return SDValue(N, 0);
14536     }
14537     break;
14538   case PPCISD::VCMP:
14539     // If a VCMPo node already exists with exactly the same operands as this
14540     // node, use its result instead of this node (VCMPo computes both a CR6 and
14541     // a normal output).
14542     //
14543     if (!N->getOperand(0).hasOneUse() &&
14544         !N->getOperand(1).hasOneUse() &&
14545         !N->getOperand(2).hasOneUse()) {
14546 
14547       // Scan all of the users of the LHS, looking for VCMPo's that match.
14548       SDNode *VCMPoNode = nullptr;
14549 
14550       SDNode *LHSN = N->getOperand(0).getNode();
14551       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14552            UI != E; ++UI)
14553         if (UI->getOpcode() == PPCISD::VCMPo &&
14554             UI->getOperand(1) == N->getOperand(1) &&
14555             UI->getOperand(2) == N->getOperand(2) &&
14556             UI->getOperand(0) == N->getOperand(0)) {
14557           VCMPoNode = *UI;
14558           break;
14559         }
14560 
14561       // If there is no VCMPo node, or if the flag value has a single use, don't
14562       // transform this.
14563       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14564         break;
14565 
14566       // Look at the (necessarily single) use of the flag value.  If it has a
14567       // chain, this transformation is more complex.  Note that multiple things
14568       // could use the value result, which we should ignore.
14569       SDNode *FlagUser = nullptr;
14570       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14571            FlagUser == nullptr; ++UI) {
14572         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14573         SDNode *User = *UI;
14574         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14575           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14576             FlagUser = User;
14577             break;
14578           }
14579         }
14580       }
14581 
14582       // If the user is a MFOCRF instruction, we know this is safe.
14583       // Otherwise we give up for right now.
14584       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14585         return SDValue(VCMPoNode, 0);
14586     }
14587     break;
14588   case ISD::BRCOND: {
14589     SDValue Cond = N->getOperand(1);
14590     SDValue Target = N->getOperand(2);
14591 
14592     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14593         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14594           Intrinsic::loop_decrement) {
14595 
14596       // We now need to make the intrinsic dead (it cannot be instruction
14597       // selected).
14598       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14599       assert(Cond.getNode()->hasOneUse() &&
14600              "Counter decrement has more than one use");
14601 
14602       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14603                          N->getOperand(0), Target);
14604     }
14605   }
14606   break;
14607   case ISD::BR_CC: {
14608     // If this is a branch on an altivec predicate comparison, lower this so
14609     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14610     // lowering is done pre-legalize, because the legalizer lowers the predicate
14611     // compare down to code that is difficult to reassemble.
14612     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14613     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14614 
14615     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14616     // value. If so, pass-through the AND to get to the intrinsic.
14617     if (LHS.getOpcode() == ISD::AND &&
14618         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14619         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14620           Intrinsic::loop_decrement &&
14621         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14622         !isNullConstant(LHS.getOperand(1)))
14623       LHS = LHS.getOperand(0);
14624 
14625     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14626         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14627           Intrinsic::loop_decrement &&
14628         isa<ConstantSDNode>(RHS)) {
14629       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14630              "Counter decrement comparison is not EQ or NE");
14631 
14632       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14633       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14634                     (CC == ISD::SETNE && !Val);
14635 
14636       // We now need to make the intrinsic dead (it cannot be instruction
14637       // selected).
14638       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14639       assert(LHS.getNode()->hasOneUse() &&
14640              "Counter decrement has more than one use");
14641 
14642       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14643                          N->getOperand(0), N->getOperand(4));
14644     }
14645 
14646     int CompareOpc;
14647     bool isDot;
14648 
14649     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14650         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14651         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14652       assert(isDot && "Can't compare against a vector result!");
14653 
14654       // If this is a comparison against something other than 0/1, then we know
14655       // that the condition is never/always true.
14656       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14657       if (Val != 0 && Val != 1) {
14658         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14659           return N->getOperand(0);
14660         // Always !=, turn it into an unconditional branch.
14661         return DAG.getNode(ISD::BR, dl, MVT::Other,
14662                            N->getOperand(0), N->getOperand(4));
14663       }
14664 
14665       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14666 
14667       // Create the PPCISD altivec 'dot' comparison node.
14668       SDValue Ops[] = {
14669         LHS.getOperand(2),  // LHS of compare
14670         LHS.getOperand(3),  // RHS of compare
14671         DAG.getConstant(CompareOpc, dl, MVT::i32)
14672       };
14673       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14674       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14675 
14676       // Unpack the result based on how the target uses it.
14677       PPC::Predicate CompOpc;
14678       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14679       default:  // Can't happen, don't crash on invalid number though.
14680       case 0:   // Branch on the value of the EQ bit of CR6.
14681         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14682         break;
14683       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14684         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14685         break;
14686       case 2:   // Branch on the value of the LT bit of CR6.
14687         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14688         break;
14689       case 3:   // Branch on the inverted value of the LT bit of CR6.
14690         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14691         break;
14692       }
14693 
14694       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14695                          DAG.getConstant(CompOpc, dl, MVT::i32),
14696                          DAG.getRegister(PPC::CR6, MVT::i32),
14697                          N->getOperand(4), CompNode.getValue(1));
14698     }
14699     break;
14700   }
14701   case ISD::BUILD_VECTOR:
14702     return DAGCombineBuildVector(N, DCI);
14703   case ISD::ABS:
14704     return combineABS(N, DCI);
14705   case ISD::VSELECT:
14706     return combineVSelect(N, DCI);
14707   }
14708 
14709   return SDValue();
14710 }
14711 
14712 SDValue
14713 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14714                                  SelectionDAG &DAG,
14715                                  SmallVectorImpl<SDNode *> &Created) const {
14716   // fold (sdiv X, pow2)
14717   EVT VT = N->getValueType(0);
14718   if (VT == MVT::i64 && !Subtarget.isPPC64())
14719     return SDValue();
14720   if ((VT != MVT::i32 && VT != MVT::i64) ||
14721       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14722     return SDValue();
14723 
14724   SDLoc DL(N);
14725   SDValue N0 = N->getOperand(0);
14726 
14727   bool IsNegPow2 = (-Divisor).isPowerOf2();
14728   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14729   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14730 
14731   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14732   Created.push_back(Op.getNode());
14733 
14734   if (IsNegPow2) {
14735     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14736     Created.push_back(Op.getNode());
14737   }
14738 
14739   return Op;
14740 }
14741 
14742 //===----------------------------------------------------------------------===//
14743 // Inline Assembly Support
14744 //===----------------------------------------------------------------------===//
14745 
14746 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14747                                                       KnownBits &Known,
14748                                                       const APInt &DemandedElts,
14749                                                       const SelectionDAG &DAG,
14750                                                       unsigned Depth) const {
14751   Known.resetAll();
14752   switch (Op.getOpcode()) {
14753   default: break;
14754   case PPCISD::LBRX: {
14755     // lhbrx is known to have the top bits cleared out.
14756     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14757       Known.Zero = 0xFFFF0000;
14758     break;
14759   }
14760   case ISD::INTRINSIC_WO_CHAIN: {
14761     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14762     default: break;
14763     case Intrinsic::ppc_altivec_vcmpbfp_p:
14764     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14765     case Intrinsic::ppc_altivec_vcmpequb_p:
14766     case Intrinsic::ppc_altivec_vcmpequh_p:
14767     case Intrinsic::ppc_altivec_vcmpequw_p:
14768     case Intrinsic::ppc_altivec_vcmpequd_p:
14769     case Intrinsic::ppc_altivec_vcmpgefp_p:
14770     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14771     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14772     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14773     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14774     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14775     case Intrinsic::ppc_altivec_vcmpgtub_p:
14776     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14777     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14778     case Intrinsic::ppc_altivec_vcmpgtud_p:
14779       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14780       break;
14781     }
14782   }
14783   }
14784 }
14785 
14786 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14787   switch (Subtarget.getCPUDirective()) {
14788   default: break;
14789   case PPC::DIR_970:
14790   case PPC::DIR_PWR4:
14791   case PPC::DIR_PWR5:
14792   case PPC::DIR_PWR5X:
14793   case PPC::DIR_PWR6:
14794   case PPC::DIR_PWR6X:
14795   case PPC::DIR_PWR7:
14796   case PPC::DIR_PWR8:
14797   case PPC::DIR_PWR9:
14798   case PPC::DIR_PWR10:
14799   case PPC::DIR_PWR_FUTURE: {
14800     if (!ML)
14801       break;
14802 
14803     if (!DisableInnermostLoopAlign32) {
14804       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14805       // so that we can decrease cache misses and branch-prediction misses.
14806       // Actual alignment of the loop will depend on the hotness check and other
14807       // logic in alignBlocks.
14808       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14809         return Align(32);
14810     }
14811 
14812     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14813 
14814     // For small loops (between 5 and 8 instructions), align to a 32-byte
14815     // boundary so that the entire loop fits in one instruction-cache line.
14816     uint64_t LoopSize = 0;
14817     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14818       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14819         LoopSize += TII->getInstSizeInBytes(*J);
14820         if (LoopSize > 32)
14821           break;
14822       }
14823 
14824     if (LoopSize > 16 && LoopSize <= 32)
14825       return Align(32);
14826 
14827     break;
14828   }
14829   }
14830 
14831   return TargetLowering::getPrefLoopAlignment(ML);
14832 }
14833 
14834 /// getConstraintType - Given a constraint, return the type of
14835 /// constraint it is for this target.
14836 PPCTargetLowering::ConstraintType
14837 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14838   if (Constraint.size() == 1) {
14839     switch (Constraint[0]) {
14840     default: break;
14841     case 'b':
14842     case 'r':
14843     case 'f':
14844     case 'd':
14845     case 'v':
14846     case 'y':
14847       return C_RegisterClass;
14848     case 'Z':
14849       // FIXME: While Z does indicate a memory constraint, it specifically
14850       // indicates an r+r address (used in conjunction with the 'y' modifier
14851       // in the replacement string). Currently, we're forcing the base
14852       // register to be r0 in the asm printer (which is interpreted as zero)
14853       // and forming the complete address in the second register. This is
14854       // suboptimal.
14855       return C_Memory;
14856     }
14857   } else if (Constraint == "wc") { // individual CR bits.
14858     return C_RegisterClass;
14859   } else if (Constraint == "wa" || Constraint == "wd" ||
14860              Constraint == "wf" || Constraint == "ws" ||
14861              Constraint == "wi" || Constraint == "ww") {
14862     return C_RegisterClass; // VSX registers.
14863   }
14864   return TargetLowering::getConstraintType(Constraint);
14865 }
14866 
14867 /// Examine constraint type and operand type and determine a weight value.
14868 /// This object must already have been set up with the operand type
14869 /// and the current alternative constraint selected.
14870 TargetLowering::ConstraintWeight
14871 PPCTargetLowering::getSingleConstraintMatchWeight(
14872     AsmOperandInfo &info, const char *constraint) const {
14873   ConstraintWeight weight = CW_Invalid;
14874   Value *CallOperandVal = info.CallOperandVal;
14875     // If we don't have a value, we can't do a match,
14876     // but allow it at the lowest weight.
14877   if (!CallOperandVal)
14878     return CW_Default;
14879   Type *type = CallOperandVal->getType();
14880 
14881   // Look at the constraint type.
14882   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14883     return CW_Register; // an individual CR bit.
14884   else if ((StringRef(constraint) == "wa" ||
14885             StringRef(constraint) == "wd" ||
14886             StringRef(constraint) == "wf") &&
14887            type->isVectorTy())
14888     return CW_Register;
14889   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14890     return CW_Register; // just hold 64-bit integers data.
14891   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14892     return CW_Register;
14893   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14894     return CW_Register;
14895 
14896   switch (*constraint) {
14897   default:
14898     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14899     break;
14900   case 'b':
14901     if (type->isIntegerTy())
14902       weight = CW_Register;
14903     break;
14904   case 'f':
14905     if (type->isFloatTy())
14906       weight = CW_Register;
14907     break;
14908   case 'd':
14909     if (type->isDoubleTy())
14910       weight = CW_Register;
14911     break;
14912   case 'v':
14913     if (type->isVectorTy())
14914       weight = CW_Register;
14915     break;
14916   case 'y':
14917     weight = CW_Register;
14918     break;
14919   case 'Z':
14920     weight = CW_Memory;
14921     break;
14922   }
14923   return weight;
14924 }
14925 
14926 std::pair<unsigned, const TargetRegisterClass *>
14927 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14928                                                 StringRef Constraint,
14929                                                 MVT VT) const {
14930   if (Constraint.size() == 1) {
14931     // GCC RS6000 Constraint Letters
14932     switch (Constraint[0]) {
14933     case 'b':   // R1-R31
14934       if (VT == MVT::i64 && Subtarget.isPPC64())
14935         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14936       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14937     case 'r':   // R0-R31
14938       if (VT == MVT::i64 && Subtarget.isPPC64())
14939         return std::make_pair(0U, &PPC::G8RCRegClass);
14940       return std::make_pair(0U, &PPC::GPRCRegClass);
14941     // 'd' and 'f' constraints are both defined to be "the floating point
14942     // registers", where one is for 32-bit and the other for 64-bit. We don't
14943     // really care overly much here so just give them all the same reg classes.
14944     case 'd':
14945     case 'f':
14946       if (Subtarget.hasSPE()) {
14947         if (VT == MVT::f32 || VT == MVT::i32)
14948           return std::make_pair(0U, &PPC::GPRCRegClass);
14949         if (VT == MVT::f64 || VT == MVT::i64)
14950           return std::make_pair(0U, &PPC::SPERCRegClass);
14951       } else {
14952         if (VT == MVT::f32 || VT == MVT::i32)
14953           return std::make_pair(0U, &PPC::F4RCRegClass);
14954         if (VT == MVT::f64 || VT == MVT::i64)
14955           return std::make_pair(0U, &PPC::F8RCRegClass);
14956       }
14957       break;
14958     case 'v':
14959       if (Subtarget.hasAltivec())
14960         return std::make_pair(0U, &PPC::VRRCRegClass);
14961       break;
14962     case 'y':   // crrc
14963       return std::make_pair(0U, &PPC::CRRCRegClass);
14964     }
14965   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14966     // An individual CR bit.
14967     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14968   } else if ((Constraint == "wa" || Constraint == "wd" ||
14969              Constraint == "wf" || Constraint == "wi") &&
14970              Subtarget.hasVSX()) {
14971     return std::make_pair(0U, &PPC::VSRCRegClass);
14972   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14973     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14974       return std::make_pair(0U, &PPC::VSSRCRegClass);
14975     else
14976       return std::make_pair(0U, &PPC::VSFRCRegClass);
14977   }
14978 
14979   // If we name a VSX register, we can't defer to the base class because it
14980   // will not recognize the correct register (their names will be VSL{0-31}
14981   // and V{0-31} so they won't match). So we match them here.
14982   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
14983     int VSNum = atoi(Constraint.data() + 3);
14984     assert(VSNum >= 0 && VSNum <= 63 &&
14985            "Attempted to access a vsr out of range");
14986     if (VSNum < 32)
14987       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
14988     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
14989   }
14990   std::pair<unsigned, const TargetRegisterClass *> R =
14991       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14992 
14993   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14994   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14995   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14996   // register.
14997   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14998   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14999   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15000       PPC::GPRCRegClass.contains(R.first))
15001     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15002                             PPC::sub_32, &PPC::G8RCRegClass),
15003                           &PPC::G8RCRegClass);
15004 
15005   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15006   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15007     R.first = PPC::CR0;
15008     R.second = &PPC::CRRCRegClass;
15009   }
15010 
15011   return R;
15012 }
15013 
15014 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15015 /// vector.  If it is invalid, don't add anything to Ops.
15016 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15017                                                      std::string &Constraint,
15018                                                      std::vector<SDValue>&Ops,
15019                                                      SelectionDAG &DAG) const {
15020   SDValue Result;
15021 
15022   // Only support length 1 constraints.
15023   if (Constraint.length() > 1) return;
15024 
15025   char Letter = Constraint[0];
15026   switch (Letter) {
15027   default: break;
15028   case 'I':
15029   case 'J':
15030   case 'K':
15031   case 'L':
15032   case 'M':
15033   case 'N':
15034   case 'O':
15035   case 'P': {
15036     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15037     if (!CST) return; // Must be an immediate to match.
15038     SDLoc dl(Op);
15039     int64_t Value = CST->getSExtValue();
15040     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15041                          // numbers are printed as such.
15042     switch (Letter) {
15043     default: llvm_unreachable("Unknown constraint letter!");
15044     case 'I':  // "I" is a signed 16-bit constant.
15045       if (isInt<16>(Value))
15046         Result = DAG.getTargetConstant(Value, dl, TCVT);
15047       break;
15048     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15049       if (isShiftedUInt<16, 16>(Value))
15050         Result = DAG.getTargetConstant(Value, dl, TCVT);
15051       break;
15052     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15053       if (isShiftedInt<16, 16>(Value))
15054         Result = DAG.getTargetConstant(Value, dl, TCVT);
15055       break;
15056     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15057       if (isUInt<16>(Value))
15058         Result = DAG.getTargetConstant(Value, dl, TCVT);
15059       break;
15060     case 'M':  // "M" is a constant that is greater than 31.
15061       if (Value > 31)
15062         Result = DAG.getTargetConstant(Value, dl, TCVT);
15063       break;
15064     case 'N':  // "N" is a positive constant that is an exact power of two.
15065       if (Value > 0 && isPowerOf2_64(Value))
15066         Result = DAG.getTargetConstant(Value, dl, TCVT);
15067       break;
15068     case 'O':  // "O" is the constant zero.
15069       if (Value == 0)
15070         Result = DAG.getTargetConstant(Value, dl, TCVT);
15071       break;
15072     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15073       if (isInt<16>(-Value))
15074         Result = DAG.getTargetConstant(Value, dl, TCVT);
15075       break;
15076     }
15077     break;
15078   }
15079   }
15080 
15081   if (Result.getNode()) {
15082     Ops.push_back(Result);
15083     return;
15084   }
15085 
15086   // Handle standard constraint letters.
15087   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15088 }
15089 
15090 // isLegalAddressingMode - Return true if the addressing mode represented
15091 // by AM is legal for this target, for a load/store of the specified type.
15092 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15093                                               const AddrMode &AM, Type *Ty,
15094                                               unsigned AS,
15095                                               Instruction *I) const {
15096   // Vector type r+i form is supported since power9 as DQ form. We don't check
15097   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15098   // imm form is preferred and the offset can be adjusted to use imm form later
15099   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15100   // max offset to check legal addressing mode, we should be a little aggressive
15101   // to contain other offsets for that LSRUse.
15102   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15103     return false;
15104 
15105   // PPC allows a sign-extended 16-bit immediate field.
15106   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15107     return false;
15108 
15109   // No global is ever allowed as a base.
15110   if (AM.BaseGV)
15111     return false;
15112 
15113   // PPC only support r+r,
15114   switch (AM.Scale) {
15115   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15116     break;
15117   case 1:
15118     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15119       return false;
15120     // Otherwise we have r+r or r+i.
15121     break;
15122   case 2:
15123     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15124       return false;
15125     // Allow 2*r as r+r.
15126     break;
15127   default:
15128     // No other scales are supported.
15129     return false;
15130   }
15131 
15132   return true;
15133 }
15134 
15135 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15136                                            SelectionDAG &DAG) const {
15137   MachineFunction &MF = DAG.getMachineFunction();
15138   MachineFrameInfo &MFI = MF.getFrameInfo();
15139   MFI.setReturnAddressIsTaken(true);
15140 
15141   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15142     return SDValue();
15143 
15144   SDLoc dl(Op);
15145   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15146 
15147   // Make sure the function does not optimize away the store of the RA to
15148   // the stack.
15149   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15150   FuncInfo->setLRStoreRequired();
15151   bool isPPC64 = Subtarget.isPPC64();
15152   auto PtrVT = getPointerTy(MF.getDataLayout());
15153 
15154   if (Depth > 0) {
15155     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15156     SDValue Offset =
15157         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15158                         isPPC64 ? MVT::i64 : MVT::i32);
15159     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15160                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15161                        MachinePointerInfo());
15162   }
15163 
15164   // Just load the return address off the stack.
15165   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15166   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15167                      MachinePointerInfo());
15168 }
15169 
15170 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15171                                           SelectionDAG &DAG) const {
15172   SDLoc dl(Op);
15173   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15174 
15175   MachineFunction &MF = DAG.getMachineFunction();
15176   MachineFrameInfo &MFI = MF.getFrameInfo();
15177   MFI.setFrameAddressIsTaken(true);
15178 
15179   EVT PtrVT = getPointerTy(MF.getDataLayout());
15180   bool isPPC64 = PtrVT == MVT::i64;
15181 
15182   // Naked functions never have a frame pointer, and so we use r1. For all
15183   // other functions, this decision must be delayed until during PEI.
15184   unsigned FrameReg;
15185   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15186     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15187   else
15188     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15189 
15190   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15191                                          PtrVT);
15192   while (Depth--)
15193     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15194                             FrameAddr, MachinePointerInfo());
15195   return FrameAddr;
15196 }
15197 
15198 // FIXME? Maybe this could be a TableGen attribute on some registers and
15199 // this table could be generated automatically from RegInfo.
15200 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15201                                               const MachineFunction &MF) const {
15202   bool isPPC64 = Subtarget.isPPC64();
15203 
15204   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15205   if (!is64Bit && VT != LLT::scalar(32))
15206     report_fatal_error("Invalid register global variable type");
15207 
15208   Register Reg = StringSwitch<Register>(RegName)
15209                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15210                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15211                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15212                      .Default(Register());
15213 
15214   if (Reg)
15215     return Reg;
15216   report_fatal_error("Invalid register name global variable");
15217 }
15218 
15219 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15220   // 32-bit SVR4 ABI access everything as got-indirect.
15221   if (Subtarget.is32BitELFABI())
15222     return true;
15223 
15224   // AIX accesses everything indirectly through the TOC, which is similar to
15225   // the GOT.
15226   if (Subtarget.isAIXABI())
15227     return true;
15228 
15229   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15230   // If it is small or large code model, module locals are accessed
15231   // indirectly by loading their address from .toc/.got.
15232   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15233     return true;
15234 
15235   // JumpTable and BlockAddress are accessed as got-indirect.
15236   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15237     return true;
15238 
15239   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15240     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15241 
15242   return false;
15243 }
15244 
15245 bool
15246 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15247   // The PowerPC target isn't yet aware of offsets.
15248   return false;
15249 }
15250 
15251 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15252                                            const CallInst &I,
15253                                            MachineFunction &MF,
15254                                            unsigned Intrinsic) const {
15255   switch (Intrinsic) {
15256   case Intrinsic::ppc_altivec_lvx:
15257   case Intrinsic::ppc_altivec_lvxl:
15258   case Intrinsic::ppc_altivec_lvebx:
15259   case Intrinsic::ppc_altivec_lvehx:
15260   case Intrinsic::ppc_altivec_lvewx:
15261   case Intrinsic::ppc_vsx_lxvd2x:
15262   case Intrinsic::ppc_vsx_lxvw4x: {
15263     EVT VT;
15264     switch (Intrinsic) {
15265     case Intrinsic::ppc_altivec_lvebx:
15266       VT = MVT::i8;
15267       break;
15268     case Intrinsic::ppc_altivec_lvehx:
15269       VT = MVT::i16;
15270       break;
15271     case Intrinsic::ppc_altivec_lvewx:
15272       VT = MVT::i32;
15273       break;
15274     case Intrinsic::ppc_vsx_lxvd2x:
15275       VT = MVT::v2f64;
15276       break;
15277     default:
15278       VT = MVT::v4i32;
15279       break;
15280     }
15281 
15282     Info.opc = ISD::INTRINSIC_W_CHAIN;
15283     Info.memVT = VT;
15284     Info.ptrVal = I.getArgOperand(0);
15285     Info.offset = -VT.getStoreSize()+1;
15286     Info.size = 2*VT.getStoreSize()-1;
15287     Info.align = Align(1);
15288     Info.flags = MachineMemOperand::MOLoad;
15289     return true;
15290   }
15291   case Intrinsic::ppc_altivec_stvx:
15292   case Intrinsic::ppc_altivec_stvxl:
15293   case Intrinsic::ppc_altivec_stvebx:
15294   case Intrinsic::ppc_altivec_stvehx:
15295   case Intrinsic::ppc_altivec_stvewx:
15296   case Intrinsic::ppc_vsx_stxvd2x:
15297   case Intrinsic::ppc_vsx_stxvw4x: {
15298     EVT VT;
15299     switch (Intrinsic) {
15300     case Intrinsic::ppc_altivec_stvebx:
15301       VT = MVT::i8;
15302       break;
15303     case Intrinsic::ppc_altivec_stvehx:
15304       VT = MVT::i16;
15305       break;
15306     case Intrinsic::ppc_altivec_stvewx:
15307       VT = MVT::i32;
15308       break;
15309     case Intrinsic::ppc_vsx_stxvd2x:
15310       VT = MVT::v2f64;
15311       break;
15312     default:
15313       VT = MVT::v4i32;
15314       break;
15315     }
15316 
15317     Info.opc = ISD::INTRINSIC_VOID;
15318     Info.memVT = VT;
15319     Info.ptrVal = I.getArgOperand(1);
15320     Info.offset = -VT.getStoreSize()+1;
15321     Info.size = 2*VT.getStoreSize()-1;
15322     Info.align = Align(1);
15323     Info.flags = MachineMemOperand::MOStore;
15324     return true;
15325   }
15326   default:
15327     break;
15328   }
15329 
15330   return false;
15331 }
15332 
15333 /// It returns EVT::Other if the type should be determined using generic
15334 /// target-independent logic.
15335 EVT PPCTargetLowering::getOptimalMemOpType(
15336     const MemOp &Op, const AttributeList &FuncAttributes) const {
15337   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15338     // We should use Altivec/VSX loads and stores when available. For unaligned
15339     // addresses, unaligned VSX loads are only fast starting with the P8.
15340     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15341         (Op.isAligned(Align(16)) ||
15342          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15343       return MVT::v4i32;
15344   }
15345 
15346   if (Subtarget.isPPC64()) {
15347     return MVT::i64;
15348   }
15349 
15350   return MVT::i32;
15351 }
15352 
15353 /// Returns true if it is beneficial to convert a load of a constant
15354 /// to just the constant itself.
15355 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15356                                                           Type *Ty) const {
15357   assert(Ty->isIntegerTy());
15358 
15359   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15360   return !(BitSize == 0 || BitSize > 64);
15361 }
15362 
15363 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15364   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15365     return false;
15366   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15367   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15368   return NumBits1 == 64 && NumBits2 == 32;
15369 }
15370 
15371 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15372   if (!VT1.isInteger() || !VT2.isInteger())
15373     return false;
15374   unsigned NumBits1 = VT1.getSizeInBits();
15375   unsigned NumBits2 = VT2.getSizeInBits();
15376   return NumBits1 == 64 && NumBits2 == 32;
15377 }
15378 
15379 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15380   // Generally speaking, zexts are not free, but they are free when they can be
15381   // folded with other operations.
15382   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15383     EVT MemVT = LD->getMemoryVT();
15384     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15385          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15386         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15387          LD->getExtensionType() == ISD::ZEXTLOAD))
15388       return true;
15389   }
15390 
15391   // FIXME: Add other cases...
15392   //  - 32-bit shifts with a zext to i64
15393   //  - zext after ctlz, bswap, etc.
15394   //  - zext after and by a constant mask
15395 
15396   return TargetLowering::isZExtFree(Val, VT2);
15397 }
15398 
15399 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15400   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15401          "invalid fpext types");
15402   // Extending to float128 is not free.
15403   if (DestVT == MVT::f128)
15404     return false;
15405   return true;
15406 }
15407 
15408 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15409   return isInt<16>(Imm) || isUInt<16>(Imm);
15410 }
15411 
15412 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15413   return isInt<16>(Imm) || isUInt<16>(Imm);
15414 }
15415 
15416 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15417                                                        unsigned,
15418                                                        unsigned,
15419                                                        MachineMemOperand::Flags,
15420                                                        bool *Fast) const {
15421   if (DisablePPCUnaligned)
15422     return false;
15423 
15424   // PowerPC supports unaligned memory access for simple non-vector types.
15425   // Although accessing unaligned addresses is not as efficient as accessing
15426   // aligned addresses, it is generally more efficient than manual expansion,
15427   // and generally only traps for software emulation when crossing page
15428   // boundaries.
15429 
15430   if (!VT.isSimple())
15431     return false;
15432 
15433   if (VT.isFloatingPoint() && !VT.isVector() &&
15434       !Subtarget.allowsUnalignedFPAccess())
15435     return false;
15436 
15437   if (VT.getSimpleVT().isVector()) {
15438     if (Subtarget.hasVSX()) {
15439       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15440           VT != MVT::v4f32 && VT != MVT::v4i32)
15441         return false;
15442     } else {
15443       return false;
15444     }
15445   }
15446 
15447   if (VT == MVT::ppcf128)
15448     return false;
15449 
15450   if (Fast)
15451     *Fast = true;
15452 
15453   return true;
15454 }
15455 
15456 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15457                                                    EVT VT) const {
15458   return isFMAFasterThanFMulAndFAdd(
15459       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15460 }
15461 
15462 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15463                                                    Type *Ty) const {
15464   switch (Ty->getScalarType()->getTypeID()) {
15465   case Type::FloatTyID:
15466   case Type::DoubleTyID:
15467     return true;
15468   case Type::FP128TyID:
15469     return Subtarget.hasP9Vector();
15470   default:
15471     return false;
15472   }
15473 }
15474 
15475 // FIXME: add more patterns which are not profitable to hoist.
15476 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15477   if (!I->hasOneUse())
15478     return true;
15479 
15480   Instruction *User = I->user_back();
15481   assert(User && "A single use instruction with no uses.");
15482 
15483   switch (I->getOpcode()) {
15484   case Instruction::FMul: {
15485     // Don't break FMA, PowerPC prefers FMA.
15486     if (User->getOpcode() != Instruction::FSub &&
15487         User->getOpcode() != Instruction::FAdd)
15488       return true;
15489 
15490     const TargetOptions &Options = getTargetMachine().Options;
15491     const Function *F = I->getFunction();
15492     const DataLayout &DL = F->getParent()->getDataLayout();
15493     Type *Ty = User->getOperand(0)->getType();
15494 
15495     return !(
15496         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15497         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15498         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15499   }
15500   case Instruction::Load: {
15501     // Don't break "store (load float*)" pattern, this pattern will be combined
15502     // to "store (load int32)" in later InstCombine pass. See function
15503     // combineLoadToOperationType. On PowerPC, loading a float point takes more
15504     // cycles than loading a 32 bit integer.
15505     LoadInst *LI = cast<LoadInst>(I);
15506     // For the loads that combineLoadToOperationType does nothing, like
15507     // ordered load, it should be profitable to hoist them.
15508     // For swifterror load, it can only be used for pointer to pointer type, so
15509     // later type check should get rid of this case.
15510     if (!LI->isUnordered())
15511       return true;
15512 
15513     if (User->getOpcode() != Instruction::Store)
15514       return true;
15515 
15516     if (I->getType()->getTypeID() != Type::FloatTyID)
15517       return true;
15518 
15519     return false;
15520   }
15521   default:
15522     return true;
15523   }
15524   return true;
15525 }
15526 
15527 const MCPhysReg *
15528 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15529   // LR is a callee-save register, but we must treat it as clobbered by any call
15530   // site. Hence we include LR in the scratch registers, which are in turn added
15531   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15532   // to CTR, which is used by any indirect call.
15533   static const MCPhysReg ScratchRegs[] = {
15534     PPC::X12, PPC::LR8, PPC::CTR8, 0
15535   };
15536 
15537   return ScratchRegs;
15538 }
15539 
15540 Register PPCTargetLowering::getExceptionPointerRegister(
15541     const Constant *PersonalityFn) const {
15542   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15543 }
15544 
15545 Register PPCTargetLowering::getExceptionSelectorRegister(
15546     const Constant *PersonalityFn) const {
15547   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15548 }
15549 
15550 bool
15551 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15552                      EVT VT , unsigned DefinedValues) const {
15553   if (VT == MVT::v2i64)
15554     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15555 
15556   if (Subtarget.hasVSX())
15557     return true;
15558 
15559   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15560 }
15561 
15562 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15563   if (DisableILPPref || Subtarget.enableMachineScheduler())
15564     return TargetLowering::getSchedulingPreference(N);
15565 
15566   return Sched::ILP;
15567 }
15568 
15569 // Create a fast isel object.
15570 FastISel *
15571 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15572                                   const TargetLibraryInfo *LibInfo) const {
15573   return PPC::createFastISel(FuncInfo, LibInfo);
15574 }
15575 
15576 // 'Inverted' means the FMA opcode after negating one multiplicand.
15577 // For example, (fma -a b c) = (fnmsub a b c)
15578 static unsigned invertFMAOpcode(unsigned Opc) {
15579   switch (Opc) {
15580   default:
15581     llvm_unreachable("Invalid FMA opcode for PowerPC!");
15582   case ISD::FMA:
15583     return PPCISD::FNMSUB;
15584   case PPCISD::FNMSUB:
15585     return ISD::FMA;
15586   }
15587 }
15588 
15589 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
15590                                                 bool LegalOps, bool OptForSize,
15591                                                 NegatibleCost &Cost,
15592                                                 unsigned Depth) const {
15593   if (Depth > SelectionDAG::MaxRecursionDepth)
15594     return SDValue();
15595 
15596   unsigned Opc = Op.getOpcode();
15597   EVT VT = Op.getValueType();
15598   SDNodeFlags Flags = Op.getNode()->getFlags();
15599 
15600   switch (Opc) {
15601   case PPCISD::FNMSUB:
15602     if (!Op.hasOneUse() || !isTypeLegal(VT))
15603       break;
15604 
15605     const TargetOptions &Options = getTargetMachine().Options;
15606     SDValue N0 = Op.getOperand(0);
15607     SDValue N1 = Op.getOperand(1);
15608     SDValue N2 = Op.getOperand(2);
15609     SDLoc Loc(Op);
15610 
15611     NegatibleCost N2Cost = NegatibleCost::Expensive;
15612     SDValue NegN2 =
15613         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
15614 
15615     if (!NegN2)
15616       return SDValue();
15617 
15618     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
15619     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
15620     // These transformations may change sign of zeroes. For example,
15621     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
15622     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
15623       // Try and choose the cheaper one to negate.
15624       NegatibleCost N0Cost = NegatibleCost::Expensive;
15625       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
15626                                            N0Cost, Depth + 1);
15627 
15628       NegatibleCost N1Cost = NegatibleCost::Expensive;
15629       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
15630                                            N1Cost, Depth + 1);
15631 
15632       if (NegN0 && N0Cost <= N1Cost) {
15633         Cost = std::min(N0Cost, N2Cost);
15634         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
15635       } else if (NegN1) {
15636         Cost = std::min(N1Cost, N2Cost);
15637         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
15638       }
15639     }
15640 
15641     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
15642     if (isOperationLegal(ISD::FMA, VT)) {
15643       Cost = N2Cost;
15644       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
15645     }
15646 
15647     break;
15648   }
15649 
15650   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
15651                                               Cost, Depth);
15652 }
15653 
15654 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15655 bool PPCTargetLowering::useLoadStackGuardNode() const {
15656   if (!Subtarget.isTargetLinux())
15657     return TargetLowering::useLoadStackGuardNode();
15658   return true;
15659 }
15660 
15661 // Override to disable global variable loading on Linux.
15662 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15663   if (!Subtarget.isTargetLinux())
15664     return TargetLowering::insertSSPDeclarations(M);
15665 }
15666 
15667 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15668                                      bool ForCodeSize) const {
15669   if (!VT.isSimple() || !Subtarget.hasVSX())
15670     return false;
15671 
15672   switch(VT.getSimpleVT().SimpleTy) {
15673   default:
15674     // For FP types that are currently not supported by PPC backend, return
15675     // false. Examples: f16, f80.
15676     return false;
15677   case MVT::f32:
15678   case MVT::f64:
15679     if (Subtarget.hasPrefixInstrs()) {
15680       // With prefixed instructions, we can materialize anything that can be
15681       // represented with a 32-bit immediate, not just positive zero.
15682       APFloat APFloatOfImm = Imm;
15683       return convertToNonDenormSingle(APFloatOfImm);
15684     }
15685     LLVM_FALLTHROUGH;
15686   case MVT::ppcf128:
15687     return Imm.isPosZero();
15688   }
15689 }
15690 
15691 // For vector shift operation op, fold
15692 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15693 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15694                                   SelectionDAG &DAG) {
15695   SDValue N0 = N->getOperand(0);
15696   SDValue N1 = N->getOperand(1);
15697   EVT VT = N0.getValueType();
15698   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15699   unsigned Opcode = N->getOpcode();
15700   unsigned TargetOpcode;
15701 
15702   switch (Opcode) {
15703   default:
15704     llvm_unreachable("Unexpected shift operation");
15705   case ISD::SHL:
15706     TargetOpcode = PPCISD::SHL;
15707     break;
15708   case ISD::SRL:
15709     TargetOpcode = PPCISD::SRL;
15710     break;
15711   case ISD::SRA:
15712     TargetOpcode = PPCISD::SRA;
15713     break;
15714   }
15715 
15716   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15717       N1->getOpcode() == ISD::AND)
15718     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15719       if (Mask->getZExtValue() == OpSizeInBits - 1)
15720         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15721 
15722   return SDValue();
15723 }
15724 
15725 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15726   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15727     return Value;
15728 
15729   SDValue N0 = N->getOperand(0);
15730   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15731   if (!Subtarget.isISA3_0() ||
15732       N0.getOpcode() != ISD::SIGN_EXTEND ||
15733       N0.getOperand(0).getValueType() != MVT::i32 ||
15734       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15735     return SDValue();
15736 
15737   // We can't save an operation here if the value is already extended, and
15738   // the existing shift is easier to combine.
15739   SDValue ExtsSrc = N0.getOperand(0);
15740   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15741       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15742     return SDValue();
15743 
15744   SDLoc DL(N0);
15745   SDValue ShiftBy = SDValue(CN1, 0);
15746   // We want the shift amount to be i32 on the extswli, but the shift could
15747   // have an i64.
15748   if (ShiftBy.getValueType() == MVT::i64)
15749     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15750 
15751   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15752                          ShiftBy);
15753 }
15754 
15755 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15756   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15757     return Value;
15758 
15759   return SDValue();
15760 }
15761 
15762 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15763   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15764     return Value;
15765 
15766   return SDValue();
15767 }
15768 
15769 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15770 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15771 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15772 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15773 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15774                                  const PPCSubtarget &Subtarget) {
15775   if (!Subtarget.isPPC64())
15776     return SDValue();
15777 
15778   SDValue LHS = N->getOperand(0);
15779   SDValue RHS = N->getOperand(1);
15780 
15781   auto isZextOfCompareWithConstant = [](SDValue Op) {
15782     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15783         Op.getValueType() != MVT::i64)
15784       return false;
15785 
15786     SDValue Cmp = Op.getOperand(0);
15787     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15788         Cmp.getOperand(0).getValueType() != MVT::i64)
15789       return false;
15790 
15791     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15792       int64_t NegConstant = 0 - Constant->getSExtValue();
15793       // Due to the limitations of the addi instruction,
15794       // -C is required to be [-32768, 32767].
15795       return isInt<16>(NegConstant);
15796     }
15797 
15798     return false;
15799   };
15800 
15801   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15802   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15803 
15804   // If there is a pattern, canonicalize a zext operand to the RHS.
15805   if (LHSHasPattern && !RHSHasPattern)
15806     std::swap(LHS, RHS);
15807   else if (!LHSHasPattern && !RHSHasPattern)
15808     return SDValue();
15809 
15810   SDLoc DL(N);
15811   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15812   SDValue Cmp = RHS.getOperand(0);
15813   SDValue Z = Cmp.getOperand(0);
15814   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15815 
15816   assert(Constant && "Constant Should not be a null pointer.");
15817   int64_t NegConstant = 0 - Constant->getSExtValue();
15818 
15819   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15820   default: break;
15821   case ISD::SETNE: {
15822     //                                 when C == 0
15823     //                             --> addze X, (addic Z, -1).carry
15824     //                            /
15825     // add X, (zext(setne Z, C))--
15826     //                            \    when -32768 <= -C <= 32767 && C != 0
15827     //                             --> addze X, (addic (addi Z, -C), -1).carry
15828     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15829                               DAG.getConstant(NegConstant, DL, MVT::i64));
15830     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15831     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15832                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15833     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15834                        SDValue(Addc.getNode(), 1));
15835     }
15836   case ISD::SETEQ: {
15837     //                                 when C == 0
15838     //                             --> addze X, (subfic Z, 0).carry
15839     //                            /
15840     // add X, (zext(sete  Z, C))--
15841     //                            \    when -32768 <= -C <= 32767 && C != 0
15842     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15843     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15844                               DAG.getConstant(NegConstant, DL, MVT::i64));
15845     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15846     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15847                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15848     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15849                        SDValue(Subc.getNode(), 1));
15850     }
15851   }
15852 
15853   return SDValue();
15854 }
15855 
15856 // Transform
15857 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
15858 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
15859 // In this case both C1 and C2 must be known constants.
15860 // C1+C2 must fit into a 34 bit signed integer.
15861 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
15862                                           const PPCSubtarget &Subtarget) {
15863   if (!Subtarget.isUsingPCRelativeCalls())
15864     return SDValue();
15865 
15866   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
15867   // If we find that node try to cast the Global Address and the Constant.
15868   SDValue LHS = N->getOperand(0);
15869   SDValue RHS = N->getOperand(1);
15870 
15871   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
15872     std::swap(LHS, RHS);
15873 
15874   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
15875     return SDValue();
15876 
15877   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
15878   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
15879   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
15880 
15881   // Check that both casts succeeded.
15882   if (!GSDN || !ConstNode)
15883     return SDValue();
15884 
15885   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
15886   SDLoc DL(GSDN);
15887 
15888   // The signed int offset needs to fit in 34 bits.
15889   if (!isInt<34>(NewOffset))
15890     return SDValue();
15891 
15892   // The new global address is a copy of the old global address except
15893   // that it has the updated Offset.
15894   SDValue GA =
15895       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
15896                                  NewOffset, GSDN->getTargetFlags());
15897   SDValue MatPCRel =
15898       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
15899   return MatPCRel;
15900 }
15901 
15902 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15903   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15904     return Value;
15905 
15906   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
15907     return Value;
15908 
15909   return SDValue();
15910 }
15911 
15912 // Detect TRUNCATE operations on bitcasts of float128 values.
15913 // What we are looking for here is the situtation where we extract a subset
15914 // of bits from a 128 bit float.
15915 // This can be of two forms:
15916 // 1) BITCAST of f128 feeding TRUNCATE
15917 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15918 // The reason this is required is because we do not have a legal i128 type
15919 // and so we want to prevent having to store the f128 and then reload part
15920 // of it.
15921 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15922                                            DAGCombinerInfo &DCI) const {
15923   // If we are using CRBits then try that first.
15924   if (Subtarget.useCRBits()) {
15925     // Check if CRBits did anything and return that if it did.
15926     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15927       return CRTruncValue;
15928   }
15929 
15930   SDLoc dl(N);
15931   SDValue Op0 = N->getOperand(0);
15932 
15933   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
15934   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
15935     EVT VT = N->getValueType(0);
15936     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15937       return SDValue();
15938     SDValue Sub = Op0.getOperand(0);
15939     if (Sub.getOpcode() == ISD::SUB) {
15940       SDValue SubOp0 = Sub.getOperand(0);
15941       SDValue SubOp1 = Sub.getOperand(1);
15942       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
15943           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
15944         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
15945                                SubOp1.getOperand(0),
15946                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
15947       }
15948     }
15949   }
15950 
15951   // Looking for a truncate of i128 to i64.
15952   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15953     return SDValue();
15954 
15955   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15956 
15957   // SRL feeding TRUNCATE.
15958   if (Op0.getOpcode() == ISD::SRL) {
15959     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15960     // The right shift has to be by 64 bits.
15961     if (!ConstNode || ConstNode->getZExtValue() != 64)
15962       return SDValue();
15963 
15964     // Switch the element number to extract.
15965     EltToExtract = EltToExtract ? 0 : 1;
15966     // Update Op0 past the SRL.
15967     Op0 = Op0.getOperand(0);
15968   }
15969 
15970   // BITCAST feeding a TRUNCATE possibly via SRL.
15971   if (Op0.getOpcode() == ISD::BITCAST &&
15972       Op0.getValueType() == MVT::i128 &&
15973       Op0.getOperand(0).getValueType() == MVT::f128) {
15974     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15975     return DCI.DAG.getNode(
15976         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15977         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15978   }
15979   return SDValue();
15980 }
15981 
15982 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15983   SelectionDAG &DAG = DCI.DAG;
15984 
15985   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15986   if (!ConstOpOrElement)
15987     return SDValue();
15988 
15989   // An imul is usually smaller than the alternative sequence for legal type.
15990   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15991       isOperationLegal(ISD::MUL, N->getValueType(0)))
15992     return SDValue();
15993 
15994   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15995     switch (this->Subtarget.getCPUDirective()) {
15996     default:
15997       // TODO: enhance the condition for subtarget before pwr8
15998       return false;
15999     case PPC::DIR_PWR8:
16000       //  type        mul     add    shl
16001       // scalar        4       1      1
16002       // vector        7       2      2
16003       return true;
16004     case PPC::DIR_PWR9:
16005     case PPC::DIR_PWR10:
16006     case PPC::DIR_PWR_FUTURE:
16007       //  type        mul     add    shl
16008       // scalar        5       2      2
16009       // vector        7       2      2
16010 
16011       // The cycle RATIO of related operations are showed as a table above.
16012       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16013       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16014       // are 4, it is always profitable; but for 3 instrs patterns
16015       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16016       // So we should only do it for vector type.
16017       return IsAddOne && IsNeg ? VT.isVector() : true;
16018     }
16019   };
16020 
16021   EVT VT = N->getValueType(0);
16022   SDLoc DL(N);
16023 
16024   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16025   bool IsNeg = MulAmt.isNegative();
16026   APInt MulAmtAbs = MulAmt.abs();
16027 
16028   if ((MulAmtAbs - 1).isPowerOf2()) {
16029     // (mul x, 2^N + 1) => (add (shl x, N), x)
16030     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16031 
16032     if (!IsProfitable(IsNeg, true, VT))
16033       return SDValue();
16034 
16035     SDValue Op0 = N->getOperand(0);
16036     SDValue Op1 =
16037         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16038                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16039     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16040 
16041     if (!IsNeg)
16042       return Res;
16043 
16044     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16045   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16046     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16047     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16048 
16049     if (!IsProfitable(IsNeg, false, VT))
16050       return SDValue();
16051 
16052     SDValue Op0 = N->getOperand(0);
16053     SDValue Op1 =
16054         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16055                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16056 
16057     if (!IsNeg)
16058       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16059     else
16060       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16061 
16062   } else {
16063     return SDValue();
16064   }
16065 }
16066 
16067 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16068 // in combiner since we need to check SD flags and other subtarget features.
16069 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16070                                           DAGCombinerInfo &DCI) const {
16071   SDValue N0 = N->getOperand(0);
16072   SDValue N1 = N->getOperand(1);
16073   SDValue N2 = N->getOperand(2);
16074   SDNodeFlags Flags = N->getFlags();
16075   EVT VT = N->getValueType(0);
16076   SelectionDAG &DAG = DCI.DAG;
16077   const TargetOptions &Options = getTargetMachine().Options;
16078   unsigned Opc = N->getOpcode();
16079   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16080   bool LegalOps = !DCI.isBeforeLegalizeOps();
16081   SDLoc Loc(N);
16082 
16083   if (!isOperationLegal(ISD::FMA, VT))
16084     return SDValue();
16085 
16086   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16087   // since (fnmsub a b c)=-0 while c-ab=+0.
16088   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16089     return SDValue();
16090 
16091   // (fma (fneg a) b c) => (fnmsub a b c)
16092   // (fnmsub (fneg a) b c) => (fma a b c)
16093   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16094     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16095 
16096   // (fma a (fneg b) c) => (fnmsub a b c)
16097   // (fnmsub a (fneg b) c) => (fma a b c)
16098   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16099     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16100 
16101   return SDValue();
16102 }
16103 
16104 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16105   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16106   if (!Subtarget.is64BitELFABI())
16107     return false;
16108 
16109   // If not a tail call then no need to proceed.
16110   if (!CI->isTailCall())
16111     return false;
16112 
16113   // If sibling calls have been disabled and tail-calls aren't guaranteed
16114   // there is no reason to duplicate.
16115   auto &TM = getTargetMachine();
16116   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16117     return false;
16118 
16119   // Can't tail call a function called indirectly, or if it has variadic args.
16120   const Function *Callee = CI->getCalledFunction();
16121   if (!Callee || Callee->isVarArg())
16122     return false;
16123 
16124   // Make sure the callee and caller calling conventions are eligible for tco.
16125   const Function *Caller = CI->getParent()->getParent();
16126   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16127                                            CI->getCallingConv()))
16128       return false;
16129 
16130   // If the function is local then we have a good chance at tail-calling it
16131   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16132 }
16133 
16134 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16135   if (!Subtarget.hasVSX())
16136     return false;
16137   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16138     return true;
16139   return VT == MVT::f32 || VT == MVT::f64 ||
16140     VT == MVT::v4f32 || VT == MVT::v2f64;
16141 }
16142 
16143 bool PPCTargetLowering::
16144 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16145   const Value *Mask = AndI.getOperand(1);
16146   // If the mask is suitable for andi. or andis. we should sink the and.
16147   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16148     // Can't handle constants wider than 64-bits.
16149     if (CI->getBitWidth() > 64)
16150       return false;
16151     int64_t ConstVal = CI->getZExtValue();
16152     return isUInt<16>(ConstVal) ||
16153       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16154   }
16155 
16156   // For non-constant masks, we can always use the record-form and.
16157   return true;
16158 }
16159 
16160 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16161 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16162 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16163 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16164 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16165 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16166   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16167   assert(Subtarget.hasP9Altivec() &&
16168          "Only combine this when P9 altivec supported!");
16169   EVT VT = N->getValueType(0);
16170   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16171     return SDValue();
16172 
16173   SelectionDAG &DAG = DCI.DAG;
16174   SDLoc dl(N);
16175   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16176     // Even for signed integers, if it's known to be positive (as signed
16177     // integer) due to zero-extended inputs.
16178     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16179     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16180     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16181          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16182         (SubOpcd1 == ISD::ZERO_EXTEND ||
16183          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16184       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16185                          N->getOperand(0)->getOperand(0),
16186                          N->getOperand(0)->getOperand(1),
16187                          DAG.getTargetConstant(0, dl, MVT::i32));
16188     }
16189 
16190     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16191     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16192         N->getOperand(0).hasOneUse()) {
16193       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16194                          N->getOperand(0)->getOperand(0),
16195                          N->getOperand(0)->getOperand(1),
16196                          DAG.getTargetConstant(1, dl, MVT::i32));
16197     }
16198   }
16199 
16200   return SDValue();
16201 }
16202 
16203 // For type v4i32/v8ii16/v16i8, transform
16204 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16205 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16206 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16207 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16208 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16209                                           DAGCombinerInfo &DCI) const {
16210   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16211   assert(Subtarget.hasP9Altivec() &&
16212          "Only combine this when P9 altivec supported!");
16213 
16214   SelectionDAG &DAG = DCI.DAG;
16215   SDLoc dl(N);
16216   SDValue Cond = N->getOperand(0);
16217   SDValue TrueOpnd = N->getOperand(1);
16218   SDValue FalseOpnd = N->getOperand(2);
16219   EVT VT = N->getOperand(1).getValueType();
16220 
16221   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16222       FalseOpnd.getOpcode() != ISD::SUB)
16223     return SDValue();
16224 
16225   // ABSD only available for type v4i32/v8i16/v16i8
16226   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16227     return SDValue();
16228 
16229   // At least to save one more dependent computation
16230   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16231     return SDValue();
16232 
16233   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16234 
16235   // Can only handle unsigned comparison here
16236   switch (CC) {
16237   default:
16238     return SDValue();
16239   case ISD::SETUGT:
16240   case ISD::SETUGE:
16241     break;
16242   case ISD::SETULT:
16243   case ISD::SETULE:
16244     std::swap(TrueOpnd, FalseOpnd);
16245     break;
16246   }
16247 
16248   SDValue CmpOpnd1 = Cond.getOperand(0);
16249   SDValue CmpOpnd2 = Cond.getOperand(1);
16250 
16251   // SETCC CmpOpnd1 CmpOpnd2 cond
16252   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16253   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16254   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16255       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16256       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16257       FalseOpnd.getOperand(1) == CmpOpnd1) {
16258     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16259                        CmpOpnd1, CmpOpnd2,
16260                        DAG.getTargetConstant(0, dl, MVT::i32));
16261   }
16262 
16263   return SDValue();
16264 }
16265