1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPC.h"
17 #include "PPCCCState.h"
18 #include "PPCCallingConv.h"
19 #include "PPCFrameLowering.h"
20 #include "PPCInstrInfo.h"
21 #include "PPCMachineFunctionInfo.h"
22 #include "PPCPerfectShuffle.h"
23 #include "PPCRegisterInfo.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "llvm/ADT/APFloat.h"
27 #include "llvm/ADT/APInt.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/CodeGen/CallingConvLower.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineLoopInfo.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/MachineValueType.h"
51 #include "llvm/CodeGen/RuntimeLibcalls.h"
52 #include "llvm/CodeGen/SelectionDAG.h"
53 #include "llvm/CodeGen/SelectionDAGNodes.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/IR/CallSite.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/Constant.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Function.h"
63 #include "llvm/IR/GlobalValue.h"
64 #include "llvm/IR/IRBuilder.h"
65 #include "llvm/IR/Instructions.h"
66 #include "llvm/IR/Intrinsics.h"
67 #include "llvm/IR/Module.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/MC/MCExpr.h"
72 #include "llvm/MC/MCRegisterInfo.h"
73 #include "llvm/Support/AtomicOrdering.h"
74 #include "llvm/Support/BranchProbability.h"
75 #include "llvm/Support/Casting.h"
76 #include "llvm/Support/CodeGen.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/ErrorHandling.h"
81 #include "llvm/Support/Format.h"
82 #include "llvm/Support/KnownBits.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetInstrInfo.h"
86 #include "llvm/Target/TargetLowering.h"
87 #include "llvm/Target/TargetMachine.h"
88 #include "llvm/Target/TargetOptions.h"
89 #include "llvm/Target/TargetRegisterInfo.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <list>
95 #include <utility>
96 #include <vector>
97 
98 using namespace llvm;
99 
100 #define DEBUG_TYPE "ppc-lowering"
101 
102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
104 
105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisableSCO("disable-ppc-sco",
112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
113 
114 STATISTIC(NumTailCalls, "Number of tail calls");
115 STATISTIC(NumSiblingCalls, "Number of sibling calls");
116 
117 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
118 
119 // FIXME: Remove this once the bug has been fixed!
120 extern cl::opt<bool> ANDIGlueBug;
121 
122 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
123                                      const PPCSubtarget &STI)
124     : TargetLowering(TM), Subtarget(STI) {
125   // Use _setjmp/_longjmp instead of setjmp/longjmp.
126   setUseUnderscoreSetJmp(true);
127   setUseUnderscoreLongJmp(true);
128 
129   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
130   // arguments are at least 4/8 bytes aligned.
131   bool isPPC64 = Subtarget.isPPC64();
132   setMinStackArgumentAlignment(isPPC64 ? 8:4);
133 
134   // Set up the register classes.
135   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
136   if (!useSoftFloat()) {
137     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
138     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
139   }
140 
141   // Match BITREVERSE to customized fast code sequence in the td file.
142   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
143   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
144 
145   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
146   for (MVT VT : MVT::integer_valuetypes()) {
147     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
148     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
149   }
150 
151   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152 
153   // PowerPC has pre-inc load and store's.
154   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
155   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
156   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
157   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
158   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
159   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
160   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
161   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
162   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
163   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
164   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
165   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
166   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
167   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
168 
169   if (Subtarget.useCRBits()) {
170     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
171 
172     if (isPPC64 || Subtarget.hasFPCVT()) {
173       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
174       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
175                          isPPC64 ? MVT::i64 : MVT::i32);
176       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
177       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
178                         isPPC64 ? MVT::i64 : MVT::i32);
179     } else {
180       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
181       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
182     }
183 
184     // PowerPC does not support direct load/store of condition registers.
185     setOperationAction(ISD::LOAD, MVT::i1, Custom);
186     setOperationAction(ISD::STORE, MVT::i1, Custom);
187 
188     // FIXME: Remove this once the ANDI glue bug is fixed:
189     if (ANDIGlueBug)
190       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
191 
192     for (MVT VT : MVT::integer_valuetypes()) {
193       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
194       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
195       setTruncStoreAction(VT, MVT::i1, Expand);
196     }
197 
198     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
199   }
200 
201   // This is used in the ppcf128->int sequence.  Note it has different semantics
202   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
203   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
204 
205   // We do not currently implement these libm ops for PowerPC.
206   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
207   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
208   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
209   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
210   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
211   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
212 
213   // PowerPC has no SREM/UREM instructions unless we are on P9
214   // On P9 we may use a hardware instruction to compute the remainder.
215   // The instructions are not legalized directly because in the cases where the
216   // result of both the remainder and the division is required it is more
217   // efficient to compute the remainder from the result of the division rather
218   // than use the remainder instruction.
219   if (Subtarget.isISA3_0()) {
220     setOperationAction(ISD::SREM, MVT::i32, Custom);
221     setOperationAction(ISD::UREM, MVT::i32, Custom);
222     setOperationAction(ISD::SREM, MVT::i64, Custom);
223     setOperationAction(ISD::UREM, MVT::i64, Custom);
224   } else {
225     setOperationAction(ISD::SREM, MVT::i32, Expand);
226     setOperationAction(ISD::UREM, MVT::i32, Expand);
227     setOperationAction(ISD::SREM, MVT::i64, Expand);
228     setOperationAction(ISD::UREM, MVT::i64, Expand);
229   }
230 
231   if (Subtarget.hasP9Vector()) {
232     setOperationAction(ISD::ABS, MVT::v4i32, Legal);
233     setOperationAction(ISD::ABS, MVT::v8i16, Legal);
234     setOperationAction(ISD::ABS, MVT::v16i8, Legal);
235   }
236 
237   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
238   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
239   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
240   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
241   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
242   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
243   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
244   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
245   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
246 
247   // We don't support sin/cos/sqrt/fmod/pow
248   setOperationAction(ISD::FSIN , MVT::f64, Expand);
249   setOperationAction(ISD::FCOS , MVT::f64, Expand);
250   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
251   setOperationAction(ISD::FREM , MVT::f64, Expand);
252   setOperationAction(ISD::FPOW , MVT::f64, Expand);
253   setOperationAction(ISD::FMA  , MVT::f64, Legal);
254   setOperationAction(ISD::FSIN , MVT::f32, Expand);
255   setOperationAction(ISD::FCOS , MVT::f32, Expand);
256   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
257   setOperationAction(ISD::FREM , MVT::f32, Expand);
258   setOperationAction(ISD::FPOW , MVT::f32, Expand);
259   setOperationAction(ISD::FMA  , MVT::f32, Legal);
260 
261   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
262 
263   // If we're enabling GP optimizations, use hardware square root
264   if (!Subtarget.hasFSQRT() &&
265       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
266         Subtarget.hasFRE()))
267     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
268 
269   if (!Subtarget.hasFSQRT() &&
270       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
271         Subtarget.hasFRES()))
272     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
273 
274   if (Subtarget.hasFCPSGN()) {
275     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
276     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
277   } else {
278     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
279     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
280   }
281 
282   if (Subtarget.hasFPRND()) {
283     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
284     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
285     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
286     setOperationAction(ISD::FROUND, MVT::f64, Legal);
287 
288     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
289     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
290     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
291     setOperationAction(ISD::FROUND, MVT::f32, Legal);
292   }
293 
294   // PowerPC does not have BSWAP
295   // CTPOP or CTTZ were introduced in P8/P9 respectivelly
296   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
297   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
298   if (Subtarget.isISA3_0()) {
299     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
300     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
301   } else {
302     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
303     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
304   }
305 
306   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
307     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
308     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
309   } else {
310     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
311     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
312   }
313 
314   // PowerPC does not have ROTR
315   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
316   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
317 
318   if (!Subtarget.useCRBits()) {
319     // PowerPC does not have Select
320     setOperationAction(ISD::SELECT, MVT::i32, Expand);
321     setOperationAction(ISD::SELECT, MVT::i64, Expand);
322     setOperationAction(ISD::SELECT, MVT::f32, Expand);
323     setOperationAction(ISD::SELECT, MVT::f64, Expand);
324   }
325 
326   // PowerPC wants to turn select_cc of FP into fsel when possible.
327   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
328   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
329 
330   // PowerPC wants to optimize integer setcc a bit
331   if (!Subtarget.useCRBits())
332     setOperationAction(ISD::SETCC, MVT::i32, Custom);
333 
334   // PowerPC does not have BRCOND which requires SetCC
335   if (!Subtarget.useCRBits())
336     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
337 
338   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
339 
340   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
341   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
342 
343   // PowerPC does not have [U|S]INT_TO_FP
344   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
345   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
346 
347   if (Subtarget.hasDirectMove() && isPPC64) {
348     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
349     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
350     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
351     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
352   } else {
353     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
354     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
355     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
356     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
357   }
358 
359   // We cannot sextinreg(i1).  Expand to shifts.
360   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
361 
362   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
363   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
364   // support continuation, user-level threading, and etc.. As a result, no
365   // other SjLj exception interfaces are implemented and please don't build
366   // your own exception handling based on them.
367   // LLVM/Clang supports zero-cost DWARF exception handling.
368   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
369   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
370 
371   // We want to legalize GlobalAddress and ConstantPool nodes into the
372   // appropriate instructions to materialize the address.
373   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
374   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
375   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
376   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
377   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
378   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
379   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
380   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
381   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
382   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
383 
384   // TRAP is legal.
385   setOperationAction(ISD::TRAP, MVT::Other, Legal);
386 
387   // TRAMPOLINE is custom lowered.
388   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
389   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
390 
391   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
392   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
393 
394   if (Subtarget.isSVR4ABI()) {
395     if (isPPC64) {
396       // VAARG always uses double-word chunks, so promote anything smaller.
397       setOperationAction(ISD::VAARG, MVT::i1, Promote);
398       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
399       setOperationAction(ISD::VAARG, MVT::i8, Promote);
400       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
401       setOperationAction(ISD::VAARG, MVT::i16, Promote);
402       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
403       setOperationAction(ISD::VAARG, MVT::i32, Promote);
404       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
405       setOperationAction(ISD::VAARG, MVT::Other, Expand);
406     } else {
407       // VAARG is custom lowered with the 32-bit SVR4 ABI.
408       setOperationAction(ISD::VAARG, MVT::Other, Custom);
409       setOperationAction(ISD::VAARG, MVT::i64, Custom);
410     }
411   } else
412     setOperationAction(ISD::VAARG, MVT::Other, Expand);
413 
414   if (Subtarget.isSVR4ABI() && !isPPC64)
415     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
416     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
417   else
418     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
419 
420   // Use the default implementation.
421   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
422   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
423   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
424   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
425   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
426   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
427   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
428   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
429   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
430 
431   // We want to custom lower some of our intrinsics.
432   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
433 
434   // To handle counter-based loop conditions.
435   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
436 
437   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
438   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
439   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
440   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
441 
442   // Comparisons that require checking two conditions.
443   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
444   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
445   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
446   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
447   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
448   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
449   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
450   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
451   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
452   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
453   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
454   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
455 
456   if (Subtarget.has64BitSupport()) {
457     // They also have instructions for converting between i64 and fp.
458     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
459     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
460     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
461     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
462     // This is just the low 32 bits of a (signed) fp->i64 conversion.
463     // We cannot do this with Promote because i64 is not a legal type.
464     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
465 
466     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
467       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
468   } else {
469     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
470     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
471   }
472 
473   // With the instructions enabled under FPCVT, we can do everything.
474   if (Subtarget.hasFPCVT()) {
475     if (Subtarget.has64BitSupport()) {
476       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
477       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
478       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
479       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
480     }
481 
482     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
483     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
484     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
485     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
486   }
487 
488   if (Subtarget.use64BitRegs()) {
489     // 64-bit PowerPC implementations can support i64 types directly
490     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
491     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
492     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
493     // 64-bit PowerPC wants to expand i128 shifts itself.
494     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
495     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
496     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
497   } else {
498     // 32-bit PowerPC wants to expand i64 shifts itself.
499     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
500     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
501     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
502   }
503 
504   if (Subtarget.hasAltivec()) {
505     // First set operation action for all vector types to expand. Then we
506     // will selectively turn on ones that can be effectively codegen'd.
507     for (MVT VT : MVT::vector_valuetypes()) {
508       // add/sub are legal for all supported vector VT's.
509       setOperationAction(ISD::ADD, VT, Legal);
510       setOperationAction(ISD::SUB, VT, Legal);
511 
512       // Vector instructions introduced in P8
513       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
514         setOperationAction(ISD::CTPOP, VT, Legal);
515         setOperationAction(ISD::CTLZ, VT, Legal);
516       }
517       else {
518         setOperationAction(ISD::CTPOP, VT, Expand);
519         setOperationAction(ISD::CTLZ, VT, Expand);
520       }
521 
522       // Vector instructions introduced in P9
523       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
524         setOperationAction(ISD::CTTZ, VT, Legal);
525       else
526         setOperationAction(ISD::CTTZ, VT, Expand);
527 
528       // We promote all shuffles to v16i8.
529       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
530       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
531 
532       // We promote all non-typed operations to v4i32.
533       setOperationAction(ISD::AND   , VT, Promote);
534       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
535       setOperationAction(ISD::OR    , VT, Promote);
536       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
537       setOperationAction(ISD::XOR   , VT, Promote);
538       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
539       setOperationAction(ISD::LOAD  , VT, Promote);
540       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
541       setOperationAction(ISD::SELECT, VT, Promote);
542       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
543       setOperationAction(ISD::SELECT_CC, VT, Promote);
544       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
545       setOperationAction(ISD::STORE, VT, Promote);
546       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
547 
548       // No other operations are legal.
549       setOperationAction(ISD::MUL , VT, Expand);
550       setOperationAction(ISD::SDIV, VT, Expand);
551       setOperationAction(ISD::SREM, VT, Expand);
552       setOperationAction(ISD::UDIV, VT, Expand);
553       setOperationAction(ISD::UREM, VT, Expand);
554       setOperationAction(ISD::FDIV, VT, Expand);
555       setOperationAction(ISD::FREM, VT, Expand);
556       setOperationAction(ISD::FNEG, VT, Expand);
557       setOperationAction(ISD::FSQRT, VT, Expand);
558       setOperationAction(ISD::FLOG, VT, Expand);
559       setOperationAction(ISD::FLOG10, VT, Expand);
560       setOperationAction(ISD::FLOG2, VT, Expand);
561       setOperationAction(ISD::FEXP, VT, Expand);
562       setOperationAction(ISD::FEXP2, VT, Expand);
563       setOperationAction(ISD::FSIN, VT, Expand);
564       setOperationAction(ISD::FCOS, VT, Expand);
565       setOperationAction(ISD::FABS, VT, Expand);
566       setOperationAction(ISD::FFLOOR, VT, Expand);
567       setOperationAction(ISD::FCEIL,  VT, Expand);
568       setOperationAction(ISD::FTRUNC, VT, Expand);
569       setOperationAction(ISD::FRINT,  VT, Expand);
570       setOperationAction(ISD::FNEARBYINT, VT, Expand);
571       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
572       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
573       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
574       setOperationAction(ISD::MULHU, VT, Expand);
575       setOperationAction(ISD::MULHS, VT, Expand);
576       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
577       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
578       setOperationAction(ISD::UDIVREM, VT, Expand);
579       setOperationAction(ISD::SDIVREM, VT, Expand);
580       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
581       setOperationAction(ISD::FPOW, VT, Expand);
582       setOperationAction(ISD::BSWAP, VT, Expand);
583       setOperationAction(ISD::VSELECT, VT, Expand);
584       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
585       setOperationAction(ISD::ROTL, VT, Expand);
586       setOperationAction(ISD::ROTR, VT, Expand);
587 
588       for (MVT InnerVT : MVT::vector_valuetypes()) {
589         setTruncStoreAction(VT, InnerVT, Expand);
590         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
591         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
592         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
593       }
594     }
595 
596     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
597     // with merges, splats, etc.
598     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
599 
600     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
601     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
602     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
603     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
604     setOperationAction(ISD::SELECT, MVT::v4i32,
605                        Subtarget.useCRBits() ? Legal : Expand);
606     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
607     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
608     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
609     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
610     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
611     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
612     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
613     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
614     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
615 
616     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
617     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
618     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
619     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
620 
621     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
622     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
623 
624     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
625       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
626       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
627     }
628 
629     if (Subtarget.hasP8Altivec())
630       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
631     else
632       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
633 
634     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
635     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
636 
637     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
638     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
639 
640     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
641     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
642     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
643     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
644 
645     // Altivec does not contain unordered floating-point compare instructions
646     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
647     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
648     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
649     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
650 
651     if (Subtarget.hasVSX()) {
652       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
653       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
654       if (Subtarget.hasP8Vector()) {
655         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
656         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
657       }
658       if (Subtarget.hasDirectMove() && isPPC64) {
659         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
660         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
661         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
662         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
663         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
664         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
665         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
666         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
667       }
668       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
669 
670       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
671       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
672       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
673       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
674       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
675 
676       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
677 
678       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
679       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
680 
681       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
682       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
683 
684       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
685       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
686       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
687       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
688       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
689 
690       // Share the Altivec comparison restrictions.
691       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
692       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
693       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
694       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
695 
696       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
697       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
698 
699       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
700 
701       if (Subtarget.hasP8Vector())
702         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
703 
704       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
705 
706       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
707       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
708       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
709 
710       if (Subtarget.hasP8Altivec()) {
711         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
712         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
713         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
714 
715         // 128 bit shifts can be accomplished via 3 instructions for SHL and
716         // SRL, but not for SRA because of the instructions available:
717         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
718         // doing
719         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
720         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
721         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
722 
723         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
724       }
725       else {
726         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
727         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
728         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
729 
730         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
731 
732         // VSX v2i64 only supports non-arithmetic operations.
733         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
734         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
735       }
736 
737       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
738       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
739       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
740       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
741 
742       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
743 
744       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
745       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
746       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
747       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
748 
749       // Vector operation legalization checks the result type of
750       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
751       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
752       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
753       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
754       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
755 
756       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
757       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
758       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
759       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
760 
761       if (Subtarget.hasDirectMove())
762         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
763       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
764 
765       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
766     }
767 
768     if (Subtarget.hasP8Altivec()) {
769       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
770       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
771     }
772 
773     if (Subtarget.hasP9Vector()) {
774       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
775       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
776 
777       // 128 bit shifts can be accomplished via 3 instructions for SHL and
778       // SRL, but not for SRA because of the instructions available:
779       // VS{RL} and VS{RL}O.
780       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
781       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
782       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
783     }
784   }
785 
786   if (Subtarget.hasQPX()) {
787     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
788     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
789     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
790     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
791 
792     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
793     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
794 
795     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
796     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
797 
798     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
799     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
800 
801     if (!Subtarget.useCRBits())
802       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
803     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
804 
805     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
806     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
807     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
808     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
809     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
810     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
811     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
812 
813     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
814     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
815 
816     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
817     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
818     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
819 
820     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
821     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
822     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
823     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
824     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
825     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
826     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
827     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
828     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
829     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
830 
831     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
832     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
833 
834     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
835     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
836 
837     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
838 
839     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
840     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
841     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
842     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
843 
844     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
845     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
846 
847     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
848     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
849 
850     if (!Subtarget.useCRBits())
851       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
852     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
853 
854     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
855     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
856     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
857     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
858     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
859     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
860     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
861 
862     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
863     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
864 
865     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
866     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
867     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
868     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
869     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
870     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
871     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
872     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
873     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
874     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
875 
876     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
877     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
878 
879     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
880     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
881 
882     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
883 
884     setOperationAction(ISD::AND , MVT::v4i1, Legal);
885     setOperationAction(ISD::OR , MVT::v4i1, Legal);
886     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
887 
888     if (!Subtarget.useCRBits())
889       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
890     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
891 
892     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
893     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
894 
895     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
896     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
897     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
898     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
899     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
900     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
901     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
902 
903     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
904     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
905 
906     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
907 
908     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
909     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
910     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
911     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
912 
913     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
914     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
915     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
916     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
917 
918     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
919     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
920 
921     // These need to set FE_INEXACT, and so cannot be vectorized here.
922     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
923     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
924 
925     if (TM.Options.UnsafeFPMath) {
926       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
927       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
928 
929       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
930       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
931     } else {
932       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
933       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
934 
935       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
936       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
937     }
938   }
939 
940   if (Subtarget.has64BitSupport())
941     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
942 
943   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
944 
945   if (!isPPC64) {
946     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
947     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
948   }
949 
950   setBooleanContents(ZeroOrOneBooleanContent);
951 
952   if (Subtarget.hasAltivec()) {
953     // Altivec instructions set fields to all zeros or all ones.
954     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
955   }
956 
957   if (!isPPC64) {
958     // These libcalls are not available in 32-bit.
959     setLibcallName(RTLIB::SHL_I128, nullptr);
960     setLibcallName(RTLIB::SRL_I128, nullptr);
961     setLibcallName(RTLIB::SRA_I128, nullptr);
962   }
963 
964   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
965 
966   // We have target-specific dag combine patterns for the following nodes:
967   setTargetDAGCombine(ISD::SHL);
968   setTargetDAGCombine(ISD::SRA);
969   setTargetDAGCombine(ISD::SRL);
970   setTargetDAGCombine(ISD::SINT_TO_FP);
971   setTargetDAGCombine(ISD::BUILD_VECTOR);
972   if (Subtarget.hasFPCVT())
973     setTargetDAGCombine(ISD::UINT_TO_FP);
974   setTargetDAGCombine(ISD::LOAD);
975   setTargetDAGCombine(ISD::STORE);
976   setTargetDAGCombine(ISD::BR_CC);
977   if (Subtarget.useCRBits())
978     setTargetDAGCombine(ISD::BRCOND);
979   setTargetDAGCombine(ISD::BSWAP);
980   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
981   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
982   setTargetDAGCombine(ISD::INTRINSIC_VOID);
983 
984   setTargetDAGCombine(ISD::SIGN_EXTEND);
985   setTargetDAGCombine(ISD::ZERO_EXTEND);
986   setTargetDAGCombine(ISD::ANY_EXTEND);
987 
988   if (Subtarget.useCRBits()) {
989     setTargetDAGCombine(ISD::TRUNCATE);
990     setTargetDAGCombine(ISD::SETCC);
991     setTargetDAGCombine(ISD::SELECT_CC);
992   }
993 
994   // Use reciprocal estimates.
995   if (TM.Options.UnsafeFPMath) {
996     setTargetDAGCombine(ISD::FDIV);
997     setTargetDAGCombine(ISD::FSQRT);
998   }
999 
1000   // Darwin long double math library functions have $LDBL128 appended.
1001   if (Subtarget.isDarwin()) {
1002     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1003     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1004     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1005     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1006     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1007     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1008     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1009     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1010     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1011     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1012   }
1013 
1014   // With 32 condition bits, we don't need to sink (and duplicate) compares
1015   // aggressively in CodeGenPrep.
1016   if (Subtarget.useCRBits()) {
1017     setHasMultipleConditionRegisters();
1018     setJumpIsExpensive();
1019   }
1020 
1021   setMinFunctionAlignment(2);
1022   if (Subtarget.isDarwin())
1023     setPrefFunctionAlignment(4);
1024 
1025   switch (Subtarget.getDarwinDirective()) {
1026   default: break;
1027   case PPC::DIR_970:
1028   case PPC::DIR_A2:
1029   case PPC::DIR_E500mc:
1030   case PPC::DIR_E5500:
1031   case PPC::DIR_PWR4:
1032   case PPC::DIR_PWR5:
1033   case PPC::DIR_PWR5X:
1034   case PPC::DIR_PWR6:
1035   case PPC::DIR_PWR6X:
1036   case PPC::DIR_PWR7:
1037   case PPC::DIR_PWR8:
1038   case PPC::DIR_PWR9:
1039     setPrefFunctionAlignment(4);
1040     setPrefLoopAlignment(4);
1041     break;
1042   }
1043 
1044   if (Subtarget.enableMachineScheduler())
1045     setSchedulingPreference(Sched::Source);
1046   else
1047     setSchedulingPreference(Sched::Hybrid);
1048 
1049   computeRegisterProperties(STI.getRegisterInfo());
1050 
1051   // The Freescale cores do better with aggressive inlining of memcpy and
1052   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1053   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1054       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1055     MaxStoresPerMemset = 32;
1056     MaxStoresPerMemsetOptSize = 16;
1057     MaxStoresPerMemcpy = 32;
1058     MaxStoresPerMemcpyOptSize = 8;
1059     MaxStoresPerMemmove = 32;
1060     MaxStoresPerMemmoveOptSize = 8;
1061   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1062     // The A2 also benefits from (very) aggressive inlining of memcpy and
1063     // friends. The overhead of a the function call, even when warm, can be
1064     // over one hundred cycles.
1065     MaxStoresPerMemset = 128;
1066     MaxStoresPerMemcpy = 128;
1067     MaxStoresPerMemmove = 128;
1068     MaxLoadsPerMemcmp = 128;
1069   } else {
1070     MaxLoadsPerMemcmp = 8;
1071     MaxLoadsPerMemcmpOptSize = 4;
1072   }
1073 }
1074 
1075 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1076 /// the desired ByVal argument alignment.
1077 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1078                              unsigned MaxMaxAlign) {
1079   if (MaxAlign == MaxMaxAlign)
1080     return;
1081   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1082     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1083       MaxAlign = 32;
1084     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1085       MaxAlign = 16;
1086   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1087     unsigned EltAlign = 0;
1088     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1089     if (EltAlign > MaxAlign)
1090       MaxAlign = EltAlign;
1091   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1092     for (auto *EltTy : STy->elements()) {
1093       unsigned EltAlign = 0;
1094       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1095       if (EltAlign > MaxAlign)
1096         MaxAlign = EltAlign;
1097       if (MaxAlign == MaxMaxAlign)
1098         break;
1099     }
1100   }
1101 }
1102 
1103 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1104 /// function arguments in the caller parameter area.
1105 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1106                                                   const DataLayout &DL) const {
1107   // Darwin passes everything on 4 byte boundary.
1108   if (Subtarget.isDarwin())
1109     return 4;
1110 
1111   // 16byte and wider vectors are passed on 16byte boundary.
1112   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1113   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1114   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1115     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1116   return Align;
1117 }
1118 
1119 bool PPCTargetLowering::useSoftFloat() const {
1120   return Subtarget.useSoftFloat();
1121 }
1122 
1123 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1124   switch ((PPCISD::NodeType)Opcode) {
1125   case PPCISD::FIRST_NUMBER:    break;
1126   case PPCISD::FSEL:            return "PPCISD::FSEL";
1127   case PPCISD::FCFID:           return "PPCISD::FCFID";
1128   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1129   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1130   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1131   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1132   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1133   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1134   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1135   case PPCISD::FRE:             return "PPCISD::FRE";
1136   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1137   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1138   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1139   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1140   case PPCISD::VPERM:           return "PPCISD::VPERM";
1141   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1142   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1143   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1144   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1145   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1146   case PPCISD::CMPB:            return "PPCISD::CMPB";
1147   case PPCISD::Hi:              return "PPCISD::Hi";
1148   case PPCISD::Lo:              return "PPCISD::Lo";
1149   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1150   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1151   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1152   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1153   case PPCISD::SRL:             return "PPCISD::SRL";
1154   case PPCISD::SRA:             return "PPCISD::SRA";
1155   case PPCISD::SHL:             return "PPCISD::SHL";
1156   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1157   case PPCISD::CALL:            return "PPCISD::CALL";
1158   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1159   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1160   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1161   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1162   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1163   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1164   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1165   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1166   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1167   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1168   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1169   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1170   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1171   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1172   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1173   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1174   case PPCISD::VCMP:            return "PPCISD::VCMP";
1175   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1176   case PPCISD::LBRX:            return "PPCISD::LBRX";
1177   case PPCISD::STBRX:           return "PPCISD::STBRX";
1178   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1179   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1180   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1181   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1182   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1183   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1184   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1185   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1186   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1187   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1188   case PPCISD::BDZ:             return "PPCISD::BDZ";
1189   case PPCISD::MFFS:            return "PPCISD::MFFS";
1190   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1191   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1192   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1193   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1194   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1195   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1196   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1197   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1198   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1199   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1200   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1201   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1202   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1203   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1204   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1205   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1206   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1207   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1208   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1209   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1210   case PPCISD::SC:              return "PPCISD::SC";
1211   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1212   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1213   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1214   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1215   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1216   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1217   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1218   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1219   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1220   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1221   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1222   }
1223   return nullptr;
1224 }
1225 
1226 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1227                                           EVT VT) const {
1228   if (!VT.isVector())
1229     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1230 
1231   if (Subtarget.hasQPX())
1232     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1233 
1234   return VT.changeVectorElementTypeToInteger();
1235 }
1236 
1237 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1238   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1239   return true;
1240 }
1241 
1242 //===----------------------------------------------------------------------===//
1243 // Node matching predicates, for use by the tblgen matching code.
1244 //===----------------------------------------------------------------------===//
1245 
1246 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1247 static bool isFloatingPointZero(SDValue Op) {
1248   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1249     return CFP->getValueAPF().isZero();
1250   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1251     // Maybe this has already been legalized into the constant pool?
1252     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1253       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1254         return CFP->getValueAPF().isZero();
1255   }
1256   return false;
1257 }
1258 
1259 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1260 /// true if Op is undef or if it matches the specified value.
1261 static bool isConstantOrUndef(int Op, int Val) {
1262   return Op < 0 || Op == Val;
1263 }
1264 
1265 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1266 /// VPKUHUM instruction.
1267 /// The ShuffleKind distinguishes between big-endian operations with
1268 /// two different inputs (0), either-endian operations with two identical
1269 /// inputs (1), and little-endian operations with two different inputs (2).
1270 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1271 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1272                                SelectionDAG &DAG) {
1273   bool IsLE = DAG.getDataLayout().isLittleEndian();
1274   if (ShuffleKind == 0) {
1275     if (IsLE)
1276       return false;
1277     for (unsigned i = 0; i != 16; ++i)
1278       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1279         return false;
1280   } else if (ShuffleKind == 2) {
1281     if (!IsLE)
1282       return false;
1283     for (unsigned i = 0; i != 16; ++i)
1284       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1285         return false;
1286   } else if (ShuffleKind == 1) {
1287     unsigned j = IsLE ? 0 : 1;
1288     for (unsigned i = 0; i != 8; ++i)
1289       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1290           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1291         return false;
1292   }
1293   return true;
1294 }
1295 
1296 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1297 /// VPKUWUM instruction.
1298 /// The ShuffleKind distinguishes between big-endian operations with
1299 /// two different inputs (0), either-endian operations with two identical
1300 /// inputs (1), and little-endian operations with two different inputs (2).
1301 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1302 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1303                                SelectionDAG &DAG) {
1304   bool IsLE = DAG.getDataLayout().isLittleEndian();
1305   if (ShuffleKind == 0) {
1306     if (IsLE)
1307       return false;
1308     for (unsigned i = 0; i != 16; i += 2)
1309       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1310           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1311         return false;
1312   } else if (ShuffleKind == 2) {
1313     if (!IsLE)
1314       return false;
1315     for (unsigned i = 0; i != 16; i += 2)
1316       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1317           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1318         return false;
1319   } else if (ShuffleKind == 1) {
1320     unsigned j = IsLE ? 0 : 2;
1321     for (unsigned i = 0; i != 8; i += 2)
1322       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1323           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1324           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1325           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1326         return false;
1327   }
1328   return true;
1329 }
1330 
1331 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1332 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1333 /// current subtarget.
1334 ///
1335 /// The ShuffleKind distinguishes between big-endian operations with
1336 /// two different inputs (0), either-endian operations with two identical
1337 /// inputs (1), and little-endian operations with two different inputs (2).
1338 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1339 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1340                                SelectionDAG &DAG) {
1341   const PPCSubtarget& Subtarget =
1342     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1343   if (!Subtarget.hasP8Vector())
1344     return false;
1345 
1346   bool IsLE = DAG.getDataLayout().isLittleEndian();
1347   if (ShuffleKind == 0) {
1348     if (IsLE)
1349       return false;
1350     for (unsigned i = 0; i != 16; i += 4)
1351       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1352           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1353           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1354           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1355         return false;
1356   } else if (ShuffleKind == 2) {
1357     if (!IsLE)
1358       return false;
1359     for (unsigned i = 0; i != 16; i += 4)
1360       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1361           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1362           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1363           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1364         return false;
1365   } else if (ShuffleKind == 1) {
1366     unsigned j = IsLE ? 0 : 4;
1367     for (unsigned i = 0; i != 8; i += 4)
1368       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1369           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1370           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1371           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1372           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1373           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1374           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1375           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1376         return false;
1377   }
1378   return true;
1379 }
1380 
1381 /// isVMerge - Common function, used to match vmrg* shuffles.
1382 ///
1383 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1384                      unsigned LHSStart, unsigned RHSStart) {
1385   if (N->getValueType(0) != MVT::v16i8)
1386     return false;
1387   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1388          "Unsupported merge size!");
1389 
1390   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1391     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1392       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1393                              LHSStart+j+i*UnitSize) ||
1394           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1395                              RHSStart+j+i*UnitSize))
1396         return false;
1397     }
1398   return true;
1399 }
1400 
1401 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1402 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1403 /// The ShuffleKind distinguishes between big-endian merges with two
1404 /// different inputs (0), either-endian merges with two identical inputs (1),
1405 /// and little-endian merges with two different inputs (2).  For the latter,
1406 /// the input operands are swapped (see PPCInstrAltivec.td).
1407 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1408                              unsigned ShuffleKind, SelectionDAG &DAG) {
1409   if (DAG.getDataLayout().isLittleEndian()) {
1410     if (ShuffleKind == 1) // unary
1411       return isVMerge(N, UnitSize, 0, 0);
1412     else if (ShuffleKind == 2) // swapped
1413       return isVMerge(N, UnitSize, 0, 16);
1414     else
1415       return false;
1416   } else {
1417     if (ShuffleKind == 1) // unary
1418       return isVMerge(N, UnitSize, 8, 8);
1419     else if (ShuffleKind == 0) // normal
1420       return isVMerge(N, UnitSize, 8, 24);
1421     else
1422       return false;
1423   }
1424 }
1425 
1426 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1427 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1428 /// The ShuffleKind distinguishes between big-endian merges with two
1429 /// different inputs (0), either-endian merges with two identical inputs (1),
1430 /// and little-endian merges with two different inputs (2).  For the latter,
1431 /// the input operands are swapped (see PPCInstrAltivec.td).
1432 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1433                              unsigned ShuffleKind, SelectionDAG &DAG) {
1434   if (DAG.getDataLayout().isLittleEndian()) {
1435     if (ShuffleKind == 1) // unary
1436       return isVMerge(N, UnitSize, 8, 8);
1437     else if (ShuffleKind == 2) // swapped
1438       return isVMerge(N, UnitSize, 8, 24);
1439     else
1440       return false;
1441   } else {
1442     if (ShuffleKind == 1) // unary
1443       return isVMerge(N, UnitSize, 0, 0);
1444     else if (ShuffleKind == 0) // normal
1445       return isVMerge(N, UnitSize, 0, 16);
1446     else
1447       return false;
1448   }
1449 }
1450 
1451 /**
1452  * \brief Common function used to match vmrgew and vmrgow shuffles
1453  *
1454  * The indexOffset determines whether to look for even or odd words in
1455  * the shuffle mask. This is based on the of the endianness of the target
1456  * machine.
1457  *   - Little Endian:
1458  *     - Use offset of 0 to check for odd elements
1459  *     - Use offset of 4 to check for even elements
1460  *   - Big Endian:
1461  *     - Use offset of 0 to check for even elements
1462  *     - Use offset of 4 to check for odd elements
1463  * A detailed description of the vector element ordering for little endian and
1464  * big endian can be found at
1465  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1466  * Targeting your applications - what little endian and big endian IBM XL C/C++
1467  * compiler differences mean to you
1468  *
1469  * The mask to the shuffle vector instruction specifies the indices of the
1470  * elements from the two input vectors to place in the result. The elements are
1471  * numbered in array-access order, starting with the first vector. These vectors
1472  * are always of type v16i8, thus each vector will contain 16 elements of size
1473  * 8. More info on the shuffle vector can be found in the
1474  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1475  * Language Reference.
1476  *
1477  * The RHSStartValue indicates whether the same input vectors are used (unary)
1478  * or two different input vectors are used, based on the following:
1479  *   - If the instruction uses the same vector for both inputs, the range of the
1480  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1481  *     be 0.
1482  *   - If the instruction has two different vectors then the range of the
1483  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1484  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1485  *     to 31 specify elements in the second vector).
1486  *
1487  * \param[in] N The shuffle vector SD Node to analyze
1488  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1489  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1490  * vector to the shuffle_vector instruction
1491  * \return true iff this shuffle vector represents an even or odd word merge
1492  */
1493 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1494                      unsigned RHSStartValue) {
1495   if (N->getValueType(0) != MVT::v16i8)
1496     return false;
1497 
1498   for (unsigned i = 0; i < 2; ++i)
1499     for (unsigned j = 0; j < 4; ++j)
1500       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1501                              i*RHSStartValue+j+IndexOffset) ||
1502           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1503                              i*RHSStartValue+j+IndexOffset+8))
1504         return false;
1505   return true;
1506 }
1507 
1508 /**
1509  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1510  * vmrgow instructions.
1511  *
1512  * \param[in] N The shuffle vector SD Node to analyze
1513  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1514  * \param[in] ShuffleKind Identify the type of merge:
1515  *   - 0 = big-endian merge with two different inputs;
1516  *   - 1 = either-endian merge with two identical inputs;
1517  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1518  *     little-endian merges).
1519  * \param[in] DAG The current SelectionDAG
1520  * \return true iff this shuffle mask
1521  */
1522 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1523                               unsigned ShuffleKind, SelectionDAG &DAG) {
1524   if (DAG.getDataLayout().isLittleEndian()) {
1525     unsigned indexOffset = CheckEven ? 4 : 0;
1526     if (ShuffleKind == 1) // Unary
1527       return isVMerge(N, indexOffset, 0);
1528     else if (ShuffleKind == 2) // swapped
1529       return isVMerge(N, indexOffset, 16);
1530     else
1531       return false;
1532   }
1533   else {
1534     unsigned indexOffset = CheckEven ? 0 : 4;
1535     if (ShuffleKind == 1) // Unary
1536       return isVMerge(N, indexOffset, 0);
1537     else if (ShuffleKind == 0) // Normal
1538       return isVMerge(N, indexOffset, 16);
1539     else
1540       return false;
1541   }
1542   return false;
1543 }
1544 
1545 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1546 /// amount, otherwise return -1.
1547 /// The ShuffleKind distinguishes between big-endian operations with two
1548 /// different inputs (0), either-endian operations with two identical inputs
1549 /// (1), and little-endian operations with two different inputs (2).  For the
1550 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1551 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1552                              SelectionDAG &DAG) {
1553   if (N->getValueType(0) != MVT::v16i8)
1554     return -1;
1555 
1556   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1557 
1558   // Find the first non-undef value in the shuffle mask.
1559   unsigned i;
1560   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1561     /*search*/;
1562 
1563   if (i == 16) return -1;  // all undef.
1564 
1565   // Otherwise, check to see if the rest of the elements are consecutively
1566   // numbered from this value.
1567   unsigned ShiftAmt = SVOp->getMaskElt(i);
1568   if (ShiftAmt < i) return -1;
1569 
1570   ShiftAmt -= i;
1571   bool isLE = DAG.getDataLayout().isLittleEndian();
1572 
1573   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1574     // Check the rest of the elements to see if they are consecutive.
1575     for (++i; i != 16; ++i)
1576       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1577         return -1;
1578   } else if (ShuffleKind == 1) {
1579     // Check the rest of the elements to see if they are consecutive.
1580     for (++i; i != 16; ++i)
1581       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1582         return -1;
1583   } else
1584     return -1;
1585 
1586   if (isLE)
1587     ShiftAmt = 16 - ShiftAmt;
1588 
1589   return ShiftAmt;
1590 }
1591 
1592 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1593 /// specifies a splat of a single element that is suitable for input to
1594 /// VSPLTB/VSPLTH/VSPLTW.
1595 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1596   assert(N->getValueType(0) == MVT::v16i8 &&
1597          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1598 
1599   // The consecutive indices need to specify an element, not part of two
1600   // different elements.  So abandon ship early if this isn't the case.
1601   if (N->getMaskElt(0) % EltSize != 0)
1602     return false;
1603 
1604   // This is a splat operation if each element of the permute is the same, and
1605   // if the value doesn't reference the second vector.
1606   unsigned ElementBase = N->getMaskElt(0);
1607 
1608   // FIXME: Handle UNDEF elements too!
1609   if (ElementBase >= 16)
1610     return false;
1611 
1612   // Check that the indices are consecutive, in the case of a multi-byte element
1613   // splatted with a v16i8 mask.
1614   for (unsigned i = 1; i != EltSize; ++i)
1615     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1616       return false;
1617 
1618   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1619     if (N->getMaskElt(i) < 0) continue;
1620     for (unsigned j = 0; j != EltSize; ++j)
1621       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1622         return false;
1623   }
1624   return true;
1625 }
1626 
1627 /// Check that the mask is shuffling N byte elements. Within each N byte
1628 /// element of the mask, the indices could be either in increasing or
1629 /// decreasing order as long as they are consecutive.
1630 /// \param[in] N the shuffle vector SD Node to analyze
1631 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1632 /// Word/DoubleWord/QuadWord).
1633 /// \param[in] StepLen the delta indices number among the N byte element, if
1634 /// the mask is in increasing/decreasing order then it is 1/-1.
1635 /// \return true iff the mask is shuffling N byte elements.
1636 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1637                                    int StepLen) {
1638   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1639          "Unexpected element width.");
1640   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1641 
1642   unsigned NumOfElem = 16 / Width;
1643   unsigned MaskVal[16]; //  Width is never greater than 16
1644   for (unsigned i = 0; i < NumOfElem; ++i) {
1645     MaskVal[0] = N->getMaskElt(i * Width);
1646     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1647       return false;
1648     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1649       return false;
1650     }
1651 
1652     for (unsigned int j = 1; j < Width; ++j) {
1653       MaskVal[j] = N->getMaskElt(i * Width + j);
1654       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1655         return false;
1656       }
1657     }
1658   }
1659 
1660   return true;
1661 }
1662 
1663 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1664                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1665   if (!isNByteElemShuffleMask(N, 4, 1))
1666     return false;
1667 
1668   // Now we look at mask elements 0,4,8,12
1669   unsigned M0 = N->getMaskElt(0) / 4;
1670   unsigned M1 = N->getMaskElt(4) / 4;
1671   unsigned M2 = N->getMaskElt(8) / 4;
1672   unsigned M3 = N->getMaskElt(12) / 4;
1673   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1674   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1675 
1676   // Below, let H and L be arbitrary elements of the shuffle mask
1677   // where H is in the range [4,7] and L is in the range [0,3].
1678   // H, 1, 2, 3 or L, 5, 6, 7
1679   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1680       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1681     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1682     InsertAtByte = IsLE ? 12 : 0;
1683     Swap = M0 < 4;
1684     return true;
1685   }
1686   // 0, H, 2, 3 or 4, L, 6, 7
1687   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1688       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1689     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1690     InsertAtByte = IsLE ? 8 : 4;
1691     Swap = M1 < 4;
1692     return true;
1693   }
1694   // 0, 1, H, 3 or 4, 5, L, 7
1695   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1696       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1697     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1698     InsertAtByte = IsLE ? 4 : 8;
1699     Swap = M2 < 4;
1700     return true;
1701   }
1702   // 0, 1, 2, H or 4, 5, 6, L
1703   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1704       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1705     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1706     InsertAtByte = IsLE ? 0 : 12;
1707     Swap = M3 < 4;
1708     return true;
1709   }
1710 
1711   // If both vector operands for the shuffle are the same vector, the mask will
1712   // contain only elements from the first one and the second one will be undef.
1713   if (N->getOperand(1).isUndef()) {
1714     ShiftElts = 0;
1715     Swap = true;
1716     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1717     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1718       InsertAtByte = IsLE ? 12 : 0;
1719       return true;
1720     }
1721     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1722       InsertAtByte = IsLE ? 8 : 4;
1723       return true;
1724     }
1725     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1726       InsertAtByte = IsLE ? 4 : 8;
1727       return true;
1728     }
1729     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1730       InsertAtByte = IsLE ? 0 : 12;
1731       return true;
1732     }
1733   }
1734 
1735   return false;
1736 }
1737 
1738 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1739                                bool &Swap, bool IsLE) {
1740   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1741   // Ensure each byte index of the word is consecutive.
1742   if (!isNByteElemShuffleMask(N, 4, 1))
1743     return false;
1744 
1745   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1746   unsigned M0 = N->getMaskElt(0) / 4;
1747   unsigned M1 = N->getMaskElt(4) / 4;
1748   unsigned M2 = N->getMaskElt(8) / 4;
1749   unsigned M3 = N->getMaskElt(12) / 4;
1750 
1751   // If both vector operands for the shuffle are the same vector, the mask will
1752   // contain only elements from the first one and the second one will be undef.
1753   if (N->getOperand(1).isUndef()) {
1754     assert(M0 < 4 && "Indexing into an undef vector?");
1755     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1756       return false;
1757 
1758     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1759     Swap = false;
1760     return true;
1761   }
1762 
1763   // Ensure each word index of the ShuffleVector Mask is consecutive.
1764   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1765     return false;
1766 
1767   if (IsLE) {
1768     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1769       // Input vectors don't need to be swapped if the leading element
1770       // of the result is one of the 3 left elements of the second vector
1771       // (or if there is no shift to be done at all).
1772       Swap = false;
1773       ShiftElts = (8 - M0) % 8;
1774     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1775       // Input vectors need to be swapped if the leading element
1776       // of the result is one of the 3 left elements of the first vector
1777       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1778       Swap = true;
1779       ShiftElts = (4 - M0) % 4;
1780     }
1781 
1782     return true;
1783   } else {                                          // BE
1784     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1785       // Input vectors don't need to be swapped if the leading element
1786       // of the result is one of the 4 elements of the first vector.
1787       Swap = false;
1788       ShiftElts = M0;
1789     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1790       // Input vectors need to be swapped if the leading element
1791       // of the result is one of the 4 elements of the right vector.
1792       Swap = true;
1793       ShiftElts = M0 - 4;
1794     }
1795 
1796     return true;
1797   }
1798 }
1799 
1800 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1801   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1802 
1803   if (!isNByteElemShuffleMask(N, Width, -1))
1804     return false;
1805 
1806   for (int i = 0; i < 16; i += Width)
1807     if (N->getMaskElt(i) != i + Width - 1)
1808       return false;
1809 
1810   return true;
1811 }
1812 
1813 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1814   return isXXBRShuffleMaskHelper(N, 2);
1815 }
1816 
1817 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
1818   return isXXBRShuffleMaskHelper(N, 4);
1819 }
1820 
1821 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
1822   return isXXBRShuffleMaskHelper(N, 8);
1823 }
1824 
1825 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
1826   return isXXBRShuffleMaskHelper(N, 16);
1827 }
1828 
1829 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1830 /// if the inputs to the instruction should be swapped and set \p DM to the
1831 /// value for the immediate.
1832 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1833 /// AND element 0 of the result comes from the first input (LE) or second input
1834 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1835 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1836 /// mask.
1837 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
1838                                bool &Swap, bool IsLE) {
1839   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1840 
1841   // Ensure each byte index of the double word is consecutive.
1842   if (!isNByteElemShuffleMask(N, 8, 1))
1843     return false;
1844 
1845   unsigned M0 = N->getMaskElt(0) / 8;
1846   unsigned M1 = N->getMaskElt(8) / 8;
1847   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
1848 
1849   // If both vector operands for the shuffle are the same vector, the mask will
1850   // contain only elements from the first one and the second one will be undef.
1851   if (N->getOperand(1).isUndef()) {
1852     if ((M0 | M1) < 2) {
1853       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
1854       Swap = false;
1855       return true;
1856     } else
1857       return false;
1858   }
1859 
1860   if (IsLE) {
1861     if (M0 > 1 && M1 < 2) {
1862       Swap = false;
1863     } else if (M0 < 2 && M1 > 1) {
1864       M0 = (M0 + 2) % 4;
1865       M1 = (M1 + 2) % 4;
1866       Swap = true;
1867     } else
1868       return false;
1869 
1870     // Note: if control flow comes here that means Swap is already set above
1871     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
1872     return true;
1873   } else { // BE
1874     if (M0 < 2 && M1 > 1) {
1875       Swap = false;
1876     } else if (M0 > 1 && M1 < 2) {
1877       M0 = (M0 + 2) % 4;
1878       M1 = (M1 + 2) % 4;
1879       Swap = true;
1880     } else
1881       return false;
1882 
1883     // Note: if control flow comes here that means Swap is already set above
1884     DM = (M0 << 1) + (M1 & 1);
1885     return true;
1886   }
1887 }
1888 
1889 
1890 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1891 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1892 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1893                                 SelectionDAG &DAG) {
1894   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1895   assert(isSplatShuffleMask(SVOp, EltSize));
1896   if (DAG.getDataLayout().isLittleEndian())
1897     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1898   else
1899     return SVOp->getMaskElt(0) / EltSize;
1900 }
1901 
1902 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1903 /// by using a vspltis[bhw] instruction of the specified element size, return
1904 /// the constant being splatted.  The ByteSize field indicates the number of
1905 /// bytes of each element [124] -> [bhw].
1906 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1907   SDValue OpVal(nullptr, 0);
1908 
1909   // If ByteSize of the splat is bigger than the element size of the
1910   // build_vector, then we have a case where we are checking for a splat where
1911   // multiple elements of the buildvector are folded together into a single
1912   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1913   unsigned EltSize = 16/N->getNumOperands();
1914   if (EltSize < ByteSize) {
1915     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1916     SDValue UniquedVals[4];
1917     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1918 
1919     // See if all of the elements in the buildvector agree across.
1920     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1921       if (N->getOperand(i).isUndef()) continue;
1922       // If the element isn't a constant, bail fully out.
1923       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1924 
1925       if (!UniquedVals[i&(Multiple-1)].getNode())
1926         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1927       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1928         return SDValue();  // no match.
1929     }
1930 
1931     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1932     // either constant or undef values that are identical for each chunk.  See
1933     // if these chunks can form into a larger vspltis*.
1934 
1935     // Check to see if all of the leading entries are either 0 or -1.  If
1936     // neither, then this won't fit into the immediate field.
1937     bool LeadingZero = true;
1938     bool LeadingOnes = true;
1939     for (unsigned i = 0; i != Multiple-1; ++i) {
1940       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1941 
1942       LeadingZero &= isNullConstant(UniquedVals[i]);
1943       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1944     }
1945     // Finally, check the least significant entry.
1946     if (LeadingZero) {
1947       if (!UniquedVals[Multiple-1].getNode())
1948         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1949       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1950       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1951         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1952     }
1953     if (LeadingOnes) {
1954       if (!UniquedVals[Multiple-1].getNode())
1955         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1956       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1957       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1958         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1959     }
1960 
1961     return SDValue();
1962   }
1963 
1964   // Check to see if this buildvec has a single non-undef value in its elements.
1965   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1966     if (N->getOperand(i).isUndef()) continue;
1967     if (!OpVal.getNode())
1968       OpVal = N->getOperand(i);
1969     else if (OpVal != N->getOperand(i))
1970       return SDValue();
1971   }
1972 
1973   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1974 
1975   unsigned ValSizeInBytes = EltSize;
1976   uint64_t Value = 0;
1977   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1978     Value = CN->getZExtValue();
1979   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1980     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1981     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1982   }
1983 
1984   // If the splat value is larger than the element value, then we can never do
1985   // this splat.  The only case that we could fit the replicated bits into our
1986   // immediate field for would be zero, and we prefer to use vxor for it.
1987   if (ValSizeInBytes < ByteSize) return SDValue();
1988 
1989   // If the element value is larger than the splat value, check if it consists
1990   // of a repeated bit pattern of size ByteSize.
1991   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1992     return SDValue();
1993 
1994   // Properly sign extend the value.
1995   int MaskVal = SignExtend32(Value, ByteSize * 8);
1996 
1997   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1998   if (MaskVal == 0) return SDValue();
1999 
2000   // Finally, if this value fits in a 5 bit sext field, return it
2001   if (SignExtend32<5>(MaskVal) == MaskVal)
2002     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2003   return SDValue();
2004 }
2005 
2006 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2007 /// amount, otherwise return -1.
2008 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2009   EVT VT = N->getValueType(0);
2010   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2011     return -1;
2012 
2013   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2014 
2015   // Find the first non-undef value in the shuffle mask.
2016   unsigned i;
2017   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2018     /*search*/;
2019 
2020   if (i == 4) return -1;  // all undef.
2021 
2022   // Otherwise, check to see if the rest of the elements are consecutively
2023   // numbered from this value.
2024   unsigned ShiftAmt = SVOp->getMaskElt(i);
2025   if (ShiftAmt < i) return -1;
2026   ShiftAmt -= i;
2027 
2028   // Check the rest of the elements to see if they are consecutive.
2029   for (++i; i != 4; ++i)
2030     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2031       return -1;
2032 
2033   return ShiftAmt;
2034 }
2035 
2036 //===----------------------------------------------------------------------===//
2037 //  Addressing Mode Selection
2038 //===----------------------------------------------------------------------===//
2039 
2040 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2041 /// or 64-bit immediate, and if the value can be accurately represented as a
2042 /// sign extension from a 16-bit value.  If so, this returns true and the
2043 /// immediate.
2044 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2045   if (!isa<ConstantSDNode>(N))
2046     return false;
2047 
2048   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2049   if (N->getValueType(0) == MVT::i32)
2050     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2051   else
2052     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2053 }
2054 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2055   return isIntS16Immediate(Op.getNode(), Imm);
2056 }
2057 
2058 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2059 /// can be represented as an indexed [r+r] operation.  Returns false if it
2060 /// can be more efficiently represented with [r+imm].
2061 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2062                                             SDValue &Index,
2063                                             SelectionDAG &DAG) const {
2064   int16_t imm = 0;
2065   if (N.getOpcode() == ISD::ADD) {
2066     if (isIntS16Immediate(N.getOperand(1), imm))
2067       return false;    // r+i
2068     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2069       return false;    // r+i
2070 
2071     Base = N.getOperand(0);
2072     Index = N.getOperand(1);
2073     return true;
2074   } else if (N.getOpcode() == ISD::OR) {
2075     if (isIntS16Immediate(N.getOperand(1), imm))
2076       return false;    // r+i can fold it if we can.
2077 
2078     // If this is an or of disjoint bitfields, we can codegen this as an add
2079     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2080     // disjoint.
2081     KnownBits LHSKnown, RHSKnown;
2082     DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2083 
2084     if (LHSKnown.Zero.getBoolValue()) {
2085       DAG.computeKnownBits(N.getOperand(1), RHSKnown);
2086       // If all of the bits are known zero on the LHS or RHS, the add won't
2087       // carry.
2088       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2089         Base = N.getOperand(0);
2090         Index = N.getOperand(1);
2091         return true;
2092       }
2093     }
2094   }
2095 
2096   return false;
2097 }
2098 
2099 // If we happen to be doing an i64 load or store into a stack slot that has
2100 // less than a 4-byte alignment, then the frame-index elimination may need to
2101 // use an indexed load or store instruction (because the offset may not be a
2102 // multiple of 4). The extra register needed to hold the offset comes from the
2103 // register scavenger, and it is possible that the scavenger will need to use
2104 // an emergency spill slot. As a result, we need to make sure that a spill slot
2105 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2106 // stack slot.
2107 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2108   // FIXME: This does not handle the LWA case.
2109   if (VT != MVT::i64)
2110     return;
2111 
2112   // NOTE: We'll exclude negative FIs here, which come from argument
2113   // lowering, because there are no known test cases triggering this problem
2114   // using packed structures (or similar). We can remove this exclusion if
2115   // we find such a test case. The reason why this is so test-case driven is
2116   // because this entire 'fixup' is only to prevent crashes (from the
2117   // register scavenger) on not-really-valid inputs. For example, if we have:
2118   //   %a = alloca i1
2119   //   %b = bitcast i1* %a to i64*
2120   //   store i64* a, i64 b
2121   // then the store should really be marked as 'align 1', but is not. If it
2122   // were marked as 'align 1' then the indexed form would have been
2123   // instruction-selected initially, and the problem this 'fixup' is preventing
2124   // won't happen regardless.
2125   if (FrameIdx < 0)
2126     return;
2127 
2128   MachineFunction &MF = DAG.getMachineFunction();
2129   MachineFrameInfo &MFI = MF.getFrameInfo();
2130 
2131   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2132   if (Align >= 4)
2133     return;
2134 
2135   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2136   FuncInfo->setHasNonRISpills();
2137 }
2138 
2139 /// Returns true if the address N can be represented by a base register plus
2140 /// a signed 16-bit displacement [r+imm], and if it is not better
2141 /// represented as reg+reg.  If \p Alignment is non-zero, only accept
2142 /// displacements that are multiples of that value.
2143 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2144                                             SDValue &Base,
2145                                             SelectionDAG &DAG,
2146                                             unsigned Alignment) const {
2147   // FIXME dl should come from parent load or store, not from address
2148   SDLoc dl(N);
2149   // If this can be more profitably realized as r+r, fail.
2150   if (SelectAddressRegReg(N, Disp, Base, DAG))
2151     return false;
2152 
2153   if (N.getOpcode() == ISD::ADD) {
2154     int16_t imm = 0;
2155     if (isIntS16Immediate(N.getOperand(1), imm) &&
2156         (!Alignment || (imm % Alignment) == 0)) {
2157       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2158       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2159         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2160         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2161       } else {
2162         Base = N.getOperand(0);
2163       }
2164       return true; // [r+i]
2165     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2166       // Match LOAD (ADD (X, Lo(G))).
2167       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2168              && "Cannot handle constant offsets yet!");
2169       Disp = N.getOperand(1).getOperand(0);  // The global address.
2170       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2171              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2172              Disp.getOpcode() == ISD::TargetConstantPool ||
2173              Disp.getOpcode() == ISD::TargetJumpTable);
2174       Base = N.getOperand(0);
2175       return true;  // [&g+r]
2176     }
2177   } else if (N.getOpcode() == ISD::OR) {
2178     int16_t imm = 0;
2179     if (isIntS16Immediate(N.getOperand(1), imm) &&
2180         (!Alignment || (imm % Alignment) == 0)) {
2181       // If this is an or of disjoint bitfields, we can codegen this as an add
2182       // (for better address arithmetic) if the LHS and RHS of the OR are
2183       // provably disjoint.
2184       KnownBits LHSKnown;
2185       DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2186 
2187       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2188         // If all of the bits are known zero on the LHS or RHS, the add won't
2189         // carry.
2190         if (FrameIndexSDNode *FI =
2191               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2192           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2193           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2194         } else {
2195           Base = N.getOperand(0);
2196         }
2197         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2198         return true;
2199       }
2200     }
2201   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2202     // Loading from a constant address.
2203 
2204     // If this address fits entirely in a 16-bit sext immediate field, codegen
2205     // this as "d, 0"
2206     int16_t Imm;
2207     if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) {
2208       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2209       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2210                              CN->getValueType(0));
2211       return true;
2212     }
2213 
2214     // Handle 32-bit sext immediates with LIS + addr mode.
2215     if ((CN->getValueType(0) == MVT::i32 ||
2216          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2217         (!Alignment || (CN->getZExtValue() % Alignment) == 0)) {
2218       int Addr = (int)CN->getZExtValue();
2219 
2220       // Otherwise, break this down into an LIS + disp.
2221       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2222 
2223       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2224                                    MVT::i32);
2225       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2226       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2227       return true;
2228     }
2229   }
2230 
2231   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2232   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2233     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2234     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2235   } else
2236     Base = N;
2237   return true;      // [r+0]
2238 }
2239 
2240 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2241 /// represented as an indexed [r+r] operation.
2242 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2243                                                 SDValue &Index,
2244                                                 SelectionDAG &DAG) const {
2245   // Check to see if we can easily represent this as an [r+r] address.  This
2246   // will fail if it thinks that the address is more profitably represented as
2247   // reg+imm, e.g. where imm = 0.
2248   if (SelectAddressRegReg(N, Base, Index, DAG))
2249     return true;
2250 
2251   // If the address is the result of an add, we will utilize the fact that the
2252   // address calculation includes an implicit add.  However, we can reduce
2253   // register pressure if we do not materialize a constant just for use as the
2254   // index register.  We only get rid of the add if it is not an add of a
2255   // value and a 16-bit signed constant and both have a single use.
2256   int16_t imm = 0;
2257   if (N.getOpcode() == ISD::ADD &&
2258       (!isIntS16Immediate(N.getOperand(1), imm) ||
2259        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2260     Base = N.getOperand(0);
2261     Index = N.getOperand(1);
2262     return true;
2263   }
2264 
2265   // Otherwise, do it the hard way, using R0 as the base register.
2266   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2267                          N.getValueType());
2268   Index = N;
2269   return true;
2270 }
2271 
2272 /// getPreIndexedAddressParts - returns true by value, base pointer and
2273 /// offset pointer and addressing mode by reference if the node's address
2274 /// can be legally represented as pre-indexed load / store address.
2275 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2276                                                   SDValue &Offset,
2277                                                   ISD::MemIndexedMode &AM,
2278                                                   SelectionDAG &DAG) const {
2279   if (DisablePPCPreinc) return false;
2280 
2281   bool isLoad = true;
2282   SDValue Ptr;
2283   EVT VT;
2284   unsigned Alignment;
2285   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2286     Ptr = LD->getBasePtr();
2287     VT = LD->getMemoryVT();
2288     Alignment = LD->getAlignment();
2289   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2290     Ptr = ST->getBasePtr();
2291     VT  = ST->getMemoryVT();
2292     Alignment = ST->getAlignment();
2293     isLoad = false;
2294   } else
2295     return false;
2296 
2297   // PowerPC doesn't have preinc load/store instructions for vectors (except
2298   // for QPX, which does have preinc r+r forms).
2299   if (VT.isVector()) {
2300     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2301       return false;
2302     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2303       AM = ISD::PRE_INC;
2304       return true;
2305     }
2306   }
2307 
2308   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2309     // Common code will reject creating a pre-inc form if the base pointer
2310     // is a frame index, or if N is a store and the base pointer is either
2311     // the same as or a predecessor of the value being stored.  Check for
2312     // those situations here, and try with swapped Base/Offset instead.
2313     bool Swap = false;
2314 
2315     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2316       Swap = true;
2317     else if (!isLoad) {
2318       SDValue Val = cast<StoreSDNode>(N)->getValue();
2319       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2320         Swap = true;
2321     }
2322 
2323     if (Swap)
2324       std::swap(Base, Offset);
2325 
2326     AM = ISD::PRE_INC;
2327     return true;
2328   }
2329 
2330   // LDU/STU can only handle immediates that are a multiple of 4.
2331   if (VT != MVT::i64) {
2332     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2333       return false;
2334   } else {
2335     // LDU/STU need an address with at least 4-byte alignment.
2336     if (Alignment < 4)
2337       return false;
2338 
2339     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2340       return false;
2341   }
2342 
2343   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2344     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2345     // sext i32 to i64 when addr mode is r+i.
2346     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2347         LD->getExtensionType() == ISD::SEXTLOAD &&
2348         isa<ConstantSDNode>(Offset))
2349       return false;
2350   }
2351 
2352   AM = ISD::PRE_INC;
2353   return true;
2354 }
2355 
2356 //===----------------------------------------------------------------------===//
2357 //  LowerOperation implementation
2358 //===----------------------------------------------------------------------===//
2359 
2360 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2361 /// and LoOpFlags to the target MO flags.
2362 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2363                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2364                                const GlobalValue *GV = nullptr) {
2365   HiOpFlags = PPCII::MO_HA;
2366   LoOpFlags = PPCII::MO_LO;
2367 
2368   // Don't use the pic base if not in PIC relocation model.
2369   if (IsPIC) {
2370     HiOpFlags |= PPCII::MO_PIC_FLAG;
2371     LoOpFlags |= PPCII::MO_PIC_FLAG;
2372   }
2373 
2374   // If this is a reference to a global value that requires a non-lazy-ptr, make
2375   // sure that instruction lowering adds it.
2376   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2377     HiOpFlags |= PPCII::MO_NLP_FLAG;
2378     LoOpFlags |= PPCII::MO_NLP_FLAG;
2379 
2380     if (GV->hasHiddenVisibility()) {
2381       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2382       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2383     }
2384   }
2385 }
2386 
2387 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2388                              SelectionDAG &DAG) {
2389   SDLoc DL(HiPart);
2390   EVT PtrVT = HiPart.getValueType();
2391   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2392 
2393   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2394   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2395 
2396   // With PIC, the first instruction is actually "GR+hi(&G)".
2397   if (isPIC)
2398     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2399                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2400 
2401   // Generate non-pic code that has direct accesses to the constant pool.
2402   // The address of the global is just (hi(&g)+lo(&g)).
2403   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2404 }
2405 
2406 static void setUsesTOCBasePtr(MachineFunction &MF) {
2407   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2408   FuncInfo->setUsesTOCBasePtr();
2409 }
2410 
2411 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2412   setUsesTOCBasePtr(DAG.getMachineFunction());
2413 }
2414 
2415 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2416                            SDValue GA) {
2417   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2418   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2419                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2420 
2421   SDValue Ops[] = { GA, Reg };
2422   return DAG.getMemIntrinsicNode(
2423       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2424       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2425       false, 0);
2426 }
2427 
2428 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2429                                              SelectionDAG &DAG) const {
2430   EVT PtrVT = Op.getValueType();
2431   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2432   const Constant *C = CP->getConstVal();
2433 
2434   // 64-bit SVR4 ABI code is always position-independent.
2435   // The actual address of the GlobalValue is stored in the TOC.
2436   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2437     setUsesTOCBasePtr(DAG);
2438     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2439     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2440   }
2441 
2442   unsigned MOHiFlag, MOLoFlag;
2443   bool IsPIC = isPositionIndependent();
2444   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2445 
2446   if (IsPIC && Subtarget.isSVR4ABI()) {
2447     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2448                                            PPCII::MO_PIC_FLAG);
2449     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2450   }
2451 
2452   SDValue CPIHi =
2453     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2454   SDValue CPILo =
2455     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2456   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2457 }
2458 
2459 // For 64-bit PowerPC, prefer the more compact relative encodings.
2460 // This trades 32 bits per jump table entry for one or two instructions
2461 // on the jump site.
2462 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2463   if (isJumpTableRelative())
2464     return MachineJumpTableInfo::EK_LabelDifference32;
2465 
2466   return TargetLowering::getJumpTableEncoding();
2467 }
2468 
2469 bool PPCTargetLowering::isJumpTableRelative() const {
2470   if (Subtarget.isPPC64())
2471     return true;
2472   return TargetLowering::isJumpTableRelative();
2473 }
2474 
2475 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2476                                                     SelectionDAG &DAG) const {
2477   if (!Subtarget.isPPC64())
2478     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2479 
2480   switch (getTargetMachine().getCodeModel()) {
2481   case CodeModel::Small:
2482   case CodeModel::Medium:
2483     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2484   default:
2485     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2486                        getPointerTy(DAG.getDataLayout()));
2487   }
2488 }
2489 
2490 const MCExpr *
2491 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2492                                                 unsigned JTI,
2493                                                 MCContext &Ctx) const {
2494   if (!Subtarget.isPPC64())
2495     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2496 
2497   switch (getTargetMachine().getCodeModel()) {
2498   case CodeModel::Small:
2499   case CodeModel::Medium:
2500     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2501   default:
2502     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2503   }
2504 }
2505 
2506 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2507   EVT PtrVT = Op.getValueType();
2508   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2509 
2510   // 64-bit SVR4 ABI code is always position-independent.
2511   // The actual address of the GlobalValue is stored in the TOC.
2512   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2513     setUsesTOCBasePtr(DAG);
2514     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2515     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2516   }
2517 
2518   unsigned MOHiFlag, MOLoFlag;
2519   bool IsPIC = isPositionIndependent();
2520   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2521 
2522   if (IsPIC && Subtarget.isSVR4ABI()) {
2523     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2524                                         PPCII::MO_PIC_FLAG);
2525     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2526   }
2527 
2528   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2529   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2530   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2531 }
2532 
2533 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2534                                              SelectionDAG &DAG) const {
2535   EVT PtrVT = Op.getValueType();
2536   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2537   const BlockAddress *BA = BASDN->getBlockAddress();
2538 
2539   // 64-bit SVR4 ABI code is always position-independent.
2540   // The actual BlockAddress is stored in the TOC.
2541   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2542     setUsesTOCBasePtr(DAG);
2543     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2544     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2545   }
2546 
2547   unsigned MOHiFlag, MOLoFlag;
2548   bool IsPIC = isPositionIndependent();
2549   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2550   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2551   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2552   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2553 }
2554 
2555 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2556                                               SelectionDAG &DAG) const {
2557   // FIXME: TLS addresses currently use medium model code sequences,
2558   // which is the most useful form.  Eventually support for small and
2559   // large models could be added if users need it, at the cost of
2560   // additional complexity.
2561   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2562   if (DAG.getTarget().Options.EmulatedTLS)
2563     return LowerToTLSEmulatedModel(GA, DAG);
2564 
2565   SDLoc dl(GA);
2566   const GlobalValue *GV = GA->getGlobal();
2567   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2568   bool is64bit = Subtarget.isPPC64();
2569   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2570   PICLevel::Level picLevel = M->getPICLevel();
2571 
2572   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2573 
2574   if (Model == TLSModel::LocalExec) {
2575     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2576                                                PPCII::MO_TPREL_HA);
2577     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2578                                                PPCII::MO_TPREL_LO);
2579     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2580                              : DAG.getRegister(PPC::R2, MVT::i32);
2581 
2582     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2583     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2584   }
2585 
2586   if (Model == TLSModel::InitialExec) {
2587     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2588     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2589                                                 PPCII::MO_TLS);
2590     SDValue GOTPtr;
2591     if (is64bit) {
2592       setUsesTOCBasePtr(DAG);
2593       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2594       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2595                            PtrVT, GOTReg, TGA);
2596     } else
2597       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2598     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2599                                    PtrVT, TGA, GOTPtr);
2600     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2601   }
2602 
2603   if (Model == TLSModel::GeneralDynamic) {
2604     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2605     SDValue GOTPtr;
2606     if (is64bit) {
2607       setUsesTOCBasePtr(DAG);
2608       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2609       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2610                                    GOTReg, TGA);
2611     } else {
2612       if (picLevel == PICLevel::SmallPIC)
2613         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2614       else
2615         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2616     }
2617     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2618                        GOTPtr, TGA, TGA);
2619   }
2620 
2621   if (Model == TLSModel::LocalDynamic) {
2622     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2623     SDValue GOTPtr;
2624     if (is64bit) {
2625       setUsesTOCBasePtr(DAG);
2626       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2627       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2628                            GOTReg, TGA);
2629     } else {
2630       if (picLevel == PICLevel::SmallPIC)
2631         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2632       else
2633         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2634     }
2635     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2636                                   PtrVT, GOTPtr, TGA, TGA);
2637     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2638                                       PtrVT, TLSAddr, TGA);
2639     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2640   }
2641 
2642   llvm_unreachable("Unknown TLS model!");
2643 }
2644 
2645 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2646                                               SelectionDAG &DAG) const {
2647   EVT PtrVT = Op.getValueType();
2648   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2649   SDLoc DL(GSDN);
2650   const GlobalValue *GV = GSDN->getGlobal();
2651 
2652   // 64-bit SVR4 ABI code is always position-independent.
2653   // The actual address of the GlobalValue is stored in the TOC.
2654   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2655     setUsesTOCBasePtr(DAG);
2656     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2657     return getTOCEntry(DAG, DL, true, GA);
2658   }
2659 
2660   unsigned MOHiFlag, MOLoFlag;
2661   bool IsPIC = isPositionIndependent();
2662   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2663 
2664   if (IsPIC && Subtarget.isSVR4ABI()) {
2665     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2666                                             GSDN->getOffset(),
2667                                             PPCII::MO_PIC_FLAG);
2668     return getTOCEntry(DAG, DL, false, GA);
2669   }
2670 
2671   SDValue GAHi =
2672     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2673   SDValue GALo =
2674     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2675 
2676   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2677 
2678   // If the global reference is actually to a non-lazy-pointer, we have to do an
2679   // extra load to get the address of the global.
2680   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2681     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2682   return Ptr;
2683 }
2684 
2685 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2686   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2687   SDLoc dl(Op);
2688 
2689   if (Op.getValueType() == MVT::v2i64) {
2690     // When the operands themselves are v2i64 values, we need to do something
2691     // special because VSX has no underlying comparison operations for these.
2692     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2693       // Equality can be handled by casting to the legal type for Altivec
2694       // comparisons, everything else needs to be expanded.
2695       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2696         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2697                  DAG.getSetCC(dl, MVT::v4i32,
2698                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2699                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2700                    CC));
2701       }
2702 
2703       return SDValue();
2704     }
2705 
2706     // We handle most of these in the usual way.
2707     return Op;
2708   }
2709 
2710   // If we're comparing for equality to zero, expose the fact that this is
2711   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2712   // fold the new nodes.
2713   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2714     return V;
2715 
2716   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2717     // Leave comparisons against 0 and -1 alone for now, since they're usually
2718     // optimized.  FIXME: revisit this when we can custom lower all setcc
2719     // optimizations.
2720     if (C->isAllOnesValue() || C->isNullValue())
2721       return SDValue();
2722   }
2723 
2724   // If we have an integer seteq/setne, turn it into a compare against zero
2725   // by xor'ing the rhs with the lhs, which is faster than setting a
2726   // condition register, reading it back out, and masking the correct bit.  The
2727   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2728   // the result to other bit-twiddling opportunities.
2729   EVT LHSVT = Op.getOperand(0).getValueType();
2730   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2731     EVT VT = Op.getValueType();
2732     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2733                                 Op.getOperand(1));
2734     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2735   }
2736   return SDValue();
2737 }
2738 
2739 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2740   SDNode *Node = Op.getNode();
2741   EVT VT = Node->getValueType(0);
2742   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2743   SDValue InChain = Node->getOperand(0);
2744   SDValue VAListPtr = Node->getOperand(1);
2745   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2746   SDLoc dl(Node);
2747 
2748   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2749 
2750   // gpr_index
2751   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2752                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2753   InChain = GprIndex.getValue(1);
2754 
2755   if (VT == MVT::i64) {
2756     // Check if GprIndex is even
2757     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2758                                  DAG.getConstant(1, dl, MVT::i32));
2759     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2760                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2761     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2762                                           DAG.getConstant(1, dl, MVT::i32));
2763     // Align GprIndex to be even if it isn't
2764     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2765                            GprIndex);
2766   }
2767 
2768   // fpr index is 1 byte after gpr
2769   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2770                                DAG.getConstant(1, dl, MVT::i32));
2771 
2772   // fpr
2773   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2774                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2775   InChain = FprIndex.getValue(1);
2776 
2777   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2778                                        DAG.getConstant(8, dl, MVT::i32));
2779 
2780   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2781                                         DAG.getConstant(4, dl, MVT::i32));
2782 
2783   // areas
2784   SDValue OverflowArea =
2785       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2786   InChain = OverflowArea.getValue(1);
2787 
2788   SDValue RegSaveArea =
2789       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2790   InChain = RegSaveArea.getValue(1);
2791 
2792   // select overflow_area if index > 8
2793   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2794                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2795 
2796   // adjustment constant gpr_index * 4/8
2797   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2798                                     VT.isInteger() ? GprIndex : FprIndex,
2799                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2800                                                     MVT::i32));
2801 
2802   // OurReg = RegSaveArea + RegConstant
2803   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2804                                RegConstant);
2805 
2806   // Floating types are 32 bytes into RegSaveArea
2807   if (VT.isFloatingPoint())
2808     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2809                          DAG.getConstant(32, dl, MVT::i32));
2810 
2811   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2812   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2813                                    VT.isInteger() ? GprIndex : FprIndex,
2814                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2815                                                    MVT::i32));
2816 
2817   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2818                               VT.isInteger() ? VAListPtr : FprPtr,
2819                               MachinePointerInfo(SV), MVT::i8);
2820 
2821   // determine if we should load from reg_save_area or overflow_area
2822   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2823 
2824   // increase overflow_area by 4/8 if gpr/fpr > 8
2825   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2826                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2827                                           dl, MVT::i32));
2828 
2829   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2830                              OverflowAreaPlusN);
2831 
2832   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2833                               MachinePointerInfo(), MVT::i32);
2834 
2835   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2836 }
2837 
2838 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2839   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2840 
2841   // We have to copy the entire va_list struct:
2842   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2843   return DAG.getMemcpy(Op.getOperand(0), Op,
2844                        Op.getOperand(1), Op.getOperand(2),
2845                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2846                        false, MachinePointerInfo(), MachinePointerInfo());
2847 }
2848 
2849 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2850                                                   SelectionDAG &DAG) const {
2851   return Op.getOperand(0);
2852 }
2853 
2854 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2855                                                 SelectionDAG &DAG) const {
2856   SDValue Chain = Op.getOperand(0);
2857   SDValue Trmp = Op.getOperand(1); // trampoline
2858   SDValue FPtr = Op.getOperand(2); // nested function
2859   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2860   SDLoc dl(Op);
2861 
2862   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2863   bool isPPC64 = (PtrVT == MVT::i64);
2864   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2865 
2866   TargetLowering::ArgListTy Args;
2867   TargetLowering::ArgListEntry Entry;
2868 
2869   Entry.Ty = IntPtrTy;
2870   Entry.Node = Trmp; Args.push_back(Entry);
2871 
2872   // TrampSize == (isPPC64 ? 48 : 40);
2873   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2874                                isPPC64 ? MVT::i64 : MVT::i32);
2875   Args.push_back(Entry);
2876 
2877   Entry.Node = FPtr; Args.push_back(Entry);
2878   Entry.Node = Nest; Args.push_back(Entry);
2879 
2880   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2881   TargetLowering::CallLoweringInfo CLI(DAG);
2882   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2883       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2884       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2885 
2886   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2887   return CallResult.second;
2888 }
2889 
2890 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2891   MachineFunction &MF = DAG.getMachineFunction();
2892   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2893   EVT PtrVT = getPointerTy(MF.getDataLayout());
2894 
2895   SDLoc dl(Op);
2896 
2897   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2898     // vastart just stores the address of the VarArgsFrameIndex slot into the
2899     // memory location argument.
2900     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2901     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2902     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2903                         MachinePointerInfo(SV));
2904   }
2905 
2906   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2907   // We suppose the given va_list is already allocated.
2908   //
2909   // typedef struct {
2910   //  char gpr;     /* index into the array of 8 GPRs
2911   //                 * stored in the register save area
2912   //                 * gpr=0 corresponds to r3,
2913   //                 * gpr=1 to r4, etc.
2914   //                 */
2915   //  char fpr;     /* index into the array of 8 FPRs
2916   //                 * stored in the register save area
2917   //                 * fpr=0 corresponds to f1,
2918   //                 * fpr=1 to f2, etc.
2919   //                 */
2920   //  char *overflow_arg_area;
2921   //                /* location on stack that holds
2922   //                 * the next overflow argument
2923   //                 */
2924   //  char *reg_save_area;
2925   //               /* where r3:r10 and f1:f8 (if saved)
2926   //                * are stored
2927   //                */
2928   // } va_list[1];
2929 
2930   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2931   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2932   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2933                                             PtrVT);
2934   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2935                                  PtrVT);
2936 
2937   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2938   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2939 
2940   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2941   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2942 
2943   uint64_t FPROffset = 1;
2944   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2945 
2946   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2947 
2948   // Store first byte : number of int regs
2949   SDValue firstStore =
2950       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2951                         MachinePointerInfo(SV), MVT::i8);
2952   uint64_t nextOffset = FPROffset;
2953   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2954                                   ConstFPROffset);
2955 
2956   // Store second byte : number of float regs
2957   SDValue secondStore =
2958       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2959                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2960   nextOffset += StackOffset;
2961   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2962 
2963   // Store second word : arguments given on stack
2964   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2965                                     MachinePointerInfo(SV, nextOffset));
2966   nextOffset += FrameOffset;
2967   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2968 
2969   // Store third word : arguments given in registers
2970   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2971                       MachinePointerInfo(SV, nextOffset));
2972 }
2973 
2974 #include "PPCGenCallingConv.inc"
2975 
2976 // Function whose sole purpose is to kill compiler warnings
2977 // stemming from unused functions included from PPCGenCallingConv.inc.
2978 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2979   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2980 }
2981 
2982 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2983                                       CCValAssign::LocInfo &LocInfo,
2984                                       ISD::ArgFlagsTy &ArgFlags,
2985                                       CCState &State) {
2986   return true;
2987 }
2988 
2989 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2990                                              MVT &LocVT,
2991                                              CCValAssign::LocInfo &LocInfo,
2992                                              ISD::ArgFlagsTy &ArgFlags,
2993                                              CCState &State) {
2994   static const MCPhysReg ArgRegs[] = {
2995     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2996     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2997   };
2998   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2999 
3000   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3001 
3002   // Skip one register if the first unallocated register has an even register
3003   // number and there are still argument registers available which have not been
3004   // allocated yet. RegNum is actually an index into ArgRegs, which means we
3005   // need to skip a register if RegNum is odd.
3006   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
3007     State.AllocateReg(ArgRegs[RegNum]);
3008   }
3009 
3010   // Always return false here, as this function only makes sure that the first
3011   // unallocated register has an odd register number and does not actually
3012   // allocate a register for the current argument.
3013   return false;
3014 }
3015 
3016 bool
3017 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
3018                                                   MVT &LocVT,
3019                                                   CCValAssign::LocInfo &LocInfo,
3020                                                   ISD::ArgFlagsTy &ArgFlags,
3021                                                   CCState &State) {
3022   static const MCPhysReg ArgRegs[] = {
3023     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3024     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3025   };
3026   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3027 
3028   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3029   int RegsLeft = NumArgRegs - RegNum;
3030 
3031   // Skip if there is not enough registers left for long double type (4 gpr regs
3032   // in soft float mode) and put long double argument on the stack.
3033   if (RegNum != NumArgRegs && RegsLeft < 4) {
3034     for (int i = 0; i < RegsLeft; i++) {
3035       State.AllocateReg(ArgRegs[RegNum + i]);
3036     }
3037   }
3038 
3039   return false;
3040 }
3041 
3042 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
3043                                                MVT &LocVT,
3044                                                CCValAssign::LocInfo &LocInfo,
3045                                                ISD::ArgFlagsTy &ArgFlags,
3046                                                CCState &State) {
3047   static const MCPhysReg ArgRegs[] = {
3048     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3049     PPC::F8
3050   };
3051 
3052   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3053 
3054   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3055 
3056   // If there is only one Floating-point register left we need to put both f64
3057   // values of a split ppc_fp128 value on the stack.
3058   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
3059     State.AllocateReg(ArgRegs[RegNum]);
3060   }
3061 
3062   // Always return false here, as this function only makes sure that the two f64
3063   // values a ppc_fp128 value is split into are both passed in registers or both
3064   // passed on the stack and does not actually allocate a register for the
3065   // current argument.
3066   return false;
3067 }
3068 
3069 /// FPR - The set of FP registers that should be allocated for arguments,
3070 /// on Darwin.
3071 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3072                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3073                                 PPC::F11, PPC::F12, PPC::F13};
3074 
3075 /// QFPR - The set of QPX registers that should be allocated for arguments.
3076 static const MCPhysReg QFPR[] = {
3077     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3078     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3079 
3080 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3081 /// the stack.
3082 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3083                                        unsigned PtrByteSize) {
3084   unsigned ArgSize = ArgVT.getStoreSize();
3085   if (Flags.isByVal())
3086     ArgSize = Flags.getByValSize();
3087 
3088   // Round up to multiples of the pointer size, except for array members,
3089   // which are always packed.
3090   if (!Flags.isInConsecutiveRegs())
3091     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3092 
3093   return ArgSize;
3094 }
3095 
3096 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3097 /// on the stack.
3098 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3099                                             ISD::ArgFlagsTy Flags,
3100                                             unsigned PtrByteSize) {
3101   unsigned Align = PtrByteSize;
3102 
3103   // Altivec parameters are padded to a 16 byte boundary.
3104   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3105       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3106       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3107       ArgVT == MVT::v1i128)
3108     Align = 16;
3109   // QPX vector types stored in double-precision are padded to a 32 byte
3110   // boundary.
3111   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3112     Align = 32;
3113 
3114   // ByVal parameters are aligned as requested.
3115   if (Flags.isByVal()) {
3116     unsigned BVAlign = Flags.getByValAlign();
3117     if (BVAlign > PtrByteSize) {
3118       if (BVAlign % PtrByteSize != 0)
3119           llvm_unreachable(
3120             "ByVal alignment is not a multiple of the pointer size");
3121 
3122       Align = BVAlign;
3123     }
3124   }
3125 
3126   // Array members are always packed to their original alignment.
3127   if (Flags.isInConsecutiveRegs()) {
3128     // If the array member was split into multiple registers, the first
3129     // needs to be aligned to the size of the full type.  (Except for
3130     // ppcf128, which is only aligned as its f64 components.)
3131     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3132       Align = OrigVT.getStoreSize();
3133     else
3134       Align = ArgVT.getStoreSize();
3135   }
3136 
3137   return Align;
3138 }
3139 
3140 /// CalculateStackSlotUsed - Return whether this argument will use its
3141 /// stack slot (instead of being passed in registers).  ArgOffset,
3142 /// AvailableFPRs, and AvailableVRs must hold the current argument
3143 /// position, and will be updated to account for this argument.
3144 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3145                                    ISD::ArgFlagsTy Flags,
3146                                    unsigned PtrByteSize,
3147                                    unsigned LinkageSize,
3148                                    unsigned ParamAreaSize,
3149                                    unsigned &ArgOffset,
3150                                    unsigned &AvailableFPRs,
3151                                    unsigned &AvailableVRs, bool HasQPX) {
3152   bool UseMemory = false;
3153 
3154   // Respect alignment of argument on the stack.
3155   unsigned Align =
3156     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3157   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3158   // If there's no space left in the argument save area, we must
3159   // use memory (this check also catches zero-sized arguments).
3160   if (ArgOffset >= LinkageSize + ParamAreaSize)
3161     UseMemory = true;
3162 
3163   // Allocate argument on the stack.
3164   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3165   if (Flags.isInConsecutiveRegsLast())
3166     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3167   // If we overran the argument save area, we must use memory
3168   // (this check catches arguments passed partially in memory)
3169   if (ArgOffset > LinkageSize + ParamAreaSize)
3170     UseMemory = true;
3171 
3172   // However, if the argument is actually passed in an FPR or a VR,
3173   // we don't use memory after all.
3174   if (!Flags.isByVal()) {
3175     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3176         // QPX registers overlap with the scalar FP registers.
3177         (HasQPX && (ArgVT == MVT::v4f32 ||
3178                     ArgVT == MVT::v4f64 ||
3179                     ArgVT == MVT::v4i1)))
3180       if (AvailableFPRs > 0) {
3181         --AvailableFPRs;
3182         return false;
3183       }
3184     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3185         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3186         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3187         ArgVT == MVT::v1i128)
3188       if (AvailableVRs > 0) {
3189         --AvailableVRs;
3190         return false;
3191       }
3192   }
3193 
3194   return UseMemory;
3195 }
3196 
3197 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3198 /// ensure minimum alignment required for target.
3199 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3200                                      unsigned NumBytes) {
3201   unsigned TargetAlign = Lowering->getStackAlignment();
3202   unsigned AlignMask = TargetAlign - 1;
3203   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3204   return NumBytes;
3205 }
3206 
3207 SDValue PPCTargetLowering::LowerFormalArguments(
3208     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3209     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3210     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3211   if (Subtarget.isSVR4ABI()) {
3212     if (Subtarget.isPPC64())
3213       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3214                                          dl, DAG, InVals);
3215     else
3216       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3217                                          dl, DAG, InVals);
3218   } else {
3219     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3220                                        dl, DAG, InVals);
3221   }
3222 }
3223 
3224 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3225     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3226     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3227     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3228 
3229   // 32-bit SVR4 ABI Stack Frame Layout:
3230   //              +-----------------------------------+
3231   //        +-->  |            Back chain             |
3232   //        |     +-----------------------------------+
3233   //        |     | Floating-point register save area |
3234   //        |     +-----------------------------------+
3235   //        |     |    General register save area     |
3236   //        |     +-----------------------------------+
3237   //        |     |          CR save word             |
3238   //        |     +-----------------------------------+
3239   //        |     |         VRSAVE save word          |
3240   //        |     +-----------------------------------+
3241   //        |     |         Alignment padding         |
3242   //        |     +-----------------------------------+
3243   //        |     |     Vector register save area     |
3244   //        |     +-----------------------------------+
3245   //        |     |       Local variable space        |
3246   //        |     +-----------------------------------+
3247   //        |     |        Parameter list area        |
3248   //        |     +-----------------------------------+
3249   //        |     |           LR save word            |
3250   //        |     +-----------------------------------+
3251   // SP-->  +---  |            Back chain             |
3252   //              +-----------------------------------+
3253   //
3254   // Specifications:
3255   //   System V Application Binary Interface PowerPC Processor Supplement
3256   //   AltiVec Technology Programming Interface Manual
3257 
3258   MachineFunction &MF = DAG.getMachineFunction();
3259   MachineFrameInfo &MFI = MF.getFrameInfo();
3260   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3261 
3262   EVT PtrVT = getPointerTy(MF.getDataLayout());
3263   // Potential tail calls could cause overwriting of argument stack slots.
3264   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3265                        (CallConv == CallingConv::Fast));
3266   unsigned PtrByteSize = 4;
3267 
3268   // Assign locations to all of the incoming arguments.
3269   SmallVector<CCValAssign, 16> ArgLocs;
3270   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3271                  *DAG.getContext());
3272 
3273   // Reserve space for the linkage area on the stack.
3274   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3275   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3276   if (useSoftFloat())
3277     CCInfo.PreAnalyzeFormalArguments(Ins);
3278 
3279   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3280   CCInfo.clearWasPPCF128();
3281 
3282   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3283     CCValAssign &VA = ArgLocs[i];
3284 
3285     // Arguments stored in registers.
3286     if (VA.isRegLoc()) {
3287       const TargetRegisterClass *RC;
3288       EVT ValVT = VA.getValVT();
3289 
3290       switch (ValVT.getSimpleVT().SimpleTy) {
3291         default:
3292           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3293         case MVT::i1:
3294         case MVT::i32:
3295           RC = &PPC::GPRCRegClass;
3296           break;
3297         case MVT::f32:
3298           if (Subtarget.hasP8Vector())
3299             RC = &PPC::VSSRCRegClass;
3300           else
3301             RC = &PPC::F4RCRegClass;
3302           break;
3303         case MVT::f64:
3304           if (Subtarget.hasVSX())
3305             RC = &PPC::VSFRCRegClass;
3306           else
3307             RC = &PPC::F8RCRegClass;
3308           break;
3309         case MVT::v16i8:
3310         case MVT::v8i16:
3311         case MVT::v4i32:
3312           RC = &PPC::VRRCRegClass;
3313           break;
3314         case MVT::v4f32:
3315           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3316           break;
3317         case MVT::v2f64:
3318         case MVT::v2i64:
3319           RC = &PPC::VRRCRegClass;
3320           break;
3321         case MVT::v4f64:
3322           RC = &PPC::QFRCRegClass;
3323           break;
3324         case MVT::v4i1:
3325           RC = &PPC::QBRCRegClass;
3326           break;
3327       }
3328 
3329       // Transform the arguments stored in physical registers into virtual ones.
3330       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3331       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3332                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3333 
3334       if (ValVT == MVT::i1)
3335         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3336 
3337       InVals.push_back(ArgValue);
3338     } else {
3339       // Argument stored in memory.
3340       assert(VA.isMemLoc());
3341 
3342       unsigned ArgSize = VA.getLocVT().getStoreSize();
3343       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3344                                      isImmutable);
3345 
3346       // Create load nodes to retrieve arguments from the stack.
3347       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3348       InVals.push_back(
3349           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3350     }
3351   }
3352 
3353   // Assign locations to all of the incoming aggregate by value arguments.
3354   // Aggregates passed by value are stored in the local variable space of the
3355   // caller's stack frame, right above the parameter list area.
3356   SmallVector<CCValAssign, 16> ByValArgLocs;
3357   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3358                       ByValArgLocs, *DAG.getContext());
3359 
3360   // Reserve stack space for the allocations in CCInfo.
3361   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3362 
3363   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3364 
3365   // Area that is at least reserved in the caller of this function.
3366   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3367   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3368 
3369   // Set the size that is at least reserved in caller of this function.  Tail
3370   // call optimized function's reserved stack space needs to be aligned so that
3371   // taking the difference between two stack areas will result in an aligned
3372   // stack.
3373   MinReservedArea =
3374       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3375   FuncInfo->setMinReservedArea(MinReservedArea);
3376 
3377   SmallVector<SDValue, 8> MemOps;
3378 
3379   // If the function takes variable number of arguments, make a frame index for
3380   // the start of the first vararg value... for expansion of llvm.va_start.
3381   if (isVarArg) {
3382     static const MCPhysReg GPArgRegs[] = {
3383       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3384       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3385     };
3386     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3387 
3388     static const MCPhysReg FPArgRegs[] = {
3389       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3390       PPC::F8
3391     };
3392     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3393 
3394     if (useSoftFloat())
3395        NumFPArgRegs = 0;
3396 
3397     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3398     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3399 
3400     // Make room for NumGPArgRegs and NumFPArgRegs.
3401     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3402                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3403 
3404     FuncInfo->setVarArgsStackOffset(
3405       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3406                             CCInfo.getNextStackOffset(), true));
3407 
3408     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3409     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3410 
3411     // The fixed integer arguments of a variadic function are stored to the
3412     // VarArgsFrameIndex on the stack so that they may be loaded by
3413     // dereferencing the result of va_next.
3414     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3415       // Get an existing live-in vreg, or add a new one.
3416       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3417       if (!VReg)
3418         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3419 
3420       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3421       SDValue Store =
3422           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3423       MemOps.push_back(Store);
3424       // Increment the address by four for the next argument to store
3425       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3426       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3427     }
3428 
3429     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3430     // is set.
3431     // The double arguments are stored to the VarArgsFrameIndex
3432     // on the stack.
3433     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3434       // Get an existing live-in vreg, or add a new one.
3435       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3436       if (!VReg)
3437         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3438 
3439       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3440       SDValue Store =
3441           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3442       MemOps.push_back(Store);
3443       // Increment the address by eight for the next argument to store
3444       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3445                                          PtrVT);
3446       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3447     }
3448   }
3449 
3450   if (!MemOps.empty())
3451     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3452 
3453   return Chain;
3454 }
3455 
3456 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3457 // value to MVT::i64 and then truncate to the correct register size.
3458 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3459                                              EVT ObjectVT, SelectionDAG &DAG,
3460                                              SDValue ArgVal,
3461                                              const SDLoc &dl) const {
3462   if (Flags.isSExt())
3463     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3464                          DAG.getValueType(ObjectVT));
3465   else if (Flags.isZExt())
3466     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3467                          DAG.getValueType(ObjectVT));
3468 
3469   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3470 }
3471 
3472 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3473     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3474     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3475     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3476   // TODO: add description of PPC stack frame format, or at least some docs.
3477   //
3478   bool isELFv2ABI = Subtarget.isELFv2ABI();
3479   bool isLittleEndian = Subtarget.isLittleEndian();
3480   MachineFunction &MF = DAG.getMachineFunction();
3481   MachineFrameInfo &MFI = MF.getFrameInfo();
3482   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3483 
3484   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3485          "fastcc not supported on varargs functions");
3486 
3487   EVT PtrVT = getPointerTy(MF.getDataLayout());
3488   // Potential tail calls could cause overwriting of argument stack slots.
3489   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3490                        (CallConv == CallingConv::Fast));
3491   unsigned PtrByteSize = 8;
3492   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3493 
3494   static const MCPhysReg GPR[] = {
3495     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3496     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3497   };
3498   static const MCPhysReg VR[] = {
3499     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3500     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3501   };
3502 
3503   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3504   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3505   const unsigned Num_VR_Regs  = array_lengthof(VR);
3506   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3507 
3508   // Do a first pass over the arguments to determine whether the ABI
3509   // guarantees that our caller has allocated the parameter save area
3510   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3511   // in the ELFv2 ABI, it is true if this is a vararg function or if
3512   // any parameter is located in a stack slot.
3513 
3514   bool HasParameterArea = !isELFv2ABI || isVarArg;
3515   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3516   unsigned NumBytes = LinkageSize;
3517   unsigned AvailableFPRs = Num_FPR_Regs;
3518   unsigned AvailableVRs = Num_VR_Regs;
3519   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3520     if (Ins[i].Flags.isNest())
3521       continue;
3522 
3523     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3524                                PtrByteSize, LinkageSize, ParamAreaSize,
3525                                NumBytes, AvailableFPRs, AvailableVRs,
3526                                Subtarget.hasQPX()))
3527       HasParameterArea = true;
3528   }
3529 
3530   // Add DAG nodes to load the arguments or copy them out of registers.  On
3531   // entry to a function on PPC, the arguments start after the linkage area,
3532   // although the first ones are often in registers.
3533 
3534   unsigned ArgOffset = LinkageSize;
3535   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3536   unsigned &QFPR_idx = FPR_idx;
3537   SmallVector<SDValue, 8> MemOps;
3538   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3539   unsigned CurArgIdx = 0;
3540   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3541     SDValue ArgVal;
3542     bool needsLoad = false;
3543     EVT ObjectVT = Ins[ArgNo].VT;
3544     EVT OrigVT = Ins[ArgNo].ArgVT;
3545     unsigned ObjSize = ObjectVT.getStoreSize();
3546     unsigned ArgSize = ObjSize;
3547     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3548     if (Ins[ArgNo].isOrigArg()) {
3549       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3550       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3551     }
3552     // We re-align the argument offset for each argument, except when using the
3553     // fast calling convention, when we need to make sure we do that only when
3554     // we'll actually use a stack slot.
3555     unsigned CurArgOffset, Align;
3556     auto ComputeArgOffset = [&]() {
3557       /* Respect alignment of argument on the stack.  */
3558       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3559       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3560       CurArgOffset = ArgOffset;
3561     };
3562 
3563     if (CallConv != CallingConv::Fast) {
3564       ComputeArgOffset();
3565 
3566       /* Compute GPR index associated with argument offset.  */
3567       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3568       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3569     }
3570 
3571     // FIXME the codegen can be much improved in some cases.
3572     // We do not have to keep everything in memory.
3573     if (Flags.isByVal()) {
3574       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3575 
3576       if (CallConv == CallingConv::Fast)
3577         ComputeArgOffset();
3578 
3579       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3580       ObjSize = Flags.getByValSize();
3581       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3582       // Empty aggregate parameters do not take up registers.  Examples:
3583       //   struct { } a;
3584       //   union  { } b;
3585       //   int c[0];
3586       // etc.  However, we have to provide a place-holder in InVals, so
3587       // pretend we have an 8-byte item at the current address for that
3588       // purpose.
3589       if (!ObjSize) {
3590         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3591         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3592         InVals.push_back(FIN);
3593         continue;
3594       }
3595 
3596       // Create a stack object covering all stack doublewords occupied
3597       // by the argument.  If the argument is (fully or partially) on
3598       // the stack, or if the argument is fully in registers but the
3599       // caller has allocated the parameter save anyway, we can refer
3600       // directly to the caller's stack frame.  Otherwise, create a
3601       // local copy in our own frame.
3602       int FI;
3603       if (HasParameterArea ||
3604           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3605         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3606       else
3607         FI = MFI.CreateStackObject(ArgSize, Align, false);
3608       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3609 
3610       // Handle aggregates smaller than 8 bytes.
3611       if (ObjSize < PtrByteSize) {
3612         // The value of the object is its address, which differs from the
3613         // address of the enclosing doubleword on big-endian systems.
3614         SDValue Arg = FIN;
3615         if (!isLittleEndian) {
3616           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3617           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3618         }
3619         InVals.push_back(Arg);
3620 
3621         if (GPR_idx != Num_GPR_Regs) {
3622           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3623           FuncInfo->addLiveInAttr(VReg, Flags);
3624           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3625           SDValue Store;
3626 
3627           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3628             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3629                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3630             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3631                                       MachinePointerInfo(&*FuncArg), ObjType);
3632           } else {
3633             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3634             // store the whole register as-is to the parameter save area
3635             // slot.
3636             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3637                                  MachinePointerInfo(&*FuncArg));
3638           }
3639 
3640           MemOps.push_back(Store);
3641         }
3642         // Whether we copied from a register or not, advance the offset
3643         // into the parameter save area by a full doubleword.
3644         ArgOffset += PtrByteSize;
3645         continue;
3646       }
3647 
3648       // The value of the object is its address, which is the address of
3649       // its first stack doubleword.
3650       InVals.push_back(FIN);
3651 
3652       // Store whatever pieces of the object are in registers to memory.
3653       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3654         if (GPR_idx == Num_GPR_Regs)
3655           break;
3656 
3657         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3658         FuncInfo->addLiveInAttr(VReg, Flags);
3659         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3660         SDValue Addr = FIN;
3661         if (j) {
3662           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3663           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3664         }
3665         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3666                                      MachinePointerInfo(&*FuncArg, j));
3667         MemOps.push_back(Store);
3668         ++GPR_idx;
3669       }
3670       ArgOffset += ArgSize;
3671       continue;
3672     }
3673 
3674     switch (ObjectVT.getSimpleVT().SimpleTy) {
3675     default: llvm_unreachable("Unhandled argument type!");
3676     case MVT::i1:
3677     case MVT::i32:
3678     case MVT::i64:
3679       if (Flags.isNest()) {
3680         // The 'nest' parameter, if any, is passed in R11.
3681         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3682         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3683 
3684         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3685           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3686 
3687         break;
3688       }
3689 
3690       // These can be scalar arguments or elements of an integer array type
3691       // passed directly.  Clang may use those instead of "byval" aggregate
3692       // types to avoid forcing arguments to memory unnecessarily.
3693       if (GPR_idx != Num_GPR_Regs) {
3694         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3695         FuncInfo->addLiveInAttr(VReg, Flags);
3696         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3697 
3698         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3699           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3700           // value to MVT::i64 and then truncate to the correct register size.
3701           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3702       } else {
3703         if (CallConv == CallingConv::Fast)
3704           ComputeArgOffset();
3705 
3706         needsLoad = true;
3707         ArgSize = PtrByteSize;
3708       }
3709       if (CallConv != CallingConv::Fast || needsLoad)
3710         ArgOffset += 8;
3711       break;
3712 
3713     case MVT::f32:
3714     case MVT::f64:
3715       // These can be scalar arguments or elements of a float array type
3716       // passed directly.  The latter are used to implement ELFv2 homogenous
3717       // float aggregates.
3718       if (FPR_idx != Num_FPR_Regs) {
3719         unsigned VReg;
3720 
3721         if (ObjectVT == MVT::f32)
3722           VReg = MF.addLiveIn(FPR[FPR_idx],
3723                               Subtarget.hasP8Vector()
3724                                   ? &PPC::VSSRCRegClass
3725                                   : &PPC::F4RCRegClass);
3726         else
3727           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3728                                                 ? &PPC::VSFRCRegClass
3729                                                 : &PPC::F8RCRegClass);
3730 
3731         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3732         ++FPR_idx;
3733       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3734         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3735         // once we support fp <-> gpr moves.
3736 
3737         // This can only ever happen in the presence of f32 array types,
3738         // since otherwise we never run out of FPRs before running out
3739         // of GPRs.
3740         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3741         FuncInfo->addLiveInAttr(VReg, Flags);
3742         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3743 
3744         if (ObjectVT == MVT::f32) {
3745           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3746             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3747                                  DAG.getConstant(32, dl, MVT::i32));
3748           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3749         }
3750 
3751         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3752       } else {
3753         if (CallConv == CallingConv::Fast)
3754           ComputeArgOffset();
3755 
3756         needsLoad = true;
3757       }
3758 
3759       // When passing an array of floats, the array occupies consecutive
3760       // space in the argument area; only round up to the next doubleword
3761       // at the end of the array.  Otherwise, each float takes 8 bytes.
3762       if (CallConv != CallingConv::Fast || needsLoad) {
3763         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3764         ArgOffset += ArgSize;
3765         if (Flags.isInConsecutiveRegsLast())
3766           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3767       }
3768       break;
3769     case MVT::v4f32:
3770     case MVT::v4i32:
3771     case MVT::v8i16:
3772     case MVT::v16i8:
3773     case MVT::v2f64:
3774     case MVT::v2i64:
3775     case MVT::v1i128:
3776       if (!Subtarget.hasQPX()) {
3777       // These can be scalar arguments or elements of a vector array type
3778       // passed directly.  The latter are used to implement ELFv2 homogenous
3779       // vector aggregates.
3780       if (VR_idx != Num_VR_Regs) {
3781         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3782         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3783         ++VR_idx;
3784       } else {
3785         if (CallConv == CallingConv::Fast)
3786           ComputeArgOffset();
3787 
3788         needsLoad = true;
3789       }
3790       if (CallConv != CallingConv::Fast || needsLoad)
3791         ArgOffset += 16;
3792       break;
3793       } // not QPX
3794 
3795       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3796              "Invalid QPX parameter type");
3797       /* fall through */
3798 
3799     case MVT::v4f64:
3800     case MVT::v4i1:
3801       // QPX vectors are treated like their scalar floating-point subregisters
3802       // (except that they're larger).
3803       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3804       if (QFPR_idx != Num_QFPR_Regs) {
3805         const TargetRegisterClass *RC;
3806         switch (ObjectVT.getSimpleVT().SimpleTy) {
3807         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3808         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3809         default:         RC = &PPC::QBRCRegClass; break;
3810         }
3811 
3812         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3813         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3814         ++QFPR_idx;
3815       } else {
3816         if (CallConv == CallingConv::Fast)
3817           ComputeArgOffset();
3818         needsLoad = true;
3819       }
3820       if (CallConv != CallingConv::Fast || needsLoad)
3821         ArgOffset += Sz;
3822       break;
3823     }
3824 
3825     // We need to load the argument to a virtual register if we determined
3826     // above that we ran out of physical registers of the appropriate type.
3827     if (needsLoad) {
3828       if (ObjSize < ArgSize && !isLittleEndian)
3829         CurArgOffset += ArgSize - ObjSize;
3830       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3831       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3832       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3833     }
3834 
3835     InVals.push_back(ArgVal);
3836   }
3837 
3838   // Area that is at least reserved in the caller of this function.
3839   unsigned MinReservedArea;
3840   if (HasParameterArea)
3841     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3842   else
3843     MinReservedArea = LinkageSize;
3844 
3845   // Set the size that is at least reserved in caller of this function.  Tail
3846   // call optimized functions' reserved stack space needs to be aligned so that
3847   // taking the difference between two stack areas will result in an aligned
3848   // stack.
3849   MinReservedArea =
3850       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3851   FuncInfo->setMinReservedArea(MinReservedArea);
3852 
3853   // If the function takes variable number of arguments, make a frame index for
3854   // the start of the first vararg value... for expansion of llvm.va_start.
3855   if (isVarArg) {
3856     int Depth = ArgOffset;
3857 
3858     FuncInfo->setVarArgsFrameIndex(
3859       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3860     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3861 
3862     // If this function is vararg, store any remaining integer argument regs
3863     // to their spots on the stack so that they may be loaded by dereferencing
3864     // the result of va_next.
3865     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3866          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3867       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3868       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3869       SDValue Store =
3870           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3871       MemOps.push_back(Store);
3872       // Increment the address by four for the next argument to store
3873       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3874       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3875     }
3876   }
3877 
3878   if (!MemOps.empty())
3879     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3880 
3881   return Chain;
3882 }
3883 
3884 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3885     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3886     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3887     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3888   // TODO: add description of PPC stack frame format, or at least some docs.
3889   //
3890   MachineFunction &MF = DAG.getMachineFunction();
3891   MachineFrameInfo &MFI = MF.getFrameInfo();
3892   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3893 
3894   EVT PtrVT = getPointerTy(MF.getDataLayout());
3895   bool isPPC64 = PtrVT == MVT::i64;
3896   // Potential tail calls could cause overwriting of argument stack slots.
3897   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3898                        (CallConv == CallingConv::Fast));
3899   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3900   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3901   unsigned ArgOffset = LinkageSize;
3902   // Area that is at least reserved in caller of this function.
3903   unsigned MinReservedArea = ArgOffset;
3904 
3905   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3906     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3907     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3908   };
3909   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3910     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3911     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3912   };
3913   static const MCPhysReg VR[] = {
3914     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3915     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3916   };
3917 
3918   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3919   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3920   const unsigned Num_VR_Regs  = array_lengthof( VR);
3921 
3922   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3923 
3924   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3925 
3926   // In 32-bit non-varargs functions, the stack space for vectors is after the
3927   // stack space for non-vectors.  We do not use this space unless we have
3928   // too many vectors to fit in registers, something that only occurs in
3929   // constructed examples:), but we have to walk the arglist to figure
3930   // that out...for the pathological case, compute VecArgOffset as the
3931   // start of the vector parameter area.  Computing VecArgOffset is the
3932   // entire point of the following loop.
3933   unsigned VecArgOffset = ArgOffset;
3934   if (!isVarArg && !isPPC64) {
3935     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3936          ++ArgNo) {
3937       EVT ObjectVT = Ins[ArgNo].VT;
3938       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3939 
3940       if (Flags.isByVal()) {
3941         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3942         unsigned ObjSize = Flags.getByValSize();
3943         unsigned ArgSize =
3944                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3945         VecArgOffset += ArgSize;
3946         continue;
3947       }
3948 
3949       switch(ObjectVT.getSimpleVT().SimpleTy) {
3950       default: llvm_unreachable("Unhandled argument type!");
3951       case MVT::i1:
3952       case MVT::i32:
3953       case MVT::f32:
3954         VecArgOffset += 4;
3955         break;
3956       case MVT::i64:  // PPC64
3957       case MVT::f64:
3958         // FIXME: We are guaranteed to be !isPPC64 at this point.
3959         // Does MVT::i64 apply?
3960         VecArgOffset += 8;
3961         break;
3962       case MVT::v4f32:
3963       case MVT::v4i32:
3964       case MVT::v8i16:
3965       case MVT::v16i8:
3966         // Nothing to do, we're only looking at Nonvector args here.
3967         break;
3968       }
3969     }
3970   }
3971   // We've found where the vector parameter area in memory is.  Skip the
3972   // first 12 parameters; these don't use that memory.
3973   VecArgOffset = ((VecArgOffset+15)/16)*16;
3974   VecArgOffset += 12*16;
3975 
3976   // Add DAG nodes to load the arguments or copy them out of registers.  On
3977   // entry to a function on PPC, the arguments start after the linkage area,
3978   // although the first ones are often in registers.
3979 
3980   SmallVector<SDValue, 8> MemOps;
3981   unsigned nAltivecParamsAtEnd = 0;
3982   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3983   unsigned CurArgIdx = 0;
3984   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3985     SDValue ArgVal;
3986     bool needsLoad = false;
3987     EVT ObjectVT = Ins[ArgNo].VT;
3988     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3989     unsigned ArgSize = ObjSize;
3990     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3991     if (Ins[ArgNo].isOrigArg()) {
3992       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3993       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3994     }
3995     unsigned CurArgOffset = ArgOffset;
3996 
3997     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3998     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3999         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4000       if (isVarArg || isPPC64) {
4001         MinReservedArea = ((MinReservedArea+15)/16)*16;
4002         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4003                                                   Flags,
4004                                                   PtrByteSize);
4005       } else  nAltivecParamsAtEnd++;
4006     } else
4007       // Calculate min reserved area.
4008       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4009                                                 Flags,
4010                                                 PtrByteSize);
4011 
4012     // FIXME the codegen can be much improved in some cases.
4013     // We do not have to keep everything in memory.
4014     if (Flags.isByVal()) {
4015       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4016 
4017       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4018       ObjSize = Flags.getByValSize();
4019       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4020       // Objects of size 1 and 2 are right justified, everything else is
4021       // left justified.  This means the memory address is adjusted forwards.
4022       if (ObjSize==1 || ObjSize==2) {
4023         CurArgOffset = CurArgOffset + (4 - ObjSize);
4024       }
4025       // The value of the object is its address.
4026       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4027       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4028       InVals.push_back(FIN);
4029       if (ObjSize==1 || ObjSize==2) {
4030         if (GPR_idx != Num_GPR_Regs) {
4031           unsigned VReg;
4032           if (isPPC64)
4033             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4034           else
4035             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4036           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4037           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4038           SDValue Store =
4039               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4040                                 MachinePointerInfo(&*FuncArg), ObjType);
4041           MemOps.push_back(Store);
4042           ++GPR_idx;
4043         }
4044 
4045         ArgOffset += PtrByteSize;
4046 
4047         continue;
4048       }
4049       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4050         // Store whatever pieces of the object are in registers
4051         // to memory.  ArgOffset will be the address of the beginning
4052         // of the object.
4053         if (GPR_idx != Num_GPR_Regs) {
4054           unsigned VReg;
4055           if (isPPC64)
4056             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4057           else
4058             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4059           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4060           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4061           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4062           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4063                                        MachinePointerInfo(&*FuncArg, j));
4064           MemOps.push_back(Store);
4065           ++GPR_idx;
4066           ArgOffset += PtrByteSize;
4067         } else {
4068           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4069           break;
4070         }
4071       }
4072       continue;
4073     }
4074 
4075     switch (ObjectVT.getSimpleVT().SimpleTy) {
4076     default: llvm_unreachable("Unhandled argument type!");
4077     case MVT::i1:
4078     case MVT::i32:
4079       if (!isPPC64) {
4080         if (GPR_idx != Num_GPR_Regs) {
4081           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4082           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4083 
4084           if (ObjectVT == MVT::i1)
4085             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4086 
4087           ++GPR_idx;
4088         } else {
4089           needsLoad = true;
4090           ArgSize = PtrByteSize;
4091         }
4092         // All int arguments reserve stack space in the Darwin ABI.
4093         ArgOffset += PtrByteSize;
4094         break;
4095       }
4096       LLVM_FALLTHROUGH;
4097     case MVT::i64:  // PPC64
4098       if (GPR_idx != Num_GPR_Regs) {
4099         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4100         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4101 
4102         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4103           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4104           // value to MVT::i64 and then truncate to the correct register size.
4105           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4106 
4107         ++GPR_idx;
4108       } else {
4109         needsLoad = true;
4110         ArgSize = PtrByteSize;
4111       }
4112       // All int arguments reserve stack space in the Darwin ABI.
4113       ArgOffset += 8;
4114       break;
4115 
4116     case MVT::f32:
4117     case MVT::f64:
4118       // Every 4 bytes of argument space consumes one of the GPRs available for
4119       // argument passing.
4120       if (GPR_idx != Num_GPR_Regs) {
4121         ++GPR_idx;
4122         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4123           ++GPR_idx;
4124       }
4125       if (FPR_idx != Num_FPR_Regs) {
4126         unsigned VReg;
4127 
4128         if (ObjectVT == MVT::f32)
4129           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4130         else
4131           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4132 
4133         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4134         ++FPR_idx;
4135       } else {
4136         needsLoad = true;
4137       }
4138 
4139       // All FP arguments reserve stack space in the Darwin ABI.
4140       ArgOffset += isPPC64 ? 8 : ObjSize;
4141       break;
4142     case MVT::v4f32:
4143     case MVT::v4i32:
4144     case MVT::v8i16:
4145     case MVT::v16i8:
4146       // Note that vector arguments in registers don't reserve stack space,
4147       // except in varargs functions.
4148       if (VR_idx != Num_VR_Regs) {
4149         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4150         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4151         if (isVarArg) {
4152           while ((ArgOffset % 16) != 0) {
4153             ArgOffset += PtrByteSize;
4154             if (GPR_idx != Num_GPR_Regs)
4155               GPR_idx++;
4156           }
4157           ArgOffset += 16;
4158           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4159         }
4160         ++VR_idx;
4161       } else {
4162         if (!isVarArg && !isPPC64) {
4163           // Vectors go after all the nonvectors.
4164           CurArgOffset = VecArgOffset;
4165           VecArgOffset += 16;
4166         } else {
4167           // Vectors are aligned.
4168           ArgOffset = ((ArgOffset+15)/16)*16;
4169           CurArgOffset = ArgOffset;
4170           ArgOffset += 16;
4171         }
4172         needsLoad = true;
4173       }
4174       break;
4175     }
4176 
4177     // We need to load the argument to a virtual register if we determined above
4178     // that we ran out of physical registers of the appropriate type.
4179     if (needsLoad) {
4180       int FI = MFI.CreateFixedObject(ObjSize,
4181                                      CurArgOffset + (ArgSize - ObjSize),
4182                                      isImmutable);
4183       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4184       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4185     }
4186 
4187     InVals.push_back(ArgVal);
4188   }
4189 
4190   // Allow for Altivec parameters at the end, if needed.
4191   if (nAltivecParamsAtEnd) {
4192     MinReservedArea = ((MinReservedArea+15)/16)*16;
4193     MinReservedArea += 16*nAltivecParamsAtEnd;
4194   }
4195 
4196   // Area that is at least reserved in the caller of this function.
4197   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4198 
4199   // Set the size that is at least reserved in caller of this function.  Tail
4200   // call optimized functions' reserved stack space needs to be aligned so that
4201   // taking the difference between two stack areas will result in an aligned
4202   // stack.
4203   MinReservedArea =
4204       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4205   FuncInfo->setMinReservedArea(MinReservedArea);
4206 
4207   // If the function takes variable number of arguments, make a frame index for
4208   // the start of the first vararg value... for expansion of llvm.va_start.
4209   if (isVarArg) {
4210     int Depth = ArgOffset;
4211 
4212     FuncInfo->setVarArgsFrameIndex(
4213       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4214                             Depth, true));
4215     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4216 
4217     // If this function is vararg, store any remaining integer argument regs
4218     // to their spots on the stack so that they may be loaded by dereferencing
4219     // the result of va_next.
4220     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4221       unsigned VReg;
4222 
4223       if (isPPC64)
4224         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4225       else
4226         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4227 
4228       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4229       SDValue Store =
4230           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4231       MemOps.push_back(Store);
4232       // Increment the address by four for the next argument to store
4233       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4234       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4235     }
4236   }
4237 
4238   if (!MemOps.empty())
4239     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4240 
4241   return Chain;
4242 }
4243 
4244 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4245 /// adjusted to accommodate the arguments for the tailcall.
4246 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4247                                    unsigned ParamSize) {
4248 
4249   if (!isTailCall) return 0;
4250 
4251   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4252   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4253   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4254   // Remember only if the new adjustement is bigger.
4255   if (SPDiff < FI->getTailCallSPDelta())
4256     FI->setTailCallSPDelta(SPDiff);
4257 
4258   return SPDiff;
4259 }
4260 
4261 static bool isFunctionGlobalAddress(SDValue Callee);
4262 
4263 static bool
4264 callsShareTOCBase(const Function *Caller, SDValue Callee,
4265                     const TargetMachine &TM) {
4266   // If !G, Callee can be an external symbol.
4267   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4268   if (!G)
4269     return false;
4270 
4271   // The medium and large code models are expected to provide a sufficiently
4272   // large TOC to provide all data addressing needs of a module with a
4273   // single TOC. Since each module will be addressed with a single TOC then we
4274   // only need to check that caller and callee don't cross dso boundaries.
4275   if (CodeModel::Medium == TM.getCodeModel() ||
4276       CodeModel::Large == TM.getCodeModel())
4277     return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal());
4278 
4279   // Otherwise we need to ensure callee and caller are in the same section,
4280   // since the linker may allocate multiple TOCs, and we don't know which
4281   // sections will belong to the same TOC base.
4282 
4283   const GlobalValue *GV = G->getGlobal();
4284   if (!GV->isStrongDefinitionForLinker())
4285     return false;
4286 
4287   // Any explicitly-specified sections and section prefixes must also match.
4288   // Also, if we're using -ffunction-sections, then each function is always in
4289   // a different section (the same is true for COMDAT functions).
4290   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4291       GV->getSection() != Caller->getSection())
4292     return false;
4293   if (const auto *F = dyn_cast<Function>(GV)) {
4294     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4295       return false;
4296   }
4297 
4298   // If the callee might be interposed, then we can't assume the ultimate call
4299   // target will be in the same section. Even in cases where we can assume that
4300   // interposition won't happen, in any case where the linker might insert a
4301   // stub to allow for interposition, we must generate code as though
4302   // interposition might occur. To understand why this matters, consider a
4303   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4304   // in the same section, but a is in a different module (i.e. has a different
4305   // TOC base pointer). If the linker allows for interposition between b and c,
4306   // then it will generate a stub for the call edge between b and c which will
4307   // save the TOC pointer into the designated stack slot allocated by b. If we
4308   // return true here, and therefore allow a tail call between b and c, that
4309   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4310   // pointer into the stack slot allocated by a (where the a -> b stub saved
4311   // a's TOC base pointer). If we're not considering a tail call, but rather,
4312   // whether a nop is needed after the call instruction in b, because the linker
4313   // will insert a stub, it might complain about a missing nop if we omit it
4314   // (although many don't complain in this case).
4315   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4316     return false;
4317 
4318   return true;
4319 }
4320 
4321 static bool
4322 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4323                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4324   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4325 
4326   const unsigned PtrByteSize = 8;
4327   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4328 
4329   static const MCPhysReg GPR[] = {
4330     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4331     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4332   };
4333   static const MCPhysReg VR[] = {
4334     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4335     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4336   };
4337 
4338   const unsigned NumGPRs = array_lengthof(GPR);
4339   const unsigned NumFPRs = 13;
4340   const unsigned NumVRs = array_lengthof(VR);
4341   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4342 
4343   unsigned NumBytes = LinkageSize;
4344   unsigned AvailableFPRs = NumFPRs;
4345   unsigned AvailableVRs = NumVRs;
4346 
4347   for (const ISD::OutputArg& Param : Outs) {
4348     if (Param.Flags.isNest()) continue;
4349 
4350     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4351                                PtrByteSize, LinkageSize, ParamAreaSize,
4352                                NumBytes, AvailableFPRs, AvailableVRs,
4353                                Subtarget.hasQPX()))
4354       return true;
4355   }
4356   return false;
4357 }
4358 
4359 static bool
4360 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4361   if (CS.arg_size() != CallerFn->arg_size())
4362     return false;
4363 
4364   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4365   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4366   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4367 
4368   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4369     const Value* CalleeArg = *CalleeArgIter;
4370     const Value* CallerArg = &(*CallerArgIter);
4371     if (CalleeArg == CallerArg)
4372       continue;
4373 
4374     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4375     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4376     //      }
4377     // 1st argument of callee is undef and has the same type as caller.
4378     if (CalleeArg->getType() == CallerArg->getType() &&
4379         isa<UndefValue>(CalleeArg))
4380       continue;
4381 
4382     return false;
4383   }
4384 
4385   return true;
4386 }
4387 
4388 bool
4389 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4390                                     SDValue Callee,
4391                                     CallingConv::ID CalleeCC,
4392                                     ImmutableCallSite CS,
4393                                     bool isVarArg,
4394                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4395                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4396                                     SelectionDAG& DAG) const {
4397   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4398 
4399   if (DisableSCO && !TailCallOpt) return false;
4400 
4401   // Variadic argument functions are not supported.
4402   if (isVarArg) return false;
4403 
4404   MachineFunction &MF = DAG.getMachineFunction();
4405   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4406 
4407   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4408   // the same calling convention
4409   if (CallerCC != CalleeCC) return false;
4410 
4411   // SCO support C calling convention
4412   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4413     return false;
4414 
4415   // Caller contains any byval parameter is not supported.
4416   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4417     return false;
4418 
4419   // Callee contains any byval parameter is not supported, too.
4420   // Note: This is a quick work around, because in some cases, e.g.
4421   // caller's stack size > callee's stack size, we are still able to apply
4422   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4423   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4424     return false;
4425 
4426   // No TCO/SCO on indirect call because Caller have to restore its TOC
4427   if (!isFunctionGlobalAddress(Callee) &&
4428       !isa<ExternalSymbolSDNode>(Callee))
4429     return false;
4430 
4431   // If the caller and callee potentially have different TOC bases then we
4432   // cannot tail call since we need to restore the TOC pointer after the call.
4433   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4434   if (!callsShareTOCBase(MF.getFunction(), Callee, getTargetMachine()))
4435     return false;
4436 
4437   // TCO allows altering callee ABI, so we don't have to check further.
4438   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4439     return true;
4440 
4441   if (DisableSCO) return false;
4442 
4443   // If callee use the same argument list that caller is using, then we can
4444   // apply SCO on this case. If it is not, then we need to check if callee needs
4445   // stack for passing arguments.
4446   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4447       needStackSlotPassParameters(Subtarget, Outs)) {
4448     return false;
4449   }
4450 
4451   return true;
4452 }
4453 
4454 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4455 /// for tail call optimization. Targets which want to do tail call
4456 /// optimization should implement this function.
4457 bool
4458 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4459                                                      CallingConv::ID CalleeCC,
4460                                                      bool isVarArg,
4461                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4462                                                      SelectionDAG& DAG) const {
4463   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4464     return false;
4465 
4466   // Variable argument functions are not supported.
4467   if (isVarArg)
4468     return false;
4469 
4470   MachineFunction &MF = DAG.getMachineFunction();
4471   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4472   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4473     // Functions containing by val parameters are not supported.
4474     for (unsigned i = 0; i != Ins.size(); i++) {
4475        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4476        if (Flags.isByVal()) return false;
4477     }
4478 
4479     // Non-PIC/GOT tail calls are supported.
4480     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4481       return true;
4482 
4483     // At the moment we can only do local tail calls (in same module, hidden
4484     // or protected) if we are generating PIC.
4485     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4486       return G->getGlobal()->hasHiddenVisibility()
4487           || G->getGlobal()->hasProtectedVisibility();
4488   }
4489 
4490   return false;
4491 }
4492 
4493 /// isCallCompatibleAddress - Return the immediate to use if the specified
4494 /// 32-bit value is representable in the immediate field of a BxA instruction.
4495 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4496   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4497   if (!C) return nullptr;
4498 
4499   int Addr = C->getZExtValue();
4500   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4501       SignExtend32<26>(Addr) != Addr)
4502     return nullptr;  // Top 6 bits have to be sext of immediate.
4503 
4504   return DAG
4505       .getConstant(
4506           (int)C->getZExtValue() >> 2, SDLoc(Op),
4507           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4508       .getNode();
4509 }
4510 
4511 namespace {
4512 
4513 struct TailCallArgumentInfo {
4514   SDValue Arg;
4515   SDValue FrameIdxOp;
4516   int FrameIdx = 0;
4517 
4518   TailCallArgumentInfo() = default;
4519 };
4520 
4521 } // end anonymous namespace
4522 
4523 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4524 static void StoreTailCallArgumentsToStackSlot(
4525     SelectionDAG &DAG, SDValue Chain,
4526     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4527     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4528   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4529     SDValue Arg = TailCallArgs[i].Arg;
4530     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4531     int FI = TailCallArgs[i].FrameIdx;
4532     // Store relative to framepointer.
4533     MemOpChains.push_back(DAG.getStore(
4534         Chain, dl, Arg, FIN,
4535         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4536   }
4537 }
4538 
4539 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4540 /// the appropriate stack slot for the tail call optimized function call.
4541 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4542                                              SDValue OldRetAddr, SDValue OldFP,
4543                                              int SPDiff, const SDLoc &dl) {
4544   if (SPDiff) {
4545     // Calculate the new stack slot for the return address.
4546     MachineFunction &MF = DAG.getMachineFunction();
4547     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4548     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4549     bool isPPC64 = Subtarget.isPPC64();
4550     int SlotSize = isPPC64 ? 8 : 4;
4551     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4552     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4553                                                          NewRetAddrLoc, true);
4554     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4555     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4556     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4557                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4558 
4559     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4560     // slot as the FP is never overwritten.
4561     if (Subtarget.isDarwinABI()) {
4562       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4563       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4564                                                          true);
4565       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4566       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4567                            MachinePointerInfo::getFixedStack(
4568                                DAG.getMachineFunction(), NewFPIdx));
4569     }
4570   }
4571   return Chain;
4572 }
4573 
4574 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4575 /// the position of the argument.
4576 static void
4577 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4578                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4579                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4580   int Offset = ArgOffset + SPDiff;
4581   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4582   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4583   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4584   SDValue FIN = DAG.getFrameIndex(FI, VT);
4585   TailCallArgumentInfo Info;
4586   Info.Arg = Arg;
4587   Info.FrameIdxOp = FIN;
4588   Info.FrameIdx = FI;
4589   TailCallArguments.push_back(Info);
4590 }
4591 
4592 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4593 /// stack slot. Returns the chain as result and the loaded frame pointers in
4594 /// LROpOut/FPOpout. Used when tail calling.
4595 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4596     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4597     SDValue &FPOpOut, const SDLoc &dl) const {
4598   if (SPDiff) {
4599     // Load the LR and FP stack slot for later adjusting.
4600     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4601     LROpOut = getReturnAddrFrameIndex(DAG);
4602     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4603     Chain = SDValue(LROpOut.getNode(), 1);
4604 
4605     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4606     // slot as the FP is never overwritten.
4607     if (Subtarget.isDarwinABI()) {
4608       FPOpOut = getFramePointerFrameIndex(DAG);
4609       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4610       Chain = SDValue(FPOpOut.getNode(), 1);
4611     }
4612   }
4613   return Chain;
4614 }
4615 
4616 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4617 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4618 /// specified by the specific parameter attribute. The copy will be passed as
4619 /// a byval function parameter.
4620 /// Sometimes what we are copying is the end of a larger object, the part that
4621 /// does not fit in registers.
4622 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4623                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4624                                          SelectionDAG &DAG, const SDLoc &dl) {
4625   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4626   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4627                        false, false, false, MachinePointerInfo(),
4628                        MachinePointerInfo());
4629 }
4630 
4631 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4632 /// tail calls.
4633 static void LowerMemOpCallTo(
4634     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4635     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4636     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4637     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4638   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4639   if (!isTailCall) {
4640     if (isVector) {
4641       SDValue StackPtr;
4642       if (isPPC64)
4643         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4644       else
4645         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4646       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4647                            DAG.getConstant(ArgOffset, dl, PtrVT));
4648     }
4649     MemOpChains.push_back(
4650         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4651     // Calculate and remember argument location.
4652   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4653                                   TailCallArguments);
4654 }
4655 
4656 static void
4657 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4658                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4659                 SDValue FPOp,
4660                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4661   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4662   // might overwrite each other in case of tail call optimization.
4663   SmallVector<SDValue, 8> MemOpChains2;
4664   // Do not flag preceding copytoreg stuff together with the following stuff.
4665   InFlag = SDValue();
4666   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4667                                     MemOpChains2, dl);
4668   if (!MemOpChains2.empty())
4669     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4670 
4671   // Store the return address to the appropriate stack slot.
4672   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4673 
4674   // Emit callseq_end just before tailcall node.
4675   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4676                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4677   InFlag = Chain.getValue(1);
4678 }
4679 
4680 // Is this global address that of a function that can be called by name? (as
4681 // opposed to something that must hold a descriptor for an indirect call).
4682 static bool isFunctionGlobalAddress(SDValue Callee) {
4683   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4684     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4685         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4686       return false;
4687 
4688     return G->getGlobal()->getValueType()->isFunctionTy();
4689   }
4690 
4691   return false;
4692 }
4693 
4694 static unsigned
4695 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4696             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4697             bool isPatchPoint, bool hasNest,
4698             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4699             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4700             ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4701   bool isPPC64 = Subtarget.isPPC64();
4702   bool isSVR4ABI = Subtarget.isSVR4ABI();
4703   bool isELFv2ABI = Subtarget.isELFv2ABI();
4704 
4705   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4706   NodeTys.push_back(MVT::Other);   // Returns a chain
4707   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4708 
4709   unsigned CallOpc = PPCISD::CALL;
4710 
4711   bool needIndirectCall = true;
4712   if (!isSVR4ABI || !isPPC64)
4713     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4714       // If this is an absolute destination address, use the munged value.
4715       Callee = SDValue(Dest, 0);
4716       needIndirectCall = false;
4717     }
4718 
4719   // PC-relative references to external symbols should go through $stub, unless
4720   // we're building with the leopard linker or later, which automatically
4721   // synthesizes these stubs.
4722   const TargetMachine &TM = DAG.getTarget();
4723   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4724   const GlobalValue *GV = nullptr;
4725   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4726     GV = G->getGlobal();
4727   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4728   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4729 
4730   if (isFunctionGlobalAddress(Callee)) {
4731     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4732     // A call to a TLS address is actually an indirect call to a
4733     // thread-specific pointer.
4734     unsigned OpFlags = 0;
4735     if (UsePlt)
4736       OpFlags = PPCII::MO_PLT;
4737 
4738     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4739     // every direct call is) turn it into a TargetGlobalAddress /
4740     // TargetExternalSymbol node so that legalize doesn't hack it.
4741     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4742                                         Callee.getValueType(), 0, OpFlags);
4743     needIndirectCall = false;
4744   }
4745 
4746   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4747     unsigned char OpFlags = 0;
4748 
4749     if (UsePlt)
4750       OpFlags = PPCII::MO_PLT;
4751 
4752     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4753                                          OpFlags);
4754     needIndirectCall = false;
4755   }
4756 
4757   if (isPatchPoint) {
4758     // We'll form an invalid direct call when lowering a patchpoint; the full
4759     // sequence for an indirect call is complicated, and many of the
4760     // instructions introduced might have side effects (and, thus, can't be
4761     // removed later). The call itself will be removed as soon as the
4762     // argument/return lowering is complete, so the fact that it has the wrong
4763     // kind of operands should not really matter.
4764     needIndirectCall = false;
4765   }
4766 
4767   if (needIndirectCall) {
4768     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4769     // to do the call, we can't use PPCISD::CALL.
4770     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4771 
4772     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4773       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4774       // entry point, but to the function descriptor (the function entry point
4775       // address is part of the function descriptor though).
4776       // The function descriptor is a three doubleword structure with the
4777       // following fields: function entry point, TOC base address and
4778       // environment pointer.
4779       // Thus for a call through a function pointer, the following actions need
4780       // to be performed:
4781       //   1. Save the TOC of the caller in the TOC save area of its stack
4782       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4783       //   2. Load the address of the function entry point from the function
4784       //      descriptor.
4785       //   3. Load the TOC of the callee from the function descriptor into r2.
4786       //   4. Load the environment pointer from the function descriptor into
4787       //      r11.
4788       //   5. Branch to the function entry point address.
4789       //   6. On return of the callee, the TOC of the caller needs to be
4790       //      restored (this is done in FinishCall()).
4791       //
4792       // The loads are scheduled at the beginning of the call sequence, and the
4793       // register copies are flagged together to ensure that no other
4794       // operations can be scheduled in between. E.g. without flagging the
4795       // copies together, a TOC access in the caller could be scheduled between
4796       // the assignment of the callee TOC and the branch to the callee, which
4797       // results in the TOC access going through the TOC of the callee instead
4798       // of going through the TOC of the caller, which leads to incorrect code.
4799 
4800       // Load the address of the function entry point from the function
4801       // descriptor.
4802       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4803       if (LDChain.getValueType() == MVT::Glue)
4804         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4805 
4806       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4807                           ? (MachineMemOperand::MODereferenceable |
4808                              MachineMemOperand::MOInvariant)
4809                           : MachineMemOperand::MONone;
4810 
4811       MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
4812       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4813                                         /* Alignment = */ 8, MMOFlags);
4814 
4815       // Load environment pointer into r11.
4816       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4817       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4818       SDValue LoadEnvPtr =
4819           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4820                       /* Alignment = */ 8, MMOFlags);
4821 
4822       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4823       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4824       SDValue TOCPtr =
4825           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4826                       /* Alignment = */ 8, MMOFlags);
4827 
4828       setUsesTOCBasePtr(DAG);
4829       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4830                                         InFlag);
4831       Chain = TOCVal.getValue(0);
4832       InFlag = TOCVal.getValue(1);
4833 
4834       // If the function call has an explicit 'nest' parameter, it takes the
4835       // place of the environment pointer.
4836       if (!hasNest) {
4837         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4838                                           InFlag);
4839 
4840         Chain = EnvVal.getValue(0);
4841         InFlag = EnvVal.getValue(1);
4842       }
4843 
4844       MTCTROps[0] = Chain;
4845       MTCTROps[1] = LoadFuncPtr;
4846       MTCTROps[2] = InFlag;
4847     }
4848 
4849     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4850                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4851     InFlag = Chain.getValue(1);
4852 
4853     NodeTys.clear();
4854     NodeTys.push_back(MVT::Other);
4855     NodeTys.push_back(MVT::Glue);
4856     Ops.push_back(Chain);
4857     CallOpc = PPCISD::BCTRL;
4858     Callee.setNode(nullptr);
4859     // Add use of X11 (holding environment pointer)
4860     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4861       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4862     // Add CTR register as callee so a bctr can be emitted later.
4863     if (isTailCall)
4864       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4865   }
4866 
4867   // If this is a direct call, pass the chain and the callee.
4868   if (Callee.getNode()) {
4869     Ops.push_back(Chain);
4870     Ops.push_back(Callee);
4871   }
4872   // If this is a tail call add stack pointer delta.
4873   if (isTailCall)
4874     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4875 
4876   // Add argument registers to the end of the list so that they are known live
4877   // into the call.
4878   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4879     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4880                                   RegsToPass[i].second.getValueType()));
4881 
4882   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4883   // into the call.
4884   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4885     setUsesTOCBasePtr(DAG);
4886     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4887   }
4888 
4889   return CallOpc;
4890 }
4891 
4892 SDValue PPCTargetLowering::LowerCallResult(
4893     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4894     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4895     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4896   SmallVector<CCValAssign, 16> RVLocs;
4897   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4898                     *DAG.getContext());
4899   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4900 
4901   // Copy all of the result registers out of their specified physreg.
4902   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4903     CCValAssign &VA = RVLocs[i];
4904     assert(VA.isRegLoc() && "Can only return in registers!");
4905 
4906     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4907                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4908     Chain = Val.getValue(1);
4909     InFlag = Val.getValue(2);
4910 
4911     switch (VA.getLocInfo()) {
4912     default: llvm_unreachable("Unknown loc info!");
4913     case CCValAssign::Full: break;
4914     case CCValAssign::AExt:
4915       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4916       break;
4917     case CCValAssign::ZExt:
4918       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4919                         DAG.getValueType(VA.getValVT()));
4920       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4921       break;
4922     case CCValAssign::SExt:
4923       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4924                         DAG.getValueType(VA.getValVT()));
4925       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4926       break;
4927     }
4928 
4929     InVals.push_back(Val);
4930   }
4931 
4932   return Chain;
4933 }
4934 
4935 SDValue PPCTargetLowering::FinishCall(
4936     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4937     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4938     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4939     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4940     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4941     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
4942   std::vector<EVT> NodeTys;
4943   SmallVector<SDValue, 8> Ops;
4944   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4945                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4946                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4947 
4948   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4949   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4950     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4951 
4952   // When performing tail call optimization the callee pops its arguments off
4953   // the stack. Account for this here so these bytes can be pushed back on in
4954   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4955   int BytesCalleePops =
4956     (CallConv == CallingConv::Fast &&
4957      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4958 
4959   // Add a register mask operand representing the call-preserved registers.
4960   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4961   const uint32_t *Mask =
4962       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4963   assert(Mask && "Missing call preserved mask for calling convention");
4964   Ops.push_back(DAG.getRegisterMask(Mask));
4965 
4966   if (InFlag.getNode())
4967     Ops.push_back(InFlag);
4968 
4969   // Emit tail call.
4970   if (isTailCall) {
4971     assert(((Callee.getOpcode() == ISD::Register &&
4972              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4973             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4974             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4975             isa<ConstantSDNode>(Callee)) &&
4976     "Expecting an global address, external symbol, absolute value or register");
4977 
4978     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4979     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4980   }
4981 
4982   // Add a NOP immediately after the branch instruction when using the 64-bit
4983   // SVR4 ABI. At link time, if caller and callee are in a different module and
4984   // thus have a different TOC, the call will be replaced with a call to a stub
4985   // function which saves the current TOC, loads the TOC of the callee and
4986   // branches to the callee. The NOP will be replaced with a load instruction
4987   // which restores the TOC of the caller from the TOC save slot of the current
4988   // stack frame. If caller and callee belong to the same module (and have the
4989   // same TOC), the NOP will remain unchanged.
4990 
4991   MachineFunction &MF = DAG.getMachineFunction();
4992   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4993       !isPatchPoint) {
4994     if (CallOpc == PPCISD::BCTRL) {
4995       // This is a call through a function pointer.
4996       // Restore the caller TOC from the save area into R2.
4997       // See PrepareCall() for more information about calls through function
4998       // pointers in the 64-bit SVR4 ABI.
4999       // We are using a target-specific load with r2 hard coded, because the
5000       // result of a target-independent load would never go directly into r2,
5001       // since r2 is a reserved register (which prevents the register allocator
5002       // from allocating it), resulting in an additional register being
5003       // allocated and an unnecessary move instruction being generated.
5004       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5005 
5006       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5007       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5008       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5009       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5010       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5011 
5012       // The address needs to go after the chain input but before the flag (or
5013       // any other variadic arguments).
5014       Ops.insert(std::next(Ops.begin()), AddTOC);
5015     } else if (CallOpc == PPCISD::CALL &&
5016       !callsShareTOCBase(MF.getFunction(), Callee, DAG.getTarget())) {
5017       // Otherwise insert NOP for non-local calls.
5018       CallOpc = PPCISD::CALL_NOP;
5019     }
5020   }
5021 
5022   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5023   InFlag = Chain.getValue(1);
5024 
5025   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5026                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5027                              InFlag, dl);
5028   if (!Ins.empty())
5029     InFlag = Chain.getValue(1);
5030 
5031   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5032                          Ins, dl, DAG, InVals);
5033 }
5034 
5035 SDValue
5036 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5037                              SmallVectorImpl<SDValue> &InVals) const {
5038   SelectionDAG &DAG                     = CLI.DAG;
5039   SDLoc &dl                             = CLI.DL;
5040   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5041   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5042   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5043   SDValue Chain                         = CLI.Chain;
5044   SDValue Callee                        = CLI.Callee;
5045   bool &isTailCall                      = CLI.IsTailCall;
5046   CallingConv::ID CallConv              = CLI.CallConv;
5047   bool isVarArg                         = CLI.IsVarArg;
5048   bool isPatchPoint                     = CLI.IsPatchPoint;
5049   ImmutableCallSite CS                  = CLI.CS;
5050 
5051   if (isTailCall) {
5052     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5053       isTailCall = false;
5054     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5055       isTailCall =
5056         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5057                                                  isVarArg, Outs, Ins, DAG);
5058     else
5059       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5060                                                      Ins, DAG);
5061     if (isTailCall) {
5062       ++NumTailCalls;
5063       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5064         ++NumSiblingCalls;
5065 
5066       assert(isa<GlobalAddressSDNode>(Callee) &&
5067              "Callee should be an llvm::Function object.");
5068       DEBUG(
5069         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5070         const unsigned Width = 80 - strlen("TCO caller: ")
5071                                   - strlen(", callee linkage: 0, 0");
5072         dbgs() << "TCO caller: "
5073                << left_justify(DAG.getMachineFunction().getName(), Width)
5074                << ", callee linkage: "
5075                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
5076       );
5077     }
5078   }
5079 
5080   if (!isTailCall && CS && CS.isMustTailCall())
5081     report_fatal_error("failed to perform tail call elimination on a call "
5082                        "site marked musttail");
5083 
5084   // When long calls (i.e. indirect calls) are always used, calls are always
5085   // made via function pointer. If we have a function name, first translate it
5086   // into a pointer.
5087   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5088       !isTailCall)
5089     Callee = LowerGlobalAddress(Callee, DAG);
5090 
5091   if (Subtarget.isSVR4ABI()) {
5092     if (Subtarget.isPPC64())
5093       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5094                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5095                               dl, DAG, InVals, CS);
5096     else
5097       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5098                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5099                               dl, DAG, InVals, CS);
5100   }
5101 
5102   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5103                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5104                           dl, DAG, InVals, CS);
5105 }
5106 
5107 SDValue PPCTargetLowering::LowerCall_32SVR4(
5108     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5109     bool isTailCall, bool isPatchPoint,
5110     const SmallVectorImpl<ISD::OutputArg> &Outs,
5111     const SmallVectorImpl<SDValue> &OutVals,
5112     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5113     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5114     ImmutableCallSite CS) const {
5115   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5116   // of the 32-bit SVR4 ABI stack frame layout.
5117 
5118   assert((CallConv == CallingConv::C ||
5119           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5120 
5121   unsigned PtrByteSize = 4;
5122 
5123   MachineFunction &MF = DAG.getMachineFunction();
5124 
5125   // Mark this function as potentially containing a function that contains a
5126   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5127   // and restoring the callers stack pointer in this functions epilog. This is
5128   // done because by tail calling the called function might overwrite the value
5129   // in this function's (MF) stack pointer stack slot 0(SP).
5130   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5131       CallConv == CallingConv::Fast)
5132     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5133 
5134   // Count how many bytes are to be pushed on the stack, including the linkage
5135   // area, parameter list area and the part of the local variable space which
5136   // contains copies of aggregates which are passed by value.
5137 
5138   // Assign locations to all of the outgoing arguments.
5139   SmallVector<CCValAssign, 16> ArgLocs;
5140   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5141 
5142   // Reserve space for the linkage area on the stack.
5143   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5144                        PtrByteSize);
5145   if (useSoftFloat())
5146     CCInfo.PreAnalyzeCallOperands(Outs);
5147 
5148   if (isVarArg) {
5149     // Handle fixed and variable vector arguments differently.
5150     // Fixed vector arguments go into registers as long as registers are
5151     // available. Variable vector arguments always go into memory.
5152     unsigned NumArgs = Outs.size();
5153 
5154     for (unsigned i = 0; i != NumArgs; ++i) {
5155       MVT ArgVT = Outs[i].VT;
5156       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5157       bool Result;
5158 
5159       if (Outs[i].IsFixed) {
5160         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5161                                CCInfo);
5162       } else {
5163         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5164                                       ArgFlags, CCInfo);
5165       }
5166 
5167       if (Result) {
5168 #ifndef NDEBUG
5169         errs() << "Call operand #" << i << " has unhandled type "
5170              << EVT(ArgVT).getEVTString() << "\n";
5171 #endif
5172         llvm_unreachable(nullptr);
5173       }
5174     }
5175   } else {
5176     // All arguments are treated the same.
5177     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5178   }
5179   CCInfo.clearWasPPCF128();
5180 
5181   // Assign locations to all of the outgoing aggregate by value arguments.
5182   SmallVector<CCValAssign, 16> ByValArgLocs;
5183   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5184 
5185   // Reserve stack space for the allocations in CCInfo.
5186   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5187 
5188   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5189 
5190   // Size of the linkage area, parameter list area and the part of the local
5191   // space variable where copies of aggregates which are passed by value are
5192   // stored.
5193   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5194 
5195   // Calculate by how many bytes the stack has to be adjusted in case of tail
5196   // call optimization.
5197   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5198 
5199   // Adjust the stack pointer for the new arguments...
5200   // These operations are automatically eliminated by the prolog/epilog pass
5201   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5202   SDValue CallSeqStart = Chain;
5203 
5204   // Load the return address and frame pointer so it can be moved somewhere else
5205   // later.
5206   SDValue LROp, FPOp;
5207   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5208 
5209   // Set up a copy of the stack pointer for use loading and storing any
5210   // arguments that may not fit in the registers available for argument
5211   // passing.
5212   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5213 
5214   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5215   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5216   SmallVector<SDValue, 8> MemOpChains;
5217 
5218   bool seenFloatArg = false;
5219   // Walk the register/memloc assignments, inserting copies/loads.
5220   for (unsigned i = 0, j = 0, e = ArgLocs.size();
5221        i != e;
5222        ++i) {
5223     CCValAssign &VA = ArgLocs[i];
5224     SDValue Arg = OutVals[i];
5225     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5226 
5227     if (Flags.isByVal()) {
5228       // Argument is an aggregate which is passed by value, thus we need to
5229       // create a copy of it in the local variable space of the current stack
5230       // frame (which is the stack frame of the caller) and pass the address of
5231       // this copy to the callee.
5232       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5233       CCValAssign &ByValVA = ByValArgLocs[j++];
5234       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5235 
5236       // Memory reserved in the local variable space of the callers stack frame.
5237       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5238 
5239       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5240       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5241                            StackPtr, PtrOff);
5242 
5243       // Create a copy of the argument in the local area of the current
5244       // stack frame.
5245       SDValue MemcpyCall =
5246         CreateCopyOfByValArgument(Arg, PtrOff,
5247                                   CallSeqStart.getNode()->getOperand(0),
5248                                   Flags, DAG, dl);
5249 
5250       // This must go outside the CALLSEQ_START..END.
5251       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5252                                                      SDLoc(MemcpyCall));
5253       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5254                              NewCallSeqStart.getNode());
5255       Chain = CallSeqStart = NewCallSeqStart;
5256 
5257       // Pass the address of the aggregate copy on the stack either in a
5258       // physical register or in the parameter list area of the current stack
5259       // frame to the callee.
5260       Arg = PtrOff;
5261     }
5262 
5263     if (VA.isRegLoc()) {
5264       if (Arg.getValueType() == MVT::i1)
5265         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5266 
5267       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5268       // Put argument in a physical register.
5269       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5270     } else {
5271       // Put argument in the parameter list area of the current stack frame.
5272       assert(VA.isMemLoc());
5273       unsigned LocMemOffset = VA.getLocMemOffset();
5274 
5275       if (!isTailCall) {
5276         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5277         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5278                              StackPtr, PtrOff);
5279 
5280         MemOpChains.push_back(
5281             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5282       } else {
5283         // Calculate and remember argument location.
5284         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5285                                  TailCallArguments);
5286       }
5287     }
5288   }
5289 
5290   if (!MemOpChains.empty())
5291     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5292 
5293   // Build a sequence of copy-to-reg nodes chained together with token chain
5294   // and flag operands which copy the outgoing args into the appropriate regs.
5295   SDValue InFlag;
5296   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5297     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5298                              RegsToPass[i].second, InFlag);
5299     InFlag = Chain.getValue(1);
5300   }
5301 
5302   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5303   // registers.
5304   if (isVarArg) {
5305     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5306     SDValue Ops[] = { Chain, InFlag };
5307 
5308     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5309                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5310 
5311     InFlag = Chain.getValue(1);
5312   }
5313 
5314   if (isTailCall)
5315     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5316                     TailCallArguments);
5317 
5318   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5319                     /* unused except on PPC64 ELFv1 */ false, DAG,
5320                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5321                     NumBytes, Ins, InVals, CS);
5322 }
5323 
5324 // Copy an argument into memory, being careful to do this outside the
5325 // call sequence for the call to which the argument belongs.
5326 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5327     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5328     SelectionDAG &DAG, const SDLoc &dl) const {
5329   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5330                         CallSeqStart.getNode()->getOperand(0),
5331                         Flags, DAG, dl);
5332   // The MEMCPY must go outside the CALLSEQ_START..END.
5333   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5334   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5335                                                  SDLoc(MemcpyCall));
5336   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5337                          NewCallSeqStart.getNode());
5338   return NewCallSeqStart;
5339 }
5340 
5341 SDValue PPCTargetLowering::LowerCall_64SVR4(
5342     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5343     bool isTailCall, bool isPatchPoint,
5344     const SmallVectorImpl<ISD::OutputArg> &Outs,
5345     const SmallVectorImpl<SDValue> &OutVals,
5346     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5347     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5348     ImmutableCallSite CS) const {
5349   bool isELFv2ABI = Subtarget.isELFv2ABI();
5350   bool isLittleEndian = Subtarget.isLittleEndian();
5351   unsigned NumOps = Outs.size();
5352   bool hasNest = false;
5353   bool IsSibCall = false;
5354 
5355   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5356   unsigned PtrByteSize = 8;
5357 
5358   MachineFunction &MF = DAG.getMachineFunction();
5359 
5360   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5361     IsSibCall = true;
5362 
5363   // Mark this function as potentially containing a function that contains a
5364   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5365   // and restoring the callers stack pointer in this functions epilog. This is
5366   // done because by tail calling the called function might overwrite the value
5367   // in this function's (MF) stack pointer stack slot 0(SP).
5368   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5369       CallConv == CallingConv::Fast)
5370     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5371 
5372   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5373          "fastcc not supported on varargs functions");
5374 
5375   // Count how many bytes are to be pushed on the stack, including the linkage
5376   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5377   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5378   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5379   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5380   unsigned NumBytes = LinkageSize;
5381   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5382   unsigned &QFPR_idx = FPR_idx;
5383 
5384   static const MCPhysReg GPR[] = {
5385     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5386     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5387   };
5388   static const MCPhysReg VR[] = {
5389     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5390     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5391   };
5392 
5393   const unsigned NumGPRs = array_lengthof(GPR);
5394   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5395   const unsigned NumVRs  = array_lengthof(VR);
5396   const unsigned NumQFPRs = NumFPRs;
5397 
5398   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5399   // can be passed to the callee in registers.
5400   // For the fast calling convention, there is another check below.
5401   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5402   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5403   if (!HasParameterArea) {
5404     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5405     unsigned AvailableFPRs = NumFPRs;
5406     unsigned AvailableVRs = NumVRs;
5407     unsigned NumBytesTmp = NumBytes;
5408     for (unsigned i = 0; i != NumOps; ++i) {
5409       if (Outs[i].Flags.isNest()) continue;
5410       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5411                                 PtrByteSize, LinkageSize, ParamAreaSize,
5412                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5413                                 Subtarget.hasQPX()))
5414         HasParameterArea = true;
5415     }
5416   }
5417 
5418   // When using the fast calling convention, we don't provide backing for
5419   // arguments that will be in registers.
5420   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5421 
5422   // Add up all the space actually used.
5423   for (unsigned i = 0; i != NumOps; ++i) {
5424     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5425     EVT ArgVT = Outs[i].VT;
5426     EVT OrigVT = Outs[i].ArgVT;
5427 
5428     if (Flags.isNest())
5429       continue;
5430 
5431     if (CallConv == CallingConv::Fast) {
5432       if (Flags.isByVal())
5433         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5434       else
5435         switch (ArgVT.getSimpleVT().SimpleTy) {
5436         default: llvm_unreachable("Unexpected ValueType for argument!");
5437         case MVT::i1:
5438         case MVT::i32:
5439         case MVT::i64:
5440           if (++NumGPRsUsed <= NumGPRs)
5441             continue;
5442           break;
5443         case MVT::v4i32:
5444         case MVT::v8i16:
5445         case MVT::v16i8:
5446         case MVT::v2f64:
5447         case MVT::v2i64:
5448         case MVT::v1i128:
5449           if (++NumVRsUsed <= NumVRs)
5450             continue;
5451           break;
5452         case MVT::v4f32:
5453           // When using QPX, this is handled like a FP register, otherwise, it
5454           // is an Altivec register.
5455           if (Subtarget.hasQPX()) {
5456             if (++NumFPRsUsed <= NumFPRs)
5457               continue;
5458           } else {
5459             if (++NumVRsUsed <= NumVRs)
5460               continue;
5461           }
5462           break;
5463         case MVT::f32:
5464         case MVT::f64:
5465         case MVT::v4f64: // QPX
5466         case MVT::v4i1:  // QPX
5467           if (++NumFPRsUsed <= NumFPRs)
5468             continue;
5469           break;
5470         }
5471     }
5472 
5473     /* Respect alignment of argument on the stack.  */
5474     unsigned Align =
5475       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5476     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5477 
5478     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5479     if (Flags.isInConsecutiveRegsLast())
5480       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5481   }
5482 
5483   unsigned NumBytesActuallyUsed = NumBytes;
5484 
5485   // In the old ELFv1 ABI,
5486   // the prolog code of the callee may store up to 8 GPR argument registers to
5487   // the stack, allowing va_start to index over them in memory if its varargs.
5488   // Because we cannot tell if this is needed on the caller side, we have to
5489   // conservatively assume that it is needed.  As such, make sure we have at
5490   // least enough stack space for the caller to store the 8 GPRs.
5491   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5492   // really requires memory operands, e.g. a vararg function.
5493   if (HasParameterArea)
5494     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5495   else
5496     NumBytes = LinkageSize;
5497 
5498   // Tail call needs the stack to be aligned.
5499   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5500       CallConv == CallingConv::Fast)
5501     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5502 
5503   int SPDiff = 0;
5504 
5505   // Calculate by how many bytes the stack has to be adjusted in case of tail
5506   // call optimization.
5507   if (!IsSibCall)
5508     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5509 
5510   // To protect arguments on the stack from being clobbered in a tail call,
5511   // force all the loads to happen before doing any other lowering.
5512   if (isTailCall)
5513     Chain = DAG.getStackArgumentTokenFactor(Chain);
5514 
5515   // Adjust the stack pointer for the new arguments...
5516   // These operations are automatically eliminated by the prolog/epilog pass
5517   if (!IsSibCall)
5518     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5519   SDValue CallSeqStart = Chain;
5520 
5521   // Load the return address and frame pointer so it can be move somewhere else
5522   // later.
5523   SDValue LROp, FPOp;
5524   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5525 
5526   // Set up a copy of the stack pointer for use loading and storing any
5527   // arguments that may not fit in the registers available for argument
5528   // passing.
5529   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5530 
5531   // Figure out which arguments are going to go in registers, and which in
5532   // memory.  Also, if this is a vararg function, floating point operations
5533   // must be stored to our stack, and loaded into integer regs as well, if
5534   // any integer regs are available for argument passing.
5535   unsigned ArgOffset = LinkageSize;
5536 
5537   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5538   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5539 
5540   SmallVector<SDValue, 8> MemOpChains;
5541   for (unsigned i = 0; i != NumOps; ++i) {
5542     SDValue Arg = OutVals[i];
5543     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5544     EVT ArgVT = Outs[i].VT;
5545     EVT OrigVT = Outs[i].ArgVT;
5546 
5547     // PtrOff will be used to store the current argument to the stack if a
5548     // register cannot be found for it.
5549     SDValue PtrOff;
5550 
5551     // We re-align the argument offset for each argument, except when using the
5552     // fast calling convention, when we need to make sure we do that only when
5553     // we'll actually use a stack slot.
5554     auto ComputePtrOff = [&]() {
5555       /* Respect alignment of argument on the stack.  */
5556       unsigned Align =
5557         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5558       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5559 
5560       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5561 
5562       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5563     };
5564 
5565     if (CallConv != CallingConv::Fast) {
5566       ComputePtrOff();
5567 
5568       /* Compute GPR index associated with argument offset.  */
5569       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5570       GPR_idx = std::min(GPR_idx, NumGPRs);
5571     }
5572 
5573     // Promote integers to 64-bit values.
5574     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5575       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5576       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5577       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5578     }
5579 
5580     // FIXME memcpy is used way more than necessary.  Correctness first.
5581     // Note: "by value" is code for passing a structure by value, not
5582     // basic types.
5583     if (Flags.isByVal()) {
5584       // Note: Size includes alignment padding, so
5585       //   struct x { short a; char b; }
5586       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5587       // These are the proper values we need for right-justifying the
5588       // aggregate in a parameter register.
5589       unsigned Size = Flags.getByValSize();
5590 
5591       // An empty aggregate parameter takes up no storage and no
5592       // registers.
5593       if (Size == 0)
5594         continue;
5595 
5596       if (CallConv == CallingConv::Fast)
5597         ComputePtrOff();
5598 
5599       // All aggregates smaller than 8 bytes must be passed right-justified.
5600       if (Size==1 || Size==2 || Size==4) {
5601         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5602         if (GPR_idx != NumGPRs) {
5603           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5604                                         MachinePointerInfo(), VT);
5605           MemOpChains.push_back(Load.getValue(1));
5606           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5607 
5608           ArgOffset += PtrByteSize;
5609           continue;
5610         }
5611       }
5612 
5613       if (GPR_idx == NumGPRs && Size < 8) {
5614         SDValue AddPtr = PtrOff;
5615         if (!isLittleEndian) {
5616           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5617                                           PtrOff.getValueType());
5618           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5619         }
5620         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5621                                                           CallSeqStart,
5622                                                           Flags, DAG, dl);
5623         ArgOffset += PtrByteSize;
5624         continue;
5625       }
5626       // Copy entire object into memory.  There are cases where gcc-generated
5627       // code assumes it is there, even if it could be put entirely into
5628       // registers.  (This is not what the doc says.)
5629 
5630       // FIXME: The above statement is likely due to a misunderstanding of the
5631       // documents.  All arguments must be copied into the parameter area BY
5632       // THE CALLEE in the event that the callee takes the address of any
5633       // formal argument.  That has not yet been implemented.  However, it is
5634       // reasonable to use the stack area as a staging area for the register
5635       // load.
5636 
5637       // Skip this for small aggregates, as we will use the same slot for a
5638       // right-justified copy, below.
5639       if (Size >= 8)
5640         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5641                                                           CallSeqStart,
5642                                                           Flags, DAG, dl);
5643 
5644       // When a register is available, pass a small aggregate right-justified.
5645       if (Size < 8 && GPR_idx != NumGPRs) {
5646         // The easiest way to get this right-justified in a register
5647         // is to copy the structure into the rightmost portion of a
5648         // local variable slot, then load the whole slot into the
5649         // register.
5650         // FIXME: The memcpy seems to produce pretty awful code for
5651         // small aggregates, particularly for packed ones.
5652         // FIXME: It would be preferable to use the slot in the
5653         // parameter save area instead of a new local variable.
5654         SDValue AddPtr = PtrOff;
5655         if (!isLittleEndian) {
5656           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5657           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5658         }
5659         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5660                                                           CallSeqStart,
5661                                                           Flags, DAG, dl);
5662 
5663         // Load the slot into the register.
5664         SDValue Load =
5665             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5666         MemOpChains.push_back(Load.getValue(1));
5667         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5668 
5669         // Done with this argument.
5670         ArgOffset += PtrByteSize;
5671         continue;
5672       }
5673 
5674       // For aggregates larger than PtrByteSize, copy the pieces of the
5675       // object that fit into registers from the parameter save area.
5676       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5677         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5678         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5679         if (GPR_idx != NumGPRs) {
5680           SDValue Load =
5681               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5682           MemOpChains.push_back(Load.getValue(1));
5683           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5684           ArgOffset += PtrByteSize;
5685         } else {
5686           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5687           break;
5688         }
5689       }
5690       continue;
5691     }
5692 
5693     switch (Arg.getSimpleValueType().SimpleTy) {
5694     default: llvm_unreachable("Unexpected ValueType for argument!");
5695     case MVT::i1:
5696     case MVT::i32:
5697     case MVT::i64:
5698       if (Flags.isNest()) {
5699         // The 'nest' parameter, if any, is passed in R11.
5700         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5701         hasNest = true;
5702         break;
5703       }
5704 
5705       // These can be scalar arguments or elements of an integer array type
5706       // passed directly.  Clang may use those instead of "byval" aggregate
5707       // types to avoid forcing arguments to memory unnecessarily.
5708       if (GPR_idx != NumGPRs) {
5709         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5710       } else {
5711         if (CallConv == CallingConv::Fast)
5712           ComputePtrOff();
5713 
5714         assert(HasParameterArea &&
5715                "Parameter area must exist to pass an argument in memory.");
5716         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5717                          true, isTailCall, false, MemOpChains,
5718                          TailCallArguments, dl);
5719         if (CallConv == CallingConv::Fast)
5720           ArgOffset += PtrByteSize;
5721       }
5722       if (CallConv != CallingConv::Fast)
5723         ArgOffset += PtrByteSize;
5724       break;
5725     case MVT::f32:
5726     case MVT::f64: {
5727       // These can be scalar arguments or elements of a float array type
5728       // passed directly.  The latter are used to implement ELFv2 homogenous
5729       // float aggregates.
5730 
5731       // Named arguments go into FPRs first, and once they overflow, the
5732       // remaining arguments go into GPRs and then the parameter save area.
5733       // Unnamed arguments for vararg functions always go to GPRs and
5734       // then the parameter save area.  For now, put all arguments to vararg
5735       // routines always in both locations (FPR *and* GPR or stack slot).
5736       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5737       bool NeededLoad = false;
5738 
5739       // First load the argument into the next available FPR.
5740       if (FPR_idx != NumFPRs)
5741         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5742 
5743       // Next, load the argument into GPR or stack slot if needed.
5744       if (!NeedGPROrStack)
5745         ;
5746       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5747         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5748         // once we support fp <-> gpr moves.
5749 
5750         // In the non-vararg case, this can only ever happen in the
5751         // presence of f32 array types, since otherwise we never run
5752         // out of FPRs before running out of GPRs.
5753         SDValue ArgVal;
5754 
5755         // Double values are always passed in a single GPR.
5756         if (Arg.getValueType() != MVT::f32) {
5757           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5758 
5759         // Non-array float values are extended and passed in a GPR.
5760         } else if (!Flags.isInConsecutiveRegs()) {
5761           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5762           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5763 
5764         // If we have an array of floats, we collect every odd element
5765         // together with its predecessor into one GPR.
5766         } else if (ArgOffset % PtrByteSize != 0) {
5767           SDValue Lo, Hi;
5768           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5769           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5770           if (!isLittleEndian)
5771             std::swap(Lo, Hi);
5772           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5773 
5774         // The final element, if even, goes into the first half of a GPR.
5775         } else if (Flags.isInConsecutiveRegsLast()) {
5776           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5777           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5778           if (!isLittleEndian)
5779             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5780                                  DAG.getConstant(32, dl, MVT::i32));
5781 
5782         // Non-final even elements are skipped; they will be handled
5783         // together the with subsequent argument on the next go-around.
5784         } else
5785           ArgVal = SDValue();
5786 
5787         if (ArgVal.getNode())
5788           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5789       } else {
5790         if (CallConv == CallingConv::Fast)
5791           ComputePtrOff();
5792 
5793         // Single-precision floating-point values are mapped to the
5794         // second (rightmost) word of the stack doubleword.
5795         if (Arg.getValueType() == MVT::f32 &&
5796             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5797           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5798           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5799         }
5800 
5801         assert(HasParameterArea &&
5802                "Parameter area must exist to pass an argument in memory.");
5803         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5804                          true, isTailCall, false, MemOpChains,
5805                          TailCallArguments, dl);
5806 
5807         NeededLoad = true;
5808       }
5809       // When passing an array of floats, the array occupies consecutive
5810       // space in the argument area; only round up to the next doubleword
5811       // at the end of the array.  Otherwise, each float takes 8 bytes.
5812       if (CallConv != CallingConv::Fast || NeededLoad) {
5813         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5814                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5815         if (Flags.isInConsecutiveRegsLast())
5816           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5817       }
5818       break;
5819     }
5820     case MVT::v4f32:
5821     case MVT::v4i32:
5822     case MVT::v8i16:
5823     case MVT::v16i8:
5824     case MVT::v2f64:
5825     case MVT::v2i64:
5826     case MVT::v1i128:
5827       if (!Subtarget.hasQPX()) {
5828       // These can be scalar arguments or elements of a vector array type
5829       // passed directly.  The latter are used to implement ELFv2 homogenous
5830       // vector aggregates.
5831 
5832       // For a varargs call, named arguments go into VRs or on the stack as
5833       // usual; unnamed arguments always go to the stack or the corresponding
5834       // GPRs when within range.  For now, we always put the value in both
5835       // locations (or even all three).
5836       if (isVarArg) {
5837         assert(HasParameterArea &&
5838                "Parameter area must exist if we have a varargs call.");
5839         // We could elide this store in the case where the object fits
5840         // entirely in R registers.  Maybe later.
5841         SDValue Store =
5842             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5843         MemOpChains.push_back(Store);
5844         if (VR_idx != NumVRs) {
5845           SDValue Load =
5846               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5847           MemOpChains.push_back(Load.getValue(1));
5848           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5849         }
5850         ArgOffset += 16;
5851         for (unsigned i=0; i<16; i+=PtrByteSize) {
5852           if (GPR_idx == NumGPRs)
5853             break;
5854           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5855                                    DAG.getConstant(i, dl, PtrVT));
5856           SDValue Load =
5857               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5858           MemOpChains.push_back(Load.getValue(1));
5859           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5860         }
5861         break;
5862       }
5863 
5864       // Non-varargs Altivec params go into VRs or on the stack.
5865       if (VR_idx != NumVRs) {
5866         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5867       } else {
5868         if (CallConv == CallingConv::Fast)
5869           ComputePtrOff();
5870 
5871         assert(HasParameterArea &&
5872                "Parameter area must exist to pass an argument in memory.");
5873         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5874                          true, isTailCall, true, MemOpChains,
5875                          TailCallArguments, dl);
5876         if (CallConv == CallingConv::Fast)
5877           ArgOffset += 16;
5878       }
5879 
5880       if (CallConv != CallingConv::Fast)
5881         ArgOffset += 16;
5882       break;
5883       } // not QPX
5884 
5885       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5886              "Invalid QPX parameter type");
5887 
5888       /* fall through */
5889     case MVT::v4f64:
5890     case MVT::v4i1: {
5891       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5892       if (isVarArg) {
5893         assert(HasParameterArea &&
5894                "Parameter area must exist if we have a varargs call.");
5895         // We could elide this store in the case where the object fits
5896         // entirely in R registers.  Maybe later.
5897         SDValue Store =
5898             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5899         MemOpChains.push_back(Store);
5900         if (QFPR_idx != NumQFPRs) {
5901           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5902                                      PtrOff, MachinePointerInfo());
5903           MemOpChains.push_back(Load.getValue(1));
5904           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5905         }
5906         ArgOffset += (IsF32 ? 16 : 32);
5907         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5908           if (GPR_idx == NumGPRs)
5909             break;
5910           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5911                                    DAG.getConstant(i, dl, PtrVT));
5912           SDValue Load =
5913               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5914           MemOpChains.push_back(Load.getValue(1));
5915           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5916         }
5917         break;
5918       }
5919 
5920       // Non-varargs QPX params go into registers or on the stack.
5921       if (QFPR_idx != NumQFPRs) {
5922         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5923       } else {
5924         if (CallConv == CallingConv::Fast)
5925           ComputePtrOff();
5926 
5927         assert(HasParameterArea &&
5928                "Parameter area must exist to pass an argument in memory.");
5929         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5930                          true, isTailCall, true, MemOpChains,
5931                          TailCallArguments, dl);
5932         if (CallConv == CallingConv::Fast)
5933           ArgOffset += (IsF32 ? 16 : 32);
5934       }
5935 
5936       if (CallConv != CallingConv::Fast)
5937         ArgOffset += (IsF32 ? 16 : 32);
5938       break;
5939       }
5940     }
5941   }
5942 
5943   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5944          "mismatch in size of parameter area");
5945   (void)NumBytesActuallyUsed;
5946 
5947   if (!MemOpChains.empty())
5948     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5949 
5950   // Check if this is an indirect call (MTCTR/BCTRL).
5951   // See PrepareCall() for more information about calls through function
5952   // pointers in the 64-bit SVR4 ABI.
5953   if (!isTailCall && !isPatchPoint &&
5954       !isFunctionGlobalAddress(Callee) &&
5955       !isa<ExternalSymbolSDNode>(Callee)) {
5956     // Load r2 into a virtual register and store it to the TOC save area.
5957     setUsesTOCBasePtr(DAG);
5958     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5959     // TOC save area offset.
5960     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5961     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5962     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5963     Chain = DAG.getStore(
5964         Val.getValue(1), dl, Val, AddPtr,
5965         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5966     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5967     // This does not mean the MTCTR instruction must use R12; it's easier
5968     // to model this as an extra parameter, so do that.
5969     if (isELFv2ABI && !isPatchPoint)
5970       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5971   }
5972 
5973   // Build a sequence of copy-to-reg nodes chained together with token chain
5974   // and flag operands which copy the outgoing args into the appropriate regs.
5975   SDValue InFlag;
5976   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5977     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5978                              RegsToPass[i].second, InFlag);
5979     InFlag = Chain.getValue(1);
5980   }
5981 
5982   if (isTailCall && !IsSibCall)
5983     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5984                     TailCallArguments);
5985 
5986   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5987                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5988                     SPDiff, NumBytes, Ins, InVals, CS);
5989 }
5990 
5991 SDValue PPCTargetLowering::LowerCall_Darwin(
5992     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5993     bool isTailCall, bool isPatchPoint,
5994     const SmallVectorImpl<ISD::OutputArg> &Outs,
5995     const SmallVectorImpl<SDValue> &OutVals,
5996     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5997     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5998     ImmutableCallSite CS) const {
5999   unsigned NumOps = Outs.size();
6000 
6001   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6002   bool isPPC64 = PtrVT == MVT::i64;
6003   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6004 
6005   MachineFunction &MF = DAG.getMachineFunction();
6006 
6007   // Mark this function as potentially containing a function that contains a
6008   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6009   // and restoring the callers stack pointer in this functions epilog. This is
6010   // done because by tail calling the called function might overwrite the value
6011   // in this function's (MF) stack pointer stack slot 0(SP).
6012   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6013       CallConv == CallingConv::Fast)
6014     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6015 
6016   // Count how many bytes are to be pushed on the stack, including the linkage
6017   // area, and parameter passing area.  We start with 24/48 bytes, which is
6018   // prereserved space for [SP][CR][LR][3 x unused].
6019   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6020   unsigned NumBytes = LinkageSize;
6021 
6022   // Add up all the space actually used.
6023   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6024   // they all go in registers, but we must reserve stack space for them for
6025   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6026   // assigned stack space in order, with padding so Altivec parameters are
6027   // 16-byte aligned.
6028   unsigned nAltivecParamsAtEnd = 0;
6029   for (unsigned i = 0; i != NumOps; ++i) {
6030     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6031     EVT ArgVT = Outs[i].VT;
6032     // Varargs Altivec parameters are padded to a 16 byte boundary.
6033     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6034         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6035         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6036       if (!isVarArg && !isPPC64) {
6037         // Non-varargs Altivec parameters go after all the non-Altivec
6038         // parameters; handle those later so we know how much padding we need.
6039         nAltivecParamsAtEnd++;
6040         continue;
6041       }
6042       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6043       NumBytes = ((NumBytes+15)/16)*16;
6044     }
6045     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6046   }
6047 
6048   // Allow for Altivec parameters at the end, if needed.
6049   if (nAltivecParamsAtEnd) {
6050     NumBytes = ((NumBytes+15)/16)*16;
6051     NumBytes += 16*nAltivecParamsAtEnd;
6052   }
6053 
6054   // The prolog code of the callee may store up to 8 GPR argument registers to
6055   // the stack, allowing va_start to index over them in memory if its varargs.
6056   // Because we cannot tell if this is needed on the caller side, we have to
6057   // conservatively assume that it is needed.  As such, make sure we have at
6058   // least enough stack space for the caller to store the 8 GPRs.
6059   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6060 
6061   // Tail call needs the stack to be aligned.
6062   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6063       CallConv == CallingConv::Fast)
6064     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6065 
6066   // Calculate by how many bytes the stack has to be adjusted in case of tail
6067   // call optimization.
6068   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6069 
6070   // To protect arguments on the stack from being clobbered in a tail call,
6071   // force all the loads to happen before doing any other lowering.
6072   if (isTailCall)
6073     Chain = DAG.getStackArgumentTokenFactor(Chain);
6074 
6075   // Adjust the stack pointer for the new arguments...
6076   // These operations are automatically eliminated by the prolog/epilog pass
6077   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6078   SDValue CallSeqStart = Chain;
6079 
6080   // Load the return address and frame pointer so it can be move somewhere else
6081   // later.
6082   SDValue LROp, FPOp;
6083   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6084 
6085   // Set up a copy of the stack pointer for use loading and storing any
6086   // arguments that may not fit in the registers available for argument
6087   // passing.
6088   SDValue StackPtr;
6089   if (isPPC64)
6090     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6091   else
6092     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6093 
6094   // Figure out which arguments are going to go in registers, and which in
6095   // memory.  Also, if this is a vararg function, floating point operations
6096   // must be stored to our stack, and loaded into integer regs as well, if
6097   // any integer regs are available for argument passing.
6098   unsigned ArgOffset = LinkageSize;
6099   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6100 
6101   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6102     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6103     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6104   };
6105   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6106     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6107     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6108   };
6109   static const MCPhysReg VR[] = {
6110     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6111     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6112   };
6113   const unsigned NumGPRs = array_lengthof(GPR_32);
6114   const unsigned NumFPRs = 13;
6115   const unsigned NumVRs  = array_lengthof(VR);
6116 
6117   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6118 
6119   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6120   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6121 
6122   SmallVector<SDValue, 8> MemOpChains;
6123   for (unsigned i = 0; i != NumOps; ++i) {
6124     SDValue Arg = OutVals[i];
6125     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6126 
6127     // PtrOff will be used to store the current argument to the stack if a
6128     // register cannot be found for it.
6129     SDValue PtrOff;
6130 
6131     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6132 
6133     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6134 
6135     // On PPC64, promote integers to 64-bit values.
6136     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6137       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6138       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6139       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6140     }
6141 
6142     // FIXME memcpy is used way more than necessary.  Correctness first.
6143     // Note: "by value" is code for passing a structure by value, not
6144     // basic types.
6145     if (Flags.isByVal()) {
6146       unsigned Size = Flags.getByValSize();
6147       // Very small objects are passed right-justified.  Everything else is
6148       // passed left-justified.
6149       if (Size==1 || Size==2) {
6150         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6151         if (GPR_idx != NumGPRs) {
6152           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6153                                         MachinePointerInfo(), VT);
6154           MemOpChains.push_back(Load.getValue(1));
6155           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6156 
6157           ArgOffset += PtrByteSize;
6158         } else {
6159           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6160                                           PtrOff.getValueType());
6161           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6162           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6163                                                             CallSeqStart,
6164                                                             Flags, DAG, dl);
6165           ArgOffset += PtrByteSize;
6166         }
6167         continue;
6168       }
6169       // Copy entire object into memory.  There are cases where gcc-generated
6170       // code assumes it is there, even if it could be put entirely into
6171       // registers.  (This is not what the doc says.)
6172       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6173                                                         CallSeqStart,
6174                                                         Flags, DAG, dl);
6175 
6176       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6177       // copy the pieces of the object that fit into registers from the
6178       // parameter save area.
6179       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6180         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6181         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6182         if (GPR_idx != NumGPRs) {
6183           SDValue Load =
6184               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6185           MemOpChains.push_back(Load.getValue(1));
6186           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6187           ArgOffset += PtrByteSize;
6188         } else {
6189           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6190           break;
6191         }
6192       }
6193       continue;
6194     }
6195 
6196     switch (Arg.getSimpleValueType().SimpleTy) {
6197     default: llvm_unreachable("Unexpected ValueType for argument!");
6198     case MVT::i1:
6199     case MVT::i32:
6200     case MVT::i64:
6201       if (GPR_idx != NumGPRs) {
6202         if (Arg.getValueType() == MVT::i1)
6203           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6204 
6205         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6206       } else {
6207         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6208                          isPPC64, isTailCall, false, MemOpChains,
6209                          TailCallArguments, dl);
6210       }
6211       ArgOffset += PtrByteSize;
6212       break;
6213     case MVT::f32:
6214     case MVT::f64:
6215       if (FPR_idx != NumFPRs) {
6216         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6217 
6218         if (isVarArg) {
6219           SDValue Store =
6220               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6221           MemOpChains.push_back(Store);
6222 
6223           // Float varargs are always shadowed in available integer registers
6224           if (GPR_idx != NumGPRs) {
6225             SDValue Load =
6226                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6227             MemOpChains.push_back(Load.getValue(1));
6228             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6229           }
6230           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6231             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6232             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6233             SDValue Load =
6234                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6235             MemOpChains.push_back(Load.getValue(1));
6236             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6237           }
6238         } else {
6239           // If we have any FPRs remaining, we may also have GPRs remaining.
6240           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6241           // GPRs.
6242           if (GPR_idx != NumGPRs)
6243             ++GPR_idx;
6244           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6245               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6246             ++GPR_idx;
6247         }
6248       } else
6249         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6250                          isPPC64, isTailCall, false, MemOpChains,
6251                          TailCallArguments, dl);
6252       if (isPPC64)
6253         ArgOffset += 8;
6254       else
6255         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6256       break;
6257     case MVT::v4f32:
6258     case MVT::v4i32:
6259     case MVT::v8i16:
6260     case MVT::v16i8:
6261       if (isVarArg) {
6262         // These go aligned on the stack, or in the corresponding R registers
6263         // when within range.  The Darwin PPC ABI doc claims they also go in
6264         // V registers; in fact gcc does this only for arguments that are
6265         // prototyped, not for those that match the ...  We do it for all
6266         // arguments, seems to work.
6267         while (ArgOffset % 16 !=0) {
6268           ArgOffset += PtrByteSize;
6269           if (GPR_idx != NumGPRs)
6270             GPR_idx++;
6271         }
6272         // We could elide this store in the case where the object fits
6273         // entirely in R registers.  Maybe later.
6274         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6275                              DAG.getConstant(ArgOffset, dl, PtrVT));
6276         SDValue Store =
6277             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6278         MemOpChains.push_back(Store);
6279         if (VR_idx != NumVRs) {
6280           SDValue Load =
6281               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6282           MemOpChains.push_back(Load.getValue(1));
6283           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6284         }
6285         ArgOffset += 16;
6286         for (unsigned i=0; i<16; i+=PtrByteSize) {
6287           if (GPR_idx == NumGPRs)
6288             break;
6289           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6290                                    DAG.getConstant(i, dl, PtrVT));
6291           SDValue Load =
6292               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6293           MemOpChains.push_back(Load.getValue(1));
6294           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6295         }
6296         break;
6297       }
6298 
6299       // Non-varargs Altivec params generally go in registers, but have
6300       // stack space allocated at the end.
6301       if (VR_idx != NumVRs) {
6302         // Doesn't have GPR space allocated.
6303         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6304       } else if (nAltivecParamsAtEnd==0) {
6305         // We are emitting Altivec params in order.
6306         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6307                          isPPC64, isTailCall, true, MemOpChains,
6308                          TailCallArguments, dl);
6309         ArgOffset += 16;
6310       }
6311       break;
6312     }
6313   }
6314   // If all Altivec parameters fit in registers, as they usually do,
6315   // they get stack space following the non-Altivec parameters.  We
6316   // don't track this here because nobody below needs it.
6317   // If there are more Altivec parameters than fit in registers emit
6318   // the stores here.
6319   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6320     unsigned j = 0;
6321     // Offset is aligned; skip 1st 12 params which go in V registers.
6322     ArgOffset = ((ArgOffset+15)/16)*16;
6323     ArgOffset += 12*16;
6324     for (unsigned i = 0; i != NumOps; ++i) {
6325       SDValue Arg = OutVals[i];
6326       EVT ArgType = Outs[i].VT;
6327       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6328           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6329         if (++j > NumVRs) {
6330           SDValue PtrOff;
6331           // We are emitting Altivec params in order.
6332           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6333                            isPPC64, isTailCall, true, MemOpChains,
6334                            TailCallArguments, dl);
6335           ArgOffset += 16;
6336         }
6337       }
6338     }
6339   }
6340 
6341   if (!MemOpChains.empty())
6342     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6343 
6344   // On Darwin, R12 must contain the address of an indirect callee.  This does
6345   // not mean the MTCTR instruction must use R12; it's easier to model this as
6346   // an extra parameter, so do that.
6347   if (!isTailCall &&
6348       !isFunctionGlobalAddress(Callee) &&
6349       !isa<ExternalSymbolSDNode>(Callee) &&
6350       !isBLACompatibleAddress(Callee, DAG))
6351     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6352                                                    PPC::R12), Callee));
6353 
6354   // Build a sequence of copy-to-reg nodes chained together with token chain
6355   // and flag operands which copy the outgoing args into the appropriate regs.
6356   SDValue InFlag;
6357   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6358     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6359                              RegsToPass[i].second, InFlag);
6360     InFlag = Chain.getValue(1);
6361   }
6362 
6363   if (isTailCall)
6364     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6365                     TailCallArguments);
6366 
6367   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6368                     /* unused except on PPC64 ELFv1 */ false, DAG,
6369                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6370                     NumBytes, Ins, InVals, CS);
6371 }
6372 
6373 bool
6374 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6375                                   MachineFunction &MF, bool isVarArg,
6376                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6377                                   LLVMContext &Context) const {
6378   SmallVector<CCValAssign, 16> RVLocs;
6379   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6380   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6381 }
6382 
6383 SDValue
6384 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6385                                bool isVarArg,
6386                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6387                                const SmallVectorImpl<SDValue> &OutVals,
6388                                const SDLoc &dl, SelectionDAG &DAG) const {
6389   SmallVector<CCValAssign, 16> RVLocs;
6390   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6391                  *DAG.getContext());
6392   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6393 
6394   SDValue Flag;
6395   SmallVector<SDValue, 4> RetOps(1, Chain);
6396 
6397   // Copy the result values into the output registers.
6398   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6399     CCValAssign &VA = RVLocs[i];
6400     assert(VA.isRegLoc() && "Can only return in registers!");
6401 
6402     SDValue Arg = OutVals[i];
6403 
6404     switch (VA.getLocInfo()) {
6405     default: llvm_unreachable("Unknown loc info!");
6406     case CCValAssign::Full: break;
6407     case CCValAssign::AExt:
6408       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6409       break;
6410     case CCValAssign::ZExt:
6411       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6412       break;
6413     case CCValAssign::SExt:
6414       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6415       break;
6416     }
6417 
6418     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6419     Flag = Chain.getValue(1);
6420     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6421   }
6422 
6423   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6424   const MCPhysReg *I =
6425     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6426   if (I) {
6427     for (; *I; ++I) {
6428 
6429       if (PPC::G8RCRegClass.contains(*I))
6430         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6431       else if (PPC::F8RCRegClass.contains(*I))
6432         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6433       else if (PPC::CRRCRegClass.contains(*I))
6434         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6435       else if (PPC::VRRCRegClass.contains(*I))
6436         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6437       else
6438         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6439     }
6440   }
6441 
6442   RetOps[0] = Chain;  // Update chain.
6443 
6444   // Add the flag if we have it.
6445   if (Flag.getNode())
6446     RetOps.push_back(Flag);
6447 
6448   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6449 }
6450 
6451 SDValue
6452 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6453                                                 SelectionDAG &DAG) const {
6454   SDLoc dl(Op);
6455 
6456   // Get the correct type for integers.
6457   EVT IntVT = Op.getValueType();
6458 
6459   // Get the inputs.
6460   SDValue Chain = Op.getOperand(0);
6461   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6462   // Build a DYNAREAOFFSET node.
6463   SDValue Ops[2] = {Chain, FPSIdx};
6464   SDVTList VTs = DAG.getVTList(IntVT);
6465   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6466 }
6467 
6468 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6469                                              SelectionDAG &DAG) const {
6470   // When we pop the dynamic allocation we need to restore the SP link.
6471   SDLoc dl(Op);
6472 
6473   // Get the correct type for pointers.
6474   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6475 
6476   // Construct the stack pointer operand.
6477   bool isPPC64 = Subtarget.isPPC64();
6478   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6479   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6480 
6481   // Get the operands for the STACKRESTORE.
6482   SDValue Chain = Op.getOperand(0);
6483   SDValue SaveSP = Op.getOperand(1);
6484 
6485   // Load the old link SP.
6486   SDValue LoadLinkSP =
6487       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6488 
6489   // Restore the stack pointer.
6490   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6491 
6492   // Store the old link SP.
6493   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6494 }
6495 
6496 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6497   MachineFunction &MF = DAG.getMachineFunction();
6498   bool isPPC64 = Subtarget.isPPC64();
6499   EVT PtrVT = getPointerTy(MF.getDataLayout());
6500 
6501   // Get current frame pointer save index.  The users of this index will be
6502   // primarily DYNALLOC instructions.
6503   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6504   int RASI = FI->getReturnAddrSaveIndex();
6505 
6506   // If the frame pointer save index hasn't been defined yet.
6507   if (!RASI) {
6508     // Find out what the fix offset of the frame pointer save area.
6509     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6510     // Allocate the frame index for frame pointer save area.
6511     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6512     // Save the result.
6513     FI->setReturnAddrSaveIndex(RASI);
6514   }
6515   return DAG.getFrameIndex(RASI, PtrVT);
6516 }
6517 
6518 SDValue
6519 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6520   MachineFunction &MF = DAG.getMachineFunction();
6521   bool isPPC64 = Subtarget.isPPC64();
6522   EVT PtrVT = getPointerTy(MF.getDataLayout());
6523 
6524   // Get current frame pointer save index.  The users of this index will be
6525   // primarily DYNALLOC instructions.
6526   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6527   int FPSI = FI->getFramePointerSaveIndex();
6528 
6529   // If the frame pointer save index hasn't been defined yet.
6530   if (!FPSI) {
6531     // Find out what the fix offset of the frame pointer save area.
6532     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6533     // Allocate the frame index for frame pointer save area.
6534     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6535     // Save the result.
6536     FI->setFramePointerSaveIndex(FPSI);
6537   }
6538   return DAG.getFrameIndex(FPSI, PtrVT);
6539 }
6540 
6541 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6542                                                    SelectionDAG &DAG) const {
6543   // Get the inputs.
6544   SDValue Chain = Op.getOperand(0);
6545   SDValue Size  = Op.getOperand(1);
6546   SDLoc dl(Op);
6547 
6548   // Get the correct type for pointers.
6549   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6550   // Negate the size.
6551   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6552                                 DAG.getConstant(0, dl, PtrVT), Size);
6553   // Construct a node for the frame pointer save index.
6554   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6555   // Build a DYNALLOC node.
6556   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6557   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6558   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6559 }
6560 
6561 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6562                                                      SelectionDAG &DAG) const {
6563   MachineFunction &MF = DAG.getMachineFunction();
6564 
6565   bool isPPC64 = Subtarget.isPPC64();
6566   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6567 
6568   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6569   return DAG.getFrameIndex(FI, PtrVT);
6570 }
6571 
6572 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6573                                                SelectionDAG &DAG) const {
6574   SDLoc DL(Op);
6575   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6576                      DAG.getVTList(MVT::i32, MVT::Other),
6577                      Op.getOperand(0), Op.getOperand(1));
6578 }
6579 
6580 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6581                                                 SelectionDAG &DAG) const {
6582   SDLoc DL(Op);
6583   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6584                      Op.getOperand(0), Op.getOperand(1));
6585 }
6586 
6587 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6588   if (Op.getValueType().isVector())
6589     return LowerVectorLoad(Op, DAG);
6590 
6591   assert(Op.getValueType() == MVT::i1 &&
6592          "Custom lowering only for i1 loads");
6593 
6594   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6595 
6596   SDLoc dl(Op);
6597   LoadSDNode *LD = cast<LoadSDNode>(Op);
6598 
6599   SDValue Chain = LD->getChain();
6600   SDValue BasePtr = LD->getBasePtr();
6601   MachineMemOperand *MMO = LD->getMemOperand();
6602 
6603   SDValue NewLD =
6604       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6605                      BasePtr, MVT::i8, MMO);
6606   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6607 
6608   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6609   return DAG.getMergeValues(Ops, dl);
6610 }
6611 
6612 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6613   if (Op.getOperand(1).getValueType().isVector())
6614     return LowerVectorStore(Op, DAG);
6615 
6616   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6617          "Custom lowering only for i1 stores");
6618 
6619   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6620 
6621   SDLoc dl(Op);
6622   StoreSDNode *ST = cast<StoreSDNode>(Op);
6623 
6624   SDValue Chain = ST->getChain();
6625   SDValue BasePtr = ST->getBasePtr();
6626   SDValue Value = ST->getValue();
6627   MachineMemOperand *MMO = ST->getMemOperand();
6628 
6629   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6630                       Value);
6631   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6632 }
6633 
6634 // FIXME: Remove this once the ANDI glue bug is fixed:
6635 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6636   assert(Op.getValueType() == MVT::i1 &&
6637          "Custom lowering only for i1 results");
6638 
6639   SDLoc DL(Op);
6640   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6641                      Op.getOperand(0));
6642 }
6643 
6644 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6645 /// possible.
6646 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6647   // Not FP? Not a fsel.
6648   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6649       !Op.getOperand(2).getValueType().isFloatingPoint())
6650     return Op;
6651 
6652   // We might be able to do better than this under some circumstances, but in
6653   // general, fsel-based lowering of select is a finite-math-only optimization.
6654   // For more information, see section F.3 of the 2.06 ISA specification.
6655   if (!DAG.getTarget().Options.NoInfsFPMath ||
6656       !DAG.getTarget().Options.NoNaNsFPMath)
6657     return Op;
6658   // TODO: Propagate flags from the select rather than global settings.
6659   SDNodeFlags Flags;
6660   Flags.setNoInfs(true);
6661   Flags.setNoNaNs(true);
6662 
6663   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6664 
6665   EVT ResVT = Op.getValueType();
6666   EVT CmpVT = Op.getOperand(0).getValueType();
6667   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6668   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6669   SDLoc dl(Op);
6670 
6671   // If the RHS of the comparison is a 0.0, we don't need to do the
6672   // subtraction at all.
6673   SDValue Sel1;
6674   if (isFloatingPointZero(RHS))
6675     switch (CC) {
6676     default: break;       // SETUO etc aren't handled by fsel.
6677     case ISD::SETNE:
6678       std::swap(TV, FV);
6679       LLVM_FALLTHROUGH;
6680     case ISD::SETEQ:
6681       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6682         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6683       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6684       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6685         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6686       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6687                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6688     case ISD::SETULT:
6689     case ISD::SETLT:
6690       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6691       LLVM_FALLTHROUGH;
6692     case ISD::SETOGE:
6693     case ISD::SETGE:
6694       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6695         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6696       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6697     case ISD::SETUGT:
6698     case ISD::SETGT:
6699       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6700       LLVM_FALLTHROUGH;
6701     case ISD::SETOLE:
6702     case ISD::SETLE:
6703       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6704         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6705       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6706                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6707     }
6708 
6709   SDValue Cmp;
6710   switch (CC) {
6711   default: break;       // SETUO etc aren't handled by fsel.
6712   case ISD::SETNE:
6713     std::swap(TV, FV);
6714     LLVM_FALLTHROUGH;
6715   case ISD::SETEQ:
6716     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6717     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6718       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6719     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6720     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6721       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6722     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6723                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6724   case ISD::SETULT:
6725   case ISD::SETLT:
6726     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6727     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6728       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6729     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6730   case ISD::SETOGE:
6731   case ISD::SETGE:
6732     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6733     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6734       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6735     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6736   case ISD::SETUGT:
6737   case ISD::SETGT:
6738     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6739     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6740       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6741     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6742   case ISD::SETOLE:
6743   case ISD::SETLE:
6744     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6745     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6746       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6747     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6748   }
6749   return Op;
6750 }
6751 
6752 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6753                                                SelectionDAG &DAG,
6754                                                const SDLoc &dl) const {
6755   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6756   SDValue Src = Op.getOperand(0);
6757   if (Src.getValueType() == MVT::f32)
6758     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6759 
6760   SDValue Tmp;
6761   switch (Op.getSimpleValueType().SimpleTy) {
6762   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6763   case MVT::i32:
6764     Tmp = DAG.getNode(
6765         Op.getOpcode() == ISD::FP_TO_SINT
6766             ? PPCISD::FCTIWZ
6767             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6768         dl, MVT::f64, Src);
6769     break;
6770   case MVT::i64:
6771     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6772            "i64 FP_TO_UINT is supported only with FPCVT");
6773     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6774                                                         PPCISD::FCTIDUZ,
6775                       dl, MVT::f64, Src);
6776     break;
6777   }
6778 
6779   // Convert the FP value to an int value through memory.
6780   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6781     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6782   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6783   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6784   MachinePointerInfo MPI =
6785       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6786 
6787   // Emit a store to the stack slot.
6788   SDValue Chain;
6789   if (i32Stack) {
6790     MachineFunction &MF = DAG.getMachineFunction();
6791     MachineMemOperand *MMO =
6792       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6793     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6794     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6795               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6796   } else
6797     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6798 
6799   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6800   // add in a bias on big endian.
6801   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6802     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6803                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6804     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6805   }
6806 
6807   RLI.Chain = Chain;
6808   RLI.Ptr = FIPtr;
6809   RLI.MPI = MPI;
6810 }
6811 
6812 /// \brief Custom lowers floating point to integer conversions to use
6813 /// the direct move instructions available in ISA 2.07 to avoid the
6814 /// need for load/store combinations.
6815 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6816                                                     SelectionDAG &DAG,
6817                                                     const SDLoc &dl) const {
6818   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6819   SDValue Src = Op.getOperand(0);
6820 
6821   if (Src.getValueType() == MVT::f32)
6822     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6823 
6824   SDValue Tmp;
6825   switch (Op.getSimpleValueType().SimpleTy) {
6826   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6827   case MVT::i32:
6828     Tmp = DAG.getNode(
6829         Op.getOpcode() == ISD::FP_TO_SINT
6830             ? PPCISD::FCTIWZ
6831             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6832         dl, MVT::f64, Src);
6833     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6834     break;
6835   case MVT::i64:
6836     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6837            "i64 FP_TO_UINT is supported only with FPCVT");
6838     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6839                                                         PPCISD::FCTIDUZ,
6840                       dl, MVT::f64, Src);
6841     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6842     break;
6843   }
6844   return Tmp;
6845 }
6846 
6847 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6848                                           const SDLoc &dl) const {
6849   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6850     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6851 
6852   ReuseLoadInfo RLI;
6853   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6854 
6855   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6856                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6857 }
6858 
6859 // We're trying to insert a regular store, S, and then a load, L. If the
6860 // incoming value, O, is a load, we might just be able to have our load use the
6861 // address used by O. However, we don't know if anything else will store to
6862 // that address before we can load from it. To prevent this situation, we need
6863 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6864 // the same chain operand as O, we create a token factor from the chain results
6865 // of O and L, and we replace all uses of O's chain result with that token
6866 // factor (see spliceIntoChain below for this last part).
6867 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6868                                             ReuseLoadInfo &RLI,
6869                                             SelectionDAG &DAG,
6870                                             ISD::LoadExtType ET) const {
6871   SDLoc dl(Op);
6872   if (ET == ISD::NON_EXTLOAD &&
6873       (Op.getOpcode() == ISD::FP_TO_UINT ||
6874        Op.getOpcode() == ISD::FP_TO_SINT) &&
6875       isOperationLegalOrCustom(Op.getOpcode(),
6876                                Op.getOperand(0).getValueType())) {
6877 
6878     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6879     return true;
6880   }
6881 
6882   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6883   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6884       LD->isNonTemporal())
6885     return false;
6886   if (LD->getMemoryVT() != MemVT)
6887     return false;
6888 
6889   RLI.Ptr = LD->getBasePtr();
6890   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6891     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6892            "Non-pre-inc AM on PPC?");
6893     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6894                           LD->getOffset());
6895   }
6896 
6897   RLI.Chain = LD->getChain();
6898   RLI.MPI = LD->getPointerInfo();
6899   RLI.IsDereferenceable = LD->isDereferenceable();
6900   RLI.IsInvariant = LD->isInvariant();
6901   RLI.Alignment = LD->getAlignment();
6902   RLI.AAInfo = LD->getAAInfo();
6903   RLI.Ranges = LD->getRanges();
6904 
6905   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6906   return true;
6907 }
6908 
6909 // Given the head of the old chain, ResChain, insert a token factor containing
6910 // it and NewResChain, and make users of ResChain now be users of that token
6911 // factor.
6912 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
6913 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6914                                         SDValue NewResChain,
6915                                         SelectionDAG &DAG) const {
6916   if (!ResChain)
6917     return;
6918 
6919   SDLoc dl(NewResChain);
6920 
6921   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6922                            NewResChain, DAG.getUNDEF(MVT::Other));
6923   assert(TF.getNode() != NewResChain.getNode() &&
6924          "A new TF really is required here");
6925 
6926   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6927   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6928 }
6929 
6930 /// \brief Analyze profitability of direct move
6931 /// prefer float load to int load plus direct move
6932 /// when there is no integer use of int load
6933 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6934   SDNode *Origin = Op.getOperand(0).getNode();
6935   if (Origin->getOpcode() != ISD::LOAD)
6936     return true;
6937 
6938   // If there is no LXSIBZX/LXSIHZX, like Power8,
6939   // prefer direct move if the memory size is 1 or 2 bytes.
6940   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6941   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6942     return true;
6943 
6944   for (SDNode::use_iterator UI = Origin->use_begin(),
6945                             UE = Origin->use_end();
6946        UI != UE; ++UI) {
6947 
6948     // Only look at the users of the loaded value.
6949     if (UI.getUse().get().getResNo() != 0)
6950       continue;
6951 
6952     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6953         UI->getOpcode() != ISD::UINT_TO_FP)
6954       return true;
6955   }
6956 
6957   return false;
6958 }
6959 
6960 /// \brief Custom lowers integer to floating point conversions to use
6961 /// the direct move instructions available in ISA 2.07 to avoid the
6962 /// need for load/store combinations.
6963 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6964                                                     SelectionDAG &DAG,
6965                                                     const SDLoc &dl) const {
6966   assert((Op.getValueType() == MVT::f32 ||
6967           Op.getValueType() == MVT::f64) &&
6968          "Invalid floating point type as target of conversion");
6969   assert(Subtarget.hasFPCVT() &&
6970          "Int to FP conversions with direct moves require FPCVT");
6971   SDValue FP;
6972   SDValue Src = Op.getOperand(0);
6973   bool SinglePrec = Op.getValueType() == MVT::f32;
6974   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6975   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6976   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6977                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6978 
6979   if (WordInt) {
6980     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6981                      dl, MVT::f64, Src);
6982     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6983   }
6984   else {
6985     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6986     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6987   }
6988 
6989   return FP;
6990 }
6991 
6992 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6993                                           SelectionDAG &DAG) const {
6994   SDLoc dl(Op);
6995 
6996   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6997     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6998       return SDValue();
6999 
7000     SDValue Value = Op.getOperand(0);
7001     // The values are now known to be -1 (false) or 1 (true). To convert this
7002     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7003     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7004     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7005 
7006     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7007 
7008     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7009 
7010     if (Op.getValueType() != MVT::v4f64)
7011       Value = DAG.getNode(ISD::FP_ROUND, dl,
7012                           Op.getValueType(), Value,
7013                           DAG.getIntPtrConstant(1, dl));
7014     return Value;
7015   }
7016 
7017   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7018   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7019     return SDValue();
7020 
7021   if (Op.getOperand(0).getValueType() == MVT::i1)
7022     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7023                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7024                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7025 
7026   // If we have direct moves, we can do all the conversion, skip the store/load
7027   // however, without FPCVT we can't do most conversions.
7028   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7029       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7030     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7031 
7032   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7033          "UINT_TO_FP is supported only with FPCVT");
7034 
7035   // If we have FCFIDS, then use it when converting to single-precision.
7036   // Otherwise, convert to double-precision and then round.
7037   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7038                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7039                                                             : PPCISD::FCFIDS)
7040                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7041                                                             : PPCISD::FCFID);
7042   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7043                   ? MVT::f32
7044                   : MVT::f64;
7045 
7046   if (Op.getOperand(0).getValueType() == MVT::i64) {
7047     SDValue SINT = Op.getOperand(0);
7048     // When converting to single-precision, we actually need to convert
7049     // to double-precision first and then round to single-precision.
7050     // To avoid double-rounding effects during that operation, we have
7051     // to prepare the input operand.  Bits that might be truncated when
7052     // converting to double-precision are replaced by a bit that won't
7053     // be lost at this stage, but is below the single-precision rounding
7054     // position.
7055     //
7056     // However, if -enable-unsafe-fp-math is in effect, accept double
7057     // rounding to avoid the extra overhead.
7058     if (Op.getValueType() == MVT::f32 &&
7059         !Subtarget.hasFPCVT() &&
7060         !DAG.getTarget().Options.UnsafeFPMath) {
7061 
7062       // Twiddle input to make sure the low 11 bits are zero.  (If this
7063       // is the case, we are guaranteed the value will fit into the 53 bit
7064       // mantissa of an IEEE double-precision value without rounding.)
7065       // If any of those low 11 bits were not zero originally, make sure
7066       // bit 12 (value 2048) is set instead, so that the final rounding
7067       // to single-precision gets the correct result.
7068       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7069                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7070       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7071                           Round, DAG.getConstant(2047, dl, MVT::i64));
7072       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7073       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7074                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7075 
7076       // However, we cannot use that value unconditionally: if the magnitude
7077       // of the input value is small, the bit-twiddling we did above might
7078       // end up visibly changing the output.  Fortunately, in that case, we
7079       // don't need to twiddle bits since the original input will convert
7080       // exactly to double-precision floating-point already.  Therefore,
7081       // construct a conditional to use the original value if the top 11
7082       // bits are all sign-bit copies, and use the rounded value computed
7083       // above otherwise.
7084       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7085                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7086       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7087                          Cond, DAG.getConstant(1, dl, MVT::i64));
7088       Cond = DAG.getSetCC(dl, MVT::i32,
7089                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7090 
7091       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7092     }
7093 
7094     ReuseLoadInfo RLI;
7095     SDValue Bits;
7096 
7097     MachineFunction &MF = DAG.getMachineFunction();
7098     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7099       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7100                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7101       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7102     } else if (Subtarget.hasLFIWAX() &&
7103                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7104       MachineMemOperand *MMO =
7105         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7106                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7107       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7108       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7109                                      DAG.getVTList(MVT::f64, MVT::Other),
7110                                      Ops, MVT::i32, MMO);
7111       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7112     } else if (Subtarget.hasFPCVT() &&
7113                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7114       MachineMemOperand *MMO =
7115         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7116                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7117       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7118       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7119                                      DAG.getVTList(MVT::f64, MVT::Other),
7120                                      Ops, MVT::i32, MMO);
7121       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7122     } else if (((Subtarget.hasLFIWAX() &&
7123                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7124                 (Subtarget.hasFPCVT() &&
7125                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7126                SINT.getOperand(0).getValueType() == MVT::i32) {
7127       MachineFrameInfo &MFI = MF.getFrameInfo();
7128       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7129 
7130       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7131       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7132 
7133       SDValue Store =
7134           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7135                        MachinePointerInfo::getFixedStack(
7136                            DAG.getMachineFunction(), FrameIdx));
7137 
7138       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7139              "Expected an i32 store");
7140 
7141       RLI.Ptr = FIdx;
7142       RLI.Chain = Store;
7143       RLI.MPI =
7144           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7145       RLI.Alignment = 4;
7146 
7147       MachineMemOperand *MMO =
7148         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7149                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7150       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7151       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7152                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7153                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7154                                      Ops, MVT::i32, MMO);
7155     } else
7156       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7157 
7158     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7159 
7160     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7161       FP = DAG.getNode(ISD::FP_ROUND, dl,
7162                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7163     return FP;
7164   }
7165 
7166   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7167          "Unhandled INT_TO_FP type in custom expander!");
7168   // Since we only generate this in 64-bit mode, we can take advantage of
7169   // 64-bit registers.  In particular, sign extend the input value into the
7170   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7171   // then lfd it and fcfid it.
7172   MachineFunction &MF = DAG.getMachineFunction();
7173   MachineFrameInfo &MFI = MF.getFrameInfo();
7174   EVT PtrVT = getPointerTy(MF.getDataLayout());
7175 
7176   SDValue Ld;
7177   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7178     ReuseLoadInfo RLI;
7179     bool ReusingLoad;
7180     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7181                                             DAG))) {
7182       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7183       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7184 
7185       SDValue Store =
7186           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7187                        MachinePointerInfo::getFixedStack(
7188                            DAG.getMachineFunction(), FrameIdx));
7189 
7190       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7191              "Expected an i32 store");
7192 
7193       RLI.Ptr = FIdx;
7194       RLI.Chain = Store;
7195       RLI.MPI =
7196           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7197       RLI.Alignment = 4;
7198     }
7199 
7200     MachineMemOperand *MMO =
7201       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7202                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7203     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7204     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7205                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7206                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7207                                  Ops, MVT::i32, MMO);
7208     if (ReusingLoad)
7209       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7210   } else {
7211     assert(Subtarget.isPPC64() &&
7212            "i32->FP without LFIWAX supported only on PPC64");
7213 
7214     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7215     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7216 
7217     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7218                                 Op.getOperand(0));
7219 
7220     // STD the extended value into the stack slot.
7221     SDValue Store = DAG.getStore(
7222         DAG.getEntryNode(), dl, Ext64, FIdx,
7223         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7224 
7225     // Load the value as a double.
7226     Ld = DAG.getLoad(
7227         MVT::f64, dl, Store, FIdx,
7228         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7229   }
7230 
7231   // FCFID it and return it.
7232   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7233   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7234     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7235                      DAG.getIntPtrConstant(0, dl));
7236   return FP;
7237 }
7238 
7239 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7240                                             SelectionDAG &DAG) const {
7241   SDLoc dl(Op);
7242   /*
7243    The rounding mode is in bits 30:31 of FPSR, and has the following
7244    settings:
7245      00 Round to nearest
7246      01 Round to 0
7247      10 Round to +inf
7248      11 Round to -inf
7249 
7250   FLT_ROUNDS, on the other hand, expects the following:
7251     -1 Undefined
7252      0 Round to 0
7253      1 Round to nearest
7254      2 Round to +inf
7255      3 Round to -inf
7256 
7257   To perform the conversion, we do:
7258     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7259   */
7260 
7261   MachineFunction &MF = DAG.getMachineFunction();
7262   EVT VT = Op.getValueType();
7263   EVT PtrVT = getPointerTy(MF.getDataLayout());
7264 
7265   // Save FP Control Word to register
7266   EVT NodeTys[] = {
7267     MVT::f64,    // return register
7268     MVT::Glue    // unused in this context
7269   };
7270   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7271 
7272   // Save FP register to stack slot
7273   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7274   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7275   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7276                                MachinePointerInfo());
7277 
7278   // Load FP Control Word from low 32 bits of stack slot.
7279   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7280   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7281   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7282 
7283   // Transform as necessary
7284   SDValue CWD1 =
7285     DAG.getNode(ISD::AND, dl, MVT::i32,
7286                 CWD, DAG.getConstant(3, dl, MVT::i32));
7287   SDValue CWD2 =
7288     DAG.getNode(ISD::SRL, dl, MVT::i32,
7289                 DAG.getNode(ISD::AND, dl, MVT::i32,
7290                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7291                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7292                             DAG.getConstant(3, dl, MVT::i32)),
7293                 DAG.getConstant(1, dl, MVT::i32));
7294 
7295   SDValue RetVal =
7296     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7297 
7298   return DAG.getNode((VT.getSizeInBits() < 16 ?
7299                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7300 }
7301 
7302 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7303   EVT VT = Op.getValueType();
7304   unsigned BitWidth = VT.getSizeInBits();
7305   SDLoc dl(Op);
7306   assert(Op.getNumOperands() == 3 &&
7307          VT == Op.getOperand(1).getValueType() &&
7308          "Unexpected SHL!");
7309 
7310   // Expand into a bunch of logical ops.  Note that these ops
7311   // depend on the PPC behavior for oversized shift amounts.
7312   SDValue Lo = Op.getOperand(0);
7313   SDValue Hi = Op.getOperand(1);
7314   SDValue Amt = Op.getOperand(2);
7315   EVT AmtVT = Amt.getValueType();
7316 
7317   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7318                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7319   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7320   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7321   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7322   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7323                              DAG.getConstant(-BitWidth, dl, AmtVT));
7324   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7325   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7326   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7327   SDValue OutOps[] = { OutLo, OutHi };
7328   return DAG.getMergeValues(OutOps, dl);
7329 }
7330 
7331 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7332   EVT VT = Op.getValueType();
7333   SDLoc dl(Op);
7334   unsigned BitWidth = VT.getSizeInBits();
7335   assert(Op.getNumOperands() == 3 &&
7336          VT == Op.getOperand(1).getValueType() &&
7337          "Unexpected SRL!");
7338 
7339   // Expand into a bunch of logical ops.  Note that these ops
7340   // depend on the PPC behavior for oversized shift amounts.
7341   SDValue Lo = Op.getOperand(0);
7342   SDValue Hi = Op.getOperand(1);
7343   SDValue Amt = Op.getOperand(2);
7344   EVT AmtVT = Amt.getValueType();
7345 
7346   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7347                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7348   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7349   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7350   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7351   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7352                              DAG.getConstant(-BitWidth, dl, AmtVT));
7353   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7354   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7355   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7356   SDValue OutOps[] = { OutLo, OutHi };
7357   return DAG.getMergeValues(OutOps, dl);
7358 }
7359 
7360 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7361   SDLoc dl(Op);
7362   EVT VT = Op.getValueType();
7363   unsigned BitWidth = VT.getSizeInBits();
7364   assert(Op.getNumOperands() == 3 &&
7365          VT == Op.getOperand(1).getValueType() &&
7366          "Unexpected SRA!");
7367 
7368   // Expand into a bunch of logical ops, followed by a select_cc.
7369   SDValue Lo = Op.getOperand(0);
7370   SDValue Hi = Op.getOperand(1);
7371   SDValue Amt = Op.getOperand(2);
7372   EVT AmtVT = Amt.getValueType();
7373 
7374   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7375                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7376   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7377   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7378   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7379   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7380                              DAG.getConstant(-BitWidth, dl, AmtVT));
7381   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7382   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7383   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7384                                   Tmp4, Tmp6, ISD::SETLE);
7385   SDValue OutOps[] = { OutLo, OutHi };
7386   return DAG.getMergeValues(OutOps, dl);
7387 }
7388 
7389 //===----------------------------------------------------------------------===//
7390 // Vector related lowering.
7391 //
7392 
7393 /// BuildSplatI - Build a canonical splati of Val with an element size of
7394 /// SplatSize.  Cast the result to VT.
7395 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7396                            SelectionDAG &DAG, const SDLoc &dl) {
7397   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7398 
7399   static const MVT VTys[] = { // canonical VT to use for each size.
7400     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7401   };
7402 
7403   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7404 
7405   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7406   if (Val == -1)
7407     SplatSize = 1;
7408 
7409   EVT CanonicalVT = VTys[SplatSize-1];
7410 
7411   // Build a canonical splat for this value.
7412   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7413 }
7414 
7415 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7416 /// specified intrinsic ID.
7417 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7418                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7419   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7420   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7421                      DAG.getConstant(IID, dl, MVT::i32), Op);
7422 }
7423 
7424 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7425 /// specified intrinsic ID.
7426 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7427                                 SelectionDAG &DAG, const SDLoc &dl,
7428                                 EVT DestVT = MVT::Other) {
7429   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7430   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7431                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7432 }
7433 
7434 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7435 /// specified intrinsic ID.
7436 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7437                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7438                                 EVT DestVT = MVT::Other) {
7439   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7440   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7441                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7442 }
7443 
7444 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7445 /// amount.  The result has the specified value type.
7446 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7447                            SelectionDAG &DAG, const SDLoc &dl) {
7448   // Force LHS/RHS to be the right type.
7449   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7450   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7451 
7452   int Ops[16];
7453   for (unsigned i = 0; i != 16; ++i)
7454     Ops[i] = i + Amt;
7455   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7456   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7457 }
7458 
7459 /// Do we have an efficient pattern in a .td file for this node?
7460 ///
7461 /// \param V - pointer to the BuildVectorSDNode being matched
7462 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7463 ///
7464 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7465 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7466 /// the opposite is true (expansion is beneficial) are:
7467 /// - The node builds a vector out of integers that are not 32 or 64-bits
7468 /// - The node builds a vector out of constants
7469 /// - The node is a "load-and-splat"
7470 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7471 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7472                                             bool HasDirectMove,
7473                                             bool HasP8Vector) {
7474   EVT VecVT = V->getValueType(0);
7475   bool RightType = VecVT == MVT::v2f64 ||
7476     (HasP8Vector && VecVT == MVT::v4f32) ||
7477     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7478   if (!RightType)
7479     return false;
7480 
7481   bool IsSplat = true;
7482   bool IsLoad = false;
7483   SDValue Op0 = V->getOperand(0);
7484 
7485   // This function is called in a block that confirms the node is not a constant
7486   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7487   // different constants.
7488   if (V->isConstant())
7489     return false;
7490   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7491     if (V->getOperand(i).isUndef())
7492       return false;
7493     // We want to expand nodes that represent load-and-splat even if the
7494     // loaded value is a floating point truncation or conversion to int.
7495     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7496         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7497          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7498         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7499          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7500         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7501          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7502       IsLoad = true;
7503     // If the operands are different or the input is not a load and has more
7504     // uses than just this BV node, then it isn't a splat.
7505     if (V->getOperand(i) != Op0 ||
7506         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7507       IsSplat = false;
7508   }
7509   return !(IsSplat && IsLoad);
7510 }
7511 
7512 // If this is a case we can't handle, return null and let the default
7513 // expansion code take care of it.  If we CAN select this case, and if it
7514 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7515 // this case more efficiently than a constant pool load, lower it to the
7516 // sequence of ops that should be used.
7517 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7518                                              SelectionDAG &DAG) const {
7519   SDLoc dl(Op);
7520   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7521   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7522 
7523   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7524     // We first build an i32 vector, load it into a QPX register,
7525     // then convert it to a floating-point vector and compare it
7526     // to a zero vector to get the boolean result.
7527     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7528     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7529     MachinePointerInfo PtrInfo =
7530         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7531     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7532     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7533 
7534     assert(BVN->getNumOperands() == 4 &&
7535       "BUILD_VECTOR for v4i1 does not have 4 operands");
7536 
7537     bool IsConst = true;
7538     for (unsigned i = 0; i < 4; ++i) {
7539       if (BVN->getOperand(i).isUndef()) continue;
7540       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7541         IsConst = false;
7542         break;
7543       }
7544     }
7545 
7546     if (IsConst) {
7547       Constant *One =
7548         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7549       Constant *NegOne =
7550         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7551 
7552       Constant *CV[4];
7553       for (unsigned i = 0; i < 4; ++i) {
7554         if (BVN->getOperand(i).isUndef())
7555           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7556         else if (isNullConstant(BVN->getOperand(i)))
7557           CV[i] = NegOne;
7558         else
7559           CV[i] = One;
7560       }
7561 
7562       Constant *CP = ConstantVector::get(CV);
7563       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7564                                           16 /* alignment */);
7565 
7566       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7567       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7568       return DAG.getMemIntrinsicNode(
7569           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7570           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7571     }
7572 
7573     SmallVector<SDValue, 4> Stores;
7574     for (unsigned i = 0; i < 4; ++i) {
7575       if (BVN->getOperand(i).isUndef()) continue;
7576 
7577       unsigned Offset = 4*i;
7578       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7579       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7580 
7581       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7582       if (StoreSize > 4) {
7583         Stores.push_back(
7584             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7585                               PtrInfo.getWithOffset(Offset), MVT::i32));
7586       } else {
7587         SDValue StoreValue = BVN->getOperand(i);
7588         if (StoreSize < 4)
7589           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7590 
7591         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7592                                       PtrInfo.getWithOffset(Offset)));
7593       }
7594     }
7595 
7596     SDValue StoreChain;
7597     if (!Stores.empty())
7598       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7599     else
7600       StoreChain = DAG.getEntryNode();
7601 
7602     // Now load from v4i32 into the QPX register; this will extend it to
7603     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7604     // is typed as v4f64 because the QPX register integer states are not
7605     // explicitly represented.
7606 
7607     SDValue Ops[] = {StoreChain,
7608                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7609                      FIdx};
7610     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7611 
7612     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7613       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7614     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7615       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7616       LoadedVect);
7617 
7618     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7619 
7620     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7621   }
7622 
7623   // All other QPX vectors are handled by generic code.
7624   if (Subtarget.hasQPX())
7625     return SDValue();
7626 
7627   // Check if this is a splat of a constant value.
7628   APInt APSplatBits, APSplatUndef;
7629   unsigned SplatBitSize;
7630   bool HasAnyUndefs;
7631   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7632                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7633       SplatBitSize > 32) {
7634     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7635     // lowered to VSX instructions under certain conditions.
7636     // Without VSX, there is no pattern more efficient than expanding the node.
7637     if (Subtarget.hasVSX() &&
7638         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
7639                                         Subtarget.hasP8Vector()))
7640       return Op;
7641     return SDValue();
7642   }
7643 
7644   unsigned SplatBits = APSplatBits.getZExtValue();
7645   unsigned SplatUndef = APSplatUndef.getZExtValue();
7646   unsigned SplatSize = SplatBitSize / 8;
7647 
7648   // First, handle single instruction cases.
7649 
7650   // All zeros?
7651   if (SplatBits == 0) {
7652     // Canonicalize all zero vectors to be v4i32.
7653     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7654       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7655       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7656     }
7657     return Op;
7658   }
7659 
7660   // We have XXSPLTIB for constant splats one byte wide
7661   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7662     // This is a splat of 1-byte elements with some elements potentially undef.
7663     // Rather than trying to match undef in the SDAG patterns, ensure that all
7664     // elements are the same constant.
7665     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7666       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7667                                                        dl, MVT::i32));
7668       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7669       if (Op.getValueType() != MVT::v16i8)
7670         return DAG.getBitcast(Op.getValueType(), NewBV);
7671       return NewBV;
7672     }
7673 
7674     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
7675     // detect that constant splats like v8i16: 0xABAB are really just splats
7676     // of a 1-byte constant. In this case, we need to convert the node to a
7677     // splat of v16i8 and a bitcast.
7678     if (Op.getValueType() != MVT::v16i8)
7679       return DAG.getBitcast(Op.getValueType(),
7680                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
7681 
7682     return Op;
7683   }
7684 
7685   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7686   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7687                     (32-SplatBitSize));
7688   if (SextVal >= -16 && SextVal <= 15)
7689     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7690 
7691   // Two instruction sequences.
7692 
7693   // If this value is in the range [-32,30] and is even, use:
7694   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7695   // If this value is in the range [17,31] and is odd, use:
7696   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7697   // If this value is in the range [-31,-17] and is odd, use:
7698   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7699   // Note the last two are three-instruction sequences.
7700   if (SextVal >= -32 && SextVal <= 31) {
7701     // To avoid having these optimizations undone by constant folding,
7702     // we convert to a pseudo that will be expanded later into one of
7703     // the above forms.
7704     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7705     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7706               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7707     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7708     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7709     if (VT == Op.getValueType())
7710       return RetVal;
7711     else
7712       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7713   }
7714 
7715   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7716   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7717   // for fneg/fabs.
7718   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7719     // Make -1 and vspltisw -1:
7720     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7721 
7722     // Make the VSLW intrinsic, computing 0x8000_0000.
7723     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7724                                    OnesV, DAG, dl);
7725 
7726     // xor by OnesV to invert it.
7727     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7728     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7729   }
7730 
7731   // Check to see if this is a wide variety of vsplti*, binop self cases.
7732   static const signed char SplatCsts[] = {
7733     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7734     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7735   };
7736 
7737   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7738     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7739     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7740     int i = SplatCsts[idx];
7741 
7742     // Figure out what shift amount will be used by altivec if shifted by i in
7743     // this splat size.
7744     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7745 
7746     // vsplti + shl self.
7747     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7748       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7749       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7750         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7751         Intrinsic::ppc_altivec_vslw
7752       };
7753       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7754       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7755     }
7756 
7757     // vsplti + srl self.
7758     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7759       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7760       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7761         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7762         Intrinsic::ppc_altivec_vsrw
7763       };
7764       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7765       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7766     }
7767 
7768     // vsplti + sra self.
7769     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7770       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7771       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7772         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7773         Intrinsic::ppc_altivec_vsraw
7774       };
7775       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7776       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7777     }
7778 
7779     // vsplti + rol self.
7780     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7781                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7782       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7783       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7784         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7785         Intrinsic::ppc_altivec_vrlw
7786       };
7787       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7788       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7789     }
7790 
7791     // t = vsplti c, result = vsldoi t, t, 1
7792     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7793       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7794       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7795       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7796     }
7797     // t = vsplti c, result = vsldoi t, t, 2
7798     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7799       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7800       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7801       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7802     }
7803     // t = vsplti c, result = vsldoi t, t, 3
7804     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7805       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7806       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7807       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7808     }
7809   }
7810 
7811   return SDValue();
7812 }
7813 
7814 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7815 /// the specified operations to build the shuffle.
7816 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7817                                       SDValue RHS, SelectionDAG &DAG,
7818                                       const SDLoc &dl) {
7819   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7820   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7821   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7822 
7823   enum {
7824     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7825     OP_VMRGHW,
7826     OP_VMRGLW,
7827     OP_VSPLTISW0,
7828     OP_VSPLTISW1,
7829     OP_VSPLTISW2,
7830     OP_VSPLTISW3,
7831     OP_VSLDOI4,
7832     OP_VSLDOI8,
7833     OP_VSLDOI12
7834   };
7835 
7836   if (OpNum == OP_COPY) {
7837     if (LHSID == (1*9+2)*9+3) return LHS;
7838     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7839     return RHS;
7840   }
7841 
7842   SDValue OpLHS, OpRHS;
7843   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7844   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7845 
7846   int ShufIdxs[16];
7847   switch (OpNum) {
7848   default: llvm_unreachable("Unknown i32 permute!");
7849   case OP_VMRGHW:
7850     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7851     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7852     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7853     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7854     break;
7855   case OP_VMRGLW:
7856     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7857     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7858     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7859     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7860     break;
7861   case OP_VSPLTISW0:
7862     for (unsigned i = 0; i != 16; ++i)
7863       ShufIdxs[i] = (i&3)+0;
7864     break;
7865   case OP_VSPLTISW1:
7866     for (unsigned i = 0; i != 16; ++i)
7867       ShufIdxs[i] = (i&3)+4;
7868     break;
7869   case OP_VSPLTISW2:
7870     for (unsigned i = 0; i != 16; ++i)
7871       ShufIdxs[i] = (i&3)+8;
7872     break;
7873   case OP_VSPLTISW3:
7874     for (unsigned i = 0; i != 16; ++i)
7875       ShufIdxs[i] = (i&3)+12;
7876     break;
7877   case OP_VSLDOI4:
7878     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7879   case OP_VSLDOI8:
7880     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7881   case OP_VSLDOI12:
7882     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7883   }
7884   EVT VT = OpLHS.getValueType();
7885   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7886   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7887   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7888   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7889 }
7890 
7891 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
7892 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
7893 /// SDValue.
7894 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
7895                                            SelectionDAG &DAG) const {
7896   const unsigned NumHalfWords = 8;
7897   const unsigned BytesInVector = NumHalfWords * 2;
7898   // Check that the shuffle is on half-words.
7899   if (!isNByteElemShuffleMask(N, 2, 1))
7900     return SDValue();
7901 
7902   bool IsLE = Subtarget.isLittleEndian();
7903   SDLoc dl(N);
7904   SDValue V1 = N->getOperand(0);
7905   SDValue V2 = N->getOperand(1);
7906   unsigned ShiftElts = 0, InsertAtByte = 0;
7907   bool Swap = false;
7908 
7909   // Shifts required to get the half-word we want at element 3.
7910   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
7911   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
7912 
7913   uint32_t Mask = 0;
7914   uint32_t OriginalOrderLow = 0x1234567;
7915   uint32_t OriginalOrderHigh = 0x89ABCDEF;
7916   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
7917   // 32-bit space, only need 4-bit nibbles per element.
7918   for (unsigned i = 0; i < NumHalfWords; ++i) {
7919     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
7920     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
7921   }
7922 
7923   // For each mask element, find out if we're just inserting something
7924   // from V2 into V1 or vice versa.  Possible permutations inserting an element
7925   // from V2 into V1:
7926   //   X, 1, 2, 3, 4, 5, 6, 7
7927   //   0, X, 2, 3, 4, 5, 6, 7
7928   //   0, 1, X, 3, 4, 5, 6, 7
7929   //   0, 1, 2, X, 4, 5, 6, 7
7930   //   0, 1, 2, 3, X, 5, 6, 7
7931   //   0, 1, 2, 3, 4, X, 6, 7
7932   //   0, 1, 2, 3, 4, 5, X, 7
7933   //   0, 1, 2, 3, 4, 5, 6, X
7934   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
7935 
7936   bool FoundCandidate = false;
7937   // Go through the mask of half-words to find an element that's being moved
7938   // from one vector to the other.
7939   for (unsigned i = 0; i < NumHalfWords; ++i) {
7940     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
7941     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
7942     uint32_t MaskOtherElts = ~(0xF << MaskShift);
7943     uint32_t TargetOrder = 0x0;
7944 
7945     // If both vector operands for the shuffle are the same vector, the mask
7946     // will contain only elements from the first one and the second one will be
7947     // undef.
7948     if (V2.isUndef()) {
7949       ShiftElts = 0;
7950       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
7951       TargetOrder = OriginalOrderLow;
7952       Swap = false;
7953       // Skip if not the correct element or mask of other elements don't equal
7954       // to our expected order.
7955       if (MaskOneElt == VINSERTHSrcElem &&
7956           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
7957         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
7958         FoundCandidate = true;
7959         break;
7960       }
7961     } else { // If both operands are defined.
7962       // Target order is [8,15] if the current mask is between [0,7].
7963       TargetOrder =
7964           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
7965       // Skip if mask of other elements don't equal our expected order.
7966       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
7967         // We only need the last 3 bits for the number of shifts.
7968         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
7969                          : BigEndianShifts[MaskOneElt & 0x7];
7970         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
7971         Swap = MaskOneElt < NumHalfWords;
7972         FoundCandidate = true;
7973         break;
7974       }
7975     }
7976   }
7977 
7978   if (!FoundCandidate)
7979     return SDValue();
7980 
7981   // Candidate found, construct the proper SDAG sequence with VINSERTH,
7982   // optionally with VECSHL if shift is required.
7983   if (Swap)
7984     std::swap(V1, V2);
7985   if (V2.isUndef())
7986     V2 = V1;
7987   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7988   if (ShiftElts) {
7989     // Double ShiftElts because we're left shifting on v16i8 type.
7990     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
7991                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
7992     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
7993     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
7994                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7995     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7996   }
7997   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7998   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
7999                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8000   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8001 }
8002 
8003 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8004 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8005 /// return the code it can be lowered into.  Worst case, it can always be
8006 /// lowered into a vperm.
8007 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8008                                                SelectionDAG &DAG) const {
8009   SDLoc dl(Op);
8010   SDValue V1 = Op.getOperand(0);
8011   SDValue V2 = Op.getOperand(1);
8012   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8013   EVT VT = Op.getValueType();
8014   bool isLittleEndian = Subtarget.isLittleEndian();
8015 
8016   unsigned ShiftElts, InsertAtByte;
8017   bool Swap = false;
8018   if (Subtarget.hasP9Vector() &&
8019       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8020                            isLittleEndian)) {
8021     if (Swap)
8022       std::swap(V1, V2);
8023     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8024     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8025     if (ShiftElts) {
8026       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8027                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8028       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8029                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8030       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8031     }
8032     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8033                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8034     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8035   }
8036 
8037   if (Subtarget.hasP9Altivec()) {
8038     SDValue NewISDNode = lowerToVINSERTH(SVOp, DAG);
8039     if (NewISDNode)
8040       return NewISDNode;
8041   }
8042 
8043   if (Subtarget.hasVSX() &&
8044       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8045     if (Swap)
8046       std::swap(V1, V2);
8047     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8048     SDValue Conv2 =
8049         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8050 
8051     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8052                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8053     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8054   }
8055 
8056   if (Subtarget.hasVSX() &&
8057     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8058     if (Swap)
8059       std::swap(V1, V2);
8060     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8061     SDValue Conv2 =
8062         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8063 
8064     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8065                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8066     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8067   }
8068 
8069   if (Subtarget.hasP9Vector()) {
8070      if (PPC::isXXBRHShuffleMask(SVOp)) {
8071       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8072       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8073       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8074     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8075       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8076       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8077       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8078     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8079       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8080       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8081       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8082     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8083       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8084       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8085       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8086     }
8087   }
8088 
8089   if (Subtarget.hasVSX()) {
8090     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8091       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8092 
8093       // If the source for the shuffle is a scalar_to_vector that came from a
8094       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
8095       if (Subtarget.hasP9Vector() &&
8096           ((isLittleEndian && SplatIdx == 3) ||
8097            (!isLittleEndian && SplatIdx == 0))) {
8098         SDValue Src = V1.getOperand(0);
8099         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8100             Src.getOperand(0).getOpcode() == ISD::LOAD &&
8101             Src.getOperand(0).hasOneUse())
8102           return V1;
8103       }
8104       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8105       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8106                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8107       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8108     }
8109 
8110     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8111     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8112       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8113       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8114       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8115     }
8116   }
8117 
8118   if (Subtarget.hasQPX()) {
8119     if (VT.getVectorNumElements() != 4)
8120       return SDValue();
8121 
8122     if (V2.isUndef()) V2 = V1;
8123 
8124     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8125     if (AlignIdx != -1) {
8126       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8127                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8128     } else if (SVOp->isSplat()) {
8129       int SplatIdx = SVOp->getSplatIndex();
8130       if (SplatIdx >= 4) {
8131         std::swap(V1, V2);
8132         SplatIdx -= 4;
8133       }
8134 
8135       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8136                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8137     }
8138 
8139     // Lower this into a qvgpci/qvfperm pair.
8140 
8141     // Compute the qvgpci literal
8142     unsigned idx = 0;
8143     for (unsigned i = 0; i < 4; ++i) {
8144       int m = SVOp->getMaskElt(i);
8145       unsigned mm = m >= 0 ? (unsigned) m : i;
8146       idx |= mm << (3-i)*3;
8147     }
8148 
8149     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8150                              DAG.getConstant(idx, dl, MVT::i32));
8151     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8152   }
8153 
8154   // Cases that are handled by instructions that take permute immediates
8155   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8156   // selected by the instruction selector.
8157   if (V2.isUndef()) {
8158     if (PPC::isSplatShuffleMask(SVOp, 1) ||
8159         PPC::isSplatShuffleMask(SVOp, 2) ||
8160         PPC::isSplatShuffleMask(SVOp, 4) ||
8161         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8162         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8163         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8164         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8165         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8166         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8167         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8168         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8169         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8170         (Subtarget.hasP8Altivec() && (
8171          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8172          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8173          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8174       return Op;
8175     }
8176   }
8177 
8178   // Altivec has a variety of "shuffle immediates" that take two vector inputs
8179   // and produce a fixed permutation.  If any of these match, do not lower to
8180   // VPERM.
8181   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8182   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8183       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8184       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8185       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8186       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8187       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8188       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8189       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8190       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8191       (Subtarget.hasP8Altivec() && (
8192        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8193        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8194        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8195     return Op;
8196 
8197   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
8198   // perfect shuffle table to emit an optimal matching sequence.
8199   ArrayRef<int> PermMask = SVOp->getMask();
8200 
8201   unsigned PFIndexes[4];
8202   bool isFourElementShuffle = true;
8203   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8204     unsigned EltNo = 8;   // Start out undef.
8205     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
8206       if (PermMask[i*4+j] < 0)
8207         continue;   // Undef, ignore it.
8208 
8209       unsigned ByteSource = PermMask[i*4+j];
8210       if ((ByteSource & 3) != j) {
8211         isFourElementShuffle = false;
8212         break;
8213       }
8214 
8215       if (EltNo == 8) {
8216         EltNo = ByteSource/4;
8217       } else if (EltNo != ByteSource/4) {
8218         isFourElementShuffle = false;
8219         break;
8220       }
8221     }
8222     PFIndexes[i] = EltNo;
8223   }
8224 
8225   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8226   // perfect shuffle vector to determine if it is cost effective to do this as
8227   // discrete instructions, or whether we should use a vperm.
8228   // For now, we skip this for little endian until such time as we have a
8229   // little-endian perfect shuffle table.
8230   if (isFourElementShuffle && !isLittleEndian) {
8231     // Compute the index in the perfect shuffle table.
8232     unsigned PFTableIndex =
8233       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8234 
8235     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8236     unsigned Cost  = (PFEntry >> 30);
8237 
8238     // Determining when to avoid vperm is tricky.  Many things affect the cost
8239     // of vperm, particularly how many times the perm mask needs to be computed.
8240     // For example, if the perm mask can be hoisted out of a loop or is already
8241     // used (perhaps because there are multiple permutes with the same shuffle
8242     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
8243     // the loop requires an extra register.
8244     //
8245     // As a compromise, we only emit discrete instructions if the shuffle can be
8246     // generated in 3 or fewer operations.  When we have loop information
8247     // available, if this block is within a loop, we should avoid using vperm
8248     // for 3-operation perms and use a constant pool load instead.
8249     if (Cost < 3)
8250       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8251   }
8252 
8253   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8254   // vector that will get spilled to the constant pool.
8255   if (V2.isUndef()) V2 = V1;
8256 
8257   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8258   // that it is in input element units, not in bytes.  Convert now.
8259 
8260   // For little endian, the order of the input vectors is reversed, and
8261   // the permutation mask is complemented with respect to 31.  This is
8262   // necessary to produce proper semantics with the big-endian-biased vperm
8263   // instruction.
8264   EVT EltVT = V1.getValueType().getVectorElementType();
8265   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8266 
8267   SmallVector<SDValue, 16> ResultMask;
8268   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8269     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8270 
8271     for (unsigned j = 0; j != BytesPerElement; ++j)
8272       if (isLittleEndian)
8273         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8274                                              dl, MVT::i32));
8275       else
8276         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8277                                              MVT::i32));
8278   }
8279 
8280   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
8281   if (isLittleEndian)
8282     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8283                        V2, V1, VPermMask);
8284   else
8285     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8286                        V1, V2, VPermMask);
8287 }
8288 
8289 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
8290 /// vector comparison.  If it is, return true and fill in Opc/isDot with
8291 /// information about the intrinsic.
8292 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
8293                                  bool &isDot, const PPCSubtarget &Subtarget) {
8294   unsigned IntrinsicID =
8295       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
8296   CompareOpc = -1;
8297   isDot = false;
8298   switch (IntrinsicID) {
8299   default:
8300     return false;
8301   // Comparison predicates.
8302   case Intrinsic::ppc_altivec_vcmpbfp_p:
8303     CompareOpc = 966;
8304     isDot = true;
8305     break;
8306   case Intrinsic::ppc_altivec_vcmpeqfp_p:
8307     CompareOpc = 198;
8308     isDot = true;
8309     break;
8310   case Intrinsic::ppc_altivec_vcmpequb_p:
8311     CompareOpc = 6;
8312     isDot = true;
8313     break;
8314   case Intrinsic::ppc_altivec_vcmpequh_p:
8315     CompareOpc = 70;
8316     isDot = true;
8317     break;
8318   case Intrinsic::ppc_altivec_vcmpequw_p:
8319     CompareOpc = 134;
8320     isDot = true;
8321     break;
8322   case Intrinsic::ppc_altivec_vcmpequd_p:
8323     if (Subtarget.hasP8Altivec()) {
8324       CompareOpc = 199;
8325       isDot = true;
8326     } else
8327       return false;
8328     break;
8329   case Intrinsic::ppc_altivec_vcmpneb_p:
8330   case Intrinsic::ppc_altivec_vcmpneh_p:
8331   case Intrinsic::ppc_altivec_vcmpnew_p:
8332   case Intrinsic::ppc_altivec_vcmpnezb_p:
8333   case Intrinsic::ppc_altivec_vcmpnezh_p:
8334   case Intrinsic::ppc_altivec_vcmpnezw_p:
8335     if (Subtarget.hasP9Altivec()) {
8336       switch (IntrinsicID) {
8337       default:
8338         llvm_unreachable("Unknown comparison intrinsic.");
8339       case Intrinsic::ppc_altivec_vcmpneb_p:
8340         CompareOpc = 7;
8341         break;
8342       case Intrinsic::ppc_altivec_vcmpneh_p:
8343         CompareOpc = 71;
8344         break;
8345       case Intrinsic::ppc_altivec_vcmpnew_p:
8346         CompareOpc = 135;
8347         break;
8348       case Intrinsic::ppc_altivec_vcmpnezb_p:
8349         CompareOpc = 263;
8350         break;
8351       case Intrinsic::ppc_altivec_vcmpnezh_p:
8352         CompareOpc = 327;
8353         break;
8354       case Intrinsic::ppc_altivec_vcmpnezw_p:
8355         CompareOpc = 391;
8356         break;
8357       }
8358       isDot = true;
8359     } else
8360       return false;
8361     break;
8362   case Intrinsic::ppc_altivec_vcmpgefp_p:
8363     CompareOpc = 454;
8364     isDot = true;
8365     break;
8366   case Intrinsic::ppc_altivec_vcmpgtfp_p:
8367     CompareOpc = 710;
8368     isDot = true;
8369     break;
8370   case Intrinsic::ppc_altivec_vcmpgtsb_p:
8371     CompareOpc = 774;
8372     isDot = true;
8373     break;
8374   case Intrinsic::ppc_altivec_vcmpgtsh_p:
8375     CompareOpc = 838;
8376     isDot = true;
8377     break;
8378   case Intrinsic::ppc_altivec_vcmpgtsw_p:
8379     CompareOpc = 902;
8380     isDot = true;
8381     break;
8382   case Intrinsic::ppc_altivec_vcmpgtsd_p:
8383     if (Subtarget.hasP8Altivec()) {
8384       CompareOpc = 967;
8385       isDot = true;
8386     } else
8387       return false;
8388     break;
8389   case Intrinsic::ppc_altivec_vcmpgtub_p:
8390     CompareOpc = 518;
8391     isDot = true;
8392     break;
8393   case Intrinsic::ppc_altivec_vcmpgtuh_p:
8394     CompareOpc = 582;
8395     isDot = true;
8396     break;
8397   case Intrinsic::ppc_altivec_vcmpgtuw_p:
8398     CompareOpc = 646;
8399     isDot = true;
8400     break;
8401   case Intrinsic::ppc_altivec_vcmpgtud_p:
8402     if (Subtarget.hasP8Altivec()) {
8403       CompareOpc = 711;
8404       isDot = true;
8405     } else
8406       return false;
8407     break;
8408 
8409   // VSX predicate comparisons use the same infrastructure
8410   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8411   case Intrinsic::ppc_vsx_xvcmpgedp_p:
8412   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8413   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8414   case Intrinsic::ppc_vsx_xvcmpgesp_p:
8415   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8416     if (Subtarget.hasVSX()) {
8417       switch (IntrinsicID) {
8418       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8419         CompareOpc = 99;
8420         break;
8421       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8422         CompareOpc = 115;
8423         break;
8424       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8425         CompareOpc = 107;
8426         break;
8427       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8428         CompareOpc = 67;
8429         break;
8430       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8431         CompareOpc = 83;
8432         break;
8433       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8434         CompareOpc = 75;
8435         break;
8436       }
8437       isDot = true;
8438     } else
8439       return false;
8440     break;
8441 
8442   // Normal Comparisons.
8443   case Intrinsic::ppc_altivec_vcmpbfp:
8444     CompareOpc = 966;
8445     break;
8446   case Intrinsic::ppc_altivec_vcmpeqfp:
8447     CompareOpc = 198;
8448     break;
8449   case Intrinsic::ppc_altivec_vcmpequb:
8450     CompareOpc = 6;
8451     break;
8452   case Intrinsic::ppc_altivec_vcmpequh:
8453     CompareOpc = 70;
8454     break;
8455   case Intrinsic::ppc_altivec_vcmpequw:
8456     CompareOpc = 134;
8457     break;
8458   case Intrinsic::ppc_altivec_vcmpequd:
8459     if (Subtarget.hasP8Altivec())
8460       CompareOpc = 199;
8461     else
8462       return false;
8463     break;
8464   case Intrinsic::ppc_altivec_vcmpneb:
8465   case Intrinsic::ppc_altivec_vcmpneh:
8466   case Intrinsic::ppc_altivec_vcmpnew:
8467   case Intrinsic::ppc_altivec_vcmpnezb:
8468   case Intrinsic::ppc_altivec_vcmpnezh:
8469   case Intrinsic::ppc_altivec_vcmpnezw:
8470     if (Subtarget.hasP9Altivec())
8471       switch (IntrinsicID) {
8472       default:
8473         llvm_unreachable("Unknown comparison intrinsic.");
8474       case Intrinsic::ppc_altivec_vcmpneb:
8475         CompareOpc = 7;
8476         break;
8477       case Intrinsic::ppc_altivec_vcmpneh:
8478         CompareOpc = 71;
8479         break;
8480       case Intrinsic::ppc_altivec_vcmpnew:
8481         CompareOpc = 135;
8482         break;
8483       case Intrinsic::ppc_altivec_vcmpnezb:
8484         CompareOpc = 263;
8485         break;
8486       case Intrinsic::ppc_altivec_vcmpnezh:
8487         CompareOpc = 327;
8488         break;
8489       case Intrinsic::ppc_altivec_vcmpnezw:
8490         CompareOpc = 391;
8491         break;
8492       }
8493     else
8494       return false;
8495     break;
8496   case Intrinsic::ppc_altivec_vcmpgefp:
8497     CompareOpc = 454;
8498     break;
8499   case Intrinsic::ppc_altivec_vcmpgtfp:
8500     CompareOpc = 710;
8501     break;
8502   case Intrinsic::ppc_altivec_vcmpgtsb:
8503     CompareOpc = 774;
8504     break;
8505   case Intrinsic::ppc_altivec_vcmpgtsh:
8506     CompareOpc = 838;
8507     break;
8508   case Intrinsic::ppc_altivec_vcmpgtsw:
8509     CompareOpc = 902;
8510     break;
8511   case Intrinsic::ppc_altivec_vcmpgtsd:
8512     if (Subtarget.hasP8Altivec())
8513       CompareOpc = 967;
8514     else
8515       return false;
8516     break;
8517   case Intrinsic::ppc_altivec_vcmpgtub:
8518     CompareOpc = 518;
8519     break;
8520   case Intrinsic::ppc_altivec_vcmpgtuh:
8521     CompareOpc = 582;
8522     break;
8523   case Intrinsic::ppc_altivec_vcmpgtuw:
8524     CompareOpc = 646;
8525     break;
8526   case Intrinsic::ppc_altivec_vcmpgtud:
8527     if (Subtarget.hasP8Altivec())
8528       CompareOpc = 711;
8529     else
8530       return false;
8531     break;
8532   }
8533   return true;
8534 }
8535 
8536 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8537 /// lower, do it, otherwise return null.
8538 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8539                                                    SelectionDAG &DAG) const {
8540   unsigned IntrinsicID =
8541     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8542 
8543   SDLoc dl(Op);
8544 
8545   if (IntrinsicID == Intrinsic::thread_pointer) {
8546     // Reads the thread pointer register, used for __builtin_thread_pointer.
8547     if (Subtarget.isPPC64())
8548       return DAG.getRegister(PPC::X13, MVT::i64);
8549     return DAG.getRegister(PPC::R2, MVT::i32);
8550   }
8551 
8552   // We are looking for absolute values here.
8553   // The idea is to try to fit one of two patterns:
8554   //  max (a, (0-a))  OR  max ((0-a), a)
8555   if (Subtarget.hasP9Vector() &&
8556       (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw ||
8557        IntrinsicID == Intrinsic::ppc_altivec_vmaxsh ||
8558        IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) {
8559     SDValue V1 = Op.getOperand(1);
8560     SDValue V2 = Op.getOperand(2);
8561     if (V1.getSimpleValueType() == V2.getSimpleValueType() &&
8562         (V1.getSimpleValueType() == MVT::v4i32 ||
8563          V1.getSimpleValueType() == MVT::v8i16 ||
8564          V1.getSimpleValueType() == MVT::v16i8)) {
8565       if ( V1.getOpcode() == ISD::SUB &&
8566            ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
8567            V1.getOperand(1) == V2 ) {
8568         // Generate the abs instruction with the operands
8569         return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2);
8570       }
8571 
8572       if ( V2.getOpcode() == ISD::SUB &&
8573            ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
8574            V2.getOperand(1) == V1 ) {
8575         // Generate the abs instruction with the operands
8576         return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1);
8577       }
8578     }
8579   }
8580 
8581   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8582   // opcode number of the comparison.
8583   int CompareOpc;
8584   bool isDot;
8585   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8586     return SDValue();    // Don't custom lower most intrinsics.
8587 
8588   // If this is a non-dot comparison, make the VCMP node and we are done.
8589   if (!isDot) {
8590     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8591                               Op.getOperand(1), Op.getOperand(2),
8592                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8593     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8594   }
8595 
8596   // Create the PPCISD altivec 'dot' comparison node.
8597   SDValue Ops[] = {
8598     Op.getOperand(2),  // LHS
8599     Op.getOperand(3),  // RHS
8600     DAG.getConstant(CompareOpc, dl, MVT::i32)
8601   };
8602   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8603   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8604 
8605   // Now that we have the comparison, emit a copy from the CR to a GPR.
8606   // This is flagged to the above dot comparison.
8607   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8608                                 DAG.getRegister(PPC::CR6, MVT::i32),
8609                                 CompNode.getValue(1));
8610 
8611   // Unpack the result based on how the target uses it.
8612   unsigned BitNo;   // Bit # of CR6.
8613   bool InvertBit;   // Invert result?
8614   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8615   default:  // Can't happen, don't crash on invalid number though.
8616   case 0:   // Return the value of the EQ bit of CR6.
8617     BitNo = 0; InvertBit = false;
8618     break;
8619   case 1:   // Return the inverted value of the EQ bit of CR6.
8620     BitNo = 0; InvertBit = true;
8621     break;
8622   case 2:   // Return the value of the LT bit of CR6.
8623     BitNo = 2; InvertBit = false;
8624     break;
8625   case 3:   // Return the inverted value of the LT bit of CR6.
8626     BitNo = 2; InvertBit = true;
8627     break;
8628   }
8629 
8630   // Shift the bit into the low position.
8631   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8632                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8633   // Isolate the bit.
8634   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8635                       DAG.getConstant(1, dl, MVT::i32));
8636 
8637   // If we are supposed to, toggle the bit.
8638   if (InvertBit)
8639     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8640                         DAG.getConstant(1, dl, MVT::i32));
8641   return Flags;
8642 }
8643 
8644 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8645                                                SelectionDAG &DAG) const {
8646   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
8647   // the beginning of the argument list.
8648   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
8649   SDLoc DL(Op);
8650   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
8651   case Intrinsic::ppc_cfence: {
8652     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
8653     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
8654     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
8655                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
8656                                                   Op.getOperand(ArgStart + 1)),
8657                                       Op.getOperand(0)),
8658                    0);
8659   }
8660   default:
8661     break;
8662   }
8663   return SDValue();
8664 }
8665 
8666 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
8667   // Check for a DIV with the same operands as this REM.
8668   for (auto UI : Op.getOperand(1)->uses()) {
8669     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
8670         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
8671       if (UI->getOperand(0) == Op.getOperand(0) &&
8672           UI->getOperand(1) == Op.getOperand(1))
8673         return SDValue();
8674   }
8675   return Op;
8676 }
8677 
8678 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8679                                                   SelectionDAG &DAG) const {
8680   SDLoc dl(Op);
8681   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8682   // instructions), but for smaller types, we need to first extend up to v2i32
8683   // before doing going farther.
8684   if (Op.getValueType() == MVT::v2i64) {
8685     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8686     if (ExtVT != MVT::v2i32) {
8687       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8688       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8689                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8690                                         ExtVT.getVectorElementType(), 4)));
8691       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8692       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8693                        DAG.getValueType(MVT::v2i32));
8694     }
8695 
8696     return Op;
8697   }
8698 
8699   return SDValue();
8700 }
8701 
8702 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8703                                                  SelectionDAG &DAG) const {
8704   SDLoc dl(Op);
8705   // Create a stack slot that is 16-byte aligned.
8706   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8707   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8708   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8709   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8710 
8711   // Store the input value into Value#0 of the stack slot.
8712   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8713                                MachinePointerInfo());
8714   // Load it out.
8715   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8716 }
8717 
8718 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8719                                                   SelectionDAG &DAG) const {
8720   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8721          "Should only be called for ISD::INSERT_VECTOR_ELT");
8722   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8723   // We have legal lowering for constant indices but not for variable ones.
8724   if (C)
8725     return Op;
8726   return SDValue();
8727 }
8728 
8729 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8730                                                    SelectionDAG &DAG) const {
8731   SDLoc dl(Op);
8732   SDNode *N = Op.getNode();
8733 
8734   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8735          "Unknown extract_vector_elt type");
8736 
8737   SDValue Value = N->getOperand(0);
8738 
8739   // The first part of this is like the store lowering except that we don't
8740   // need to track the chain.
8741 
8742   // The values are now known to be -1 (false) or 1 (true). To convert this
8743   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8744   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8745   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8746 
8747   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8748   // understand how to form the extending load.
8749   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8750 
8751   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8752 
8753   // Now convert to an integer and store.
8754   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8755     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8756     Value);
8757 
8758   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8759   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8760   MachinePointerInfo PtrInfo =
8761       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8762   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8763   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8764 
8765   SDValue StoreChain = DAG.getEntryNode();
8766   SDValue Ops[] = {StoreChain,
8767                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8768                    Value, FIdx};
8769   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8770 
8771   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8772     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8773 
8774   // Extract the value requested.
8775   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8776   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8777   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8778 
8779   SDValue IntVal =
8780       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8781 
8782   if (!Subtarget.useCRBits())
8783     return IntVal;
8784 
8785   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8786 }
8787 
8788 /// Lowering for QPX v4i1 loads
8789 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8790                                            SelectionDAG &DAG) const {
8791   SDLoc dl(Op);
8792   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8793   SDValue LoadChain = LN->getChain();
8794   SDValue BasePtr = LN->getBasePtr();
8795 
8796   if (Op.getValueType() == MVT::v4f64 ||
8797       Op.getValueType() == MVT::v4f32) {
8798     EVT MemVT = LN->getMemoryVT();
8799     unsigned Alignment = LN->getAlignment();
8800 
8801     // If this load is properly aligned, then it is legal.
8802     if (Alignment >= MemVT.getStoreSize())
8803       return Op;
8804 
8805     EVT ScalarVT = Op.getValueType().getScalarType(),
8806         ScalarMemVT = MemVT.getScalarType();
8807     unsigned Stride = ScalarMemVT.getStoreSize();
8808 
8809     SDValue Vals[4], LoadChains[4];
8810     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8811       SDValue Load;
8812       if (ScalarVT != ScalarMemVT)
8813         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8814                               BasePtr,
8815                               LN->getPointerInfo().getWithOffset(Idx * Stride),
8816                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8817                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
8818       else
8819         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8820                            LN->getPointerInfo().getWithOffset(Idx * Stride),
8821                            MinAlign(Alignment, Idx * Stride),
8822                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
8823 
8824       if (Idx == 0 && LN->isIndexed()) {
8825         assert(LN->getAddressingMode() == ISD::PRE_INC &&
8826                "Unknown addressing mode on vector load");
8827         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8828                                   LN->getAddressingMode());
8829       }
8830 
8831       Vals[Idx] = Load;
8832       LoadChains[Idx] = Load.getValue(1);
8833 
8834       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8835                             DAG.getConstant(Stride, dl,
8836                                             BasePtr.getValueType()));
8837     }
8838 
8839     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8840     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8841 
8842     if (LN->isIndexed()) {
8843       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8844       return DAG.getMergeValues(RetOps, dl);
8845     }
8846 
8847     SDValue RetOps[] = { Value, TF };
8848     return DAG.getMergeValues(RetOps, dl);
8849   }
8850 
8851   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8852   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8853 
8854   // To lower v4i1 from a byte array, we load the byte elements of the
8855   // vector and then reuse the BUILD_VECTOR logic.
8856 
8857   SDValue VectElmts[4], VectElmtChains[4];
8858   for (unsigned i = 0; i < 4; ++i) {
8859     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8860     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8861 
8862     VectElmts[i] = DAG.getExtLoad(
8863         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8864         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8865         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8866     VectElmtChains[i] = VectElmts[i].getValue(1);
8867   }
8868 
8869   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8870   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8871 
8872   SDValue RVals[] = { Value, LoadChain };
8873   return DAG.getMergeValues(RVals, dl);
8874 }
8875 
8876 /// Lowering for QPX v4i1 stores
8877 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8878                                             SelectionDAG &DAG) const {
8879   SDLoc dl(Op);
8880   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8881   SDValue StoreChain = SN->getChain();
8882   SDValue BasePtr = SN->getBasePtr();
8883   SDValue Value = SN->getValue();
8884 
8885   if (Value.getValueType() == MVT::v4f64 ||
8886       Value.getValueType() == MVT::v4f32) {
8887     EVT MemVT = SN->getMemoryVT();
8888     unsigned Alignment = SN->getAlignment();
8889 
8890     // If this store is properly aligned, then it is legal.
8891     if (Alignment >= MemVT.getStoreSize())
8892       return Op;
8893 
8894     EVT ScalarVT = Value.getValueType().getScalarType(),
8895         ScalarMemVT = MemVT.getScalarType();
8896     unsigned Stride = ScalarMemVT.getStoreSize();
8897 
8898     SDValue Stores[4];
8899     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8900       SDValue Ex = DAG.getNode(
8901           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8902           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8903       SDValue Store;
8904       if (ScalarVT != ScalarMemVT)
8905         Store =
8906             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8907                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8908                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8909                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8910       else
8911         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8912                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8913                              MinAlign(Alignment, Idx * Stride),
8914                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8915 
8916       if (Idx == 0 && SN->isIndexed()) {
8917         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8918                "Unknown addressing mode on vector store");
8919         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8920                                     SN->getAddressingMode());
8921       }
8922 
8923       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8924                             DAG.getConstant(Stride, dl,
8925                                             BasePtr.getValueType()));
8926       Stores[Idx] = Store;
8927     }
8928 
8929     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8930 
8931     if (SN->isIndexed()) {
8932       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8933       return DAG.getMergeValues(RetOps, dl);
8934     }
8935 
8936     return TF;
8937   }
8938 
8939   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8940   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8941 
8942   // The values are now known to be -1 (false) or 1 (true). To convert this
8943   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8944   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8945   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8946 
8947   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8948   // understand how to form the extending load.
8949   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8950 
8951   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8952 
8953   // Now convert to an integer and store.
8954   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8955     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8956     Value);
8957 
8958   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8959   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8960   MachinePointerInfo PtrInfo =
8961       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8962   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8963   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8964 
8965   SDValue Ops[] = {StoreChain,
8966                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8967                    Value, FIdx};
8968   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8969 
8970   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8971     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8972 
8973   // Move data into the byte array.
8974   SDValue Loads[4], LoadChains[4];
8975   for (unsigned i = 0; i < 4; ++i) {
8976     unsigned Offset = 4*i;
8977     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8978     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8979 
8980     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8981                            PtrInfo.getWithOffset(Offset));
8982     LoadChains[i] = Loads[i].getValue(1);
8983   }
8984 
8985   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8986 
8987   SDValue Stores[4];
8988   for (unsigned i = 0; i < 4; ++i) {
8989     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8990     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8991 
8992     Stores[i] = DAG.getTruncStore(
8993         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8994         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8995         SN->getAAInfo());
8996   }
8997 
8998   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8999 
9000   return StoreChain;
9001 }
9002 
9003 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9004   SDLoc dl(Op);
9005   if (Op.getValueType() == MVT::v4i32) {
9006     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9007 
9008     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9009     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9010 
9011     SDValue RHSSwap =   // = vrlw RHS, 16
9012       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9013 
9014     // Shrinkify inputs to v8i16.
9015     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9016     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9017     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9018 
9019     // Low parts multiplied together, generating 32-bit results (we ignore the
9020     // top parts).
9021     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9022                                         LHS, RHS, DAG, dl, MVT::v4i32);
9023 
9024     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9025                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9026     // Shift the high parts up 16 bits.
9027     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9028                               Neg16, DAG, dl);
9029     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9030   } else if (Op.getValueType() == MVT::v8i16) {
9031     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9032 
9033     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9034 
9035     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9036                             LHS, RHS, Zero, DAG, dl);
9037   } else if (Op.getValueType() == MVT::v16i8) {
9038     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9039     bool isLittleEndian = Subtarget.isLittleEndian();
9040 
9041     // Multiply the even 8-bit parts, producing 16-bit sums.
9042     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9043                                            LHS, RHS, DAG, dl, MVT::v8i16);
9044     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9045 
9046     // Multiply the odd 8-bit parts, producing 16-bit sums.
9047     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9048                                           LHS, RHS, DAG, dl, MVT::v8i16);
9049     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9050 
9051     // Merge the results together.  Because vmuleub and vmuloub are
9052     // instructions with a big-endian bias, we must reverse the
9053     // element numbering and reverse the meaning of "odd" and "even"
9054     // when generating little endian code.
9055     int Ops[16];
9056     for (unsigned i = 0; i != 8; ++i) {
9057       if (isLittleEndian) {
9058         Ops[i*2  ] = 2*i;
9059         Ops[i*2+1] = 2*i+16;
9060       } else {
9061         Ops[i*2  ] = 2*i+1;
9062         Ops[i*2+1] = 2*i+1+16;
9063       }
9064     }
9065     if (isLittleEndian)
9066       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9067     else
9068       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9069   } else {
9070     llvm_unreachable("Unknown mul to lower!");
9071   }
9072 }
9073 
9074 /// LowerOperation - Provide custom lowering hooks for some operations.
9075 ///
9076 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9077   switch (Op.getOpcode()) {
9078   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9079   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9080   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9081   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9082   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9083   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9084   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9085   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
9086   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
9087   case ISD::VASTART:
9088     return LowerVASTART(Op, DAG);
9089 
9090   case ISD::VAARG:
9091     return LowerVAARG(Op, DAG);
9092 
9093   case ISD::VACOPY:
9094     return LowerVACOPY(Op, DAG);
9095 
9096   case ISD::STACKRESTORE:
9097     return LowerSTACKRESTORE(Op, DAG);
9098 
9099   case ISD::DYNAMIC_STACKALLOC:
9100     return LowerDYNAMIC_STACKALLOC(Op, DAG);
9101 
9102   case ISD::GET_DYNAMIC_AREA_OFFSET:
9103     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9104 
9105   case ISD::EH_DWARF_CFA:
9106     return LowerEH_DWARF_CFA(Op, DAG);
9107 
9108   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
9109   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
9110 
9111   case ISD::LOAD:               return LowerLOAD(Op, DAG);
9112   case ISD::STORE:              return LowerSTORE(Op, DAG);
9113   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
9114   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
9115   case ISD::FP_TO_UINT:
9116   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
9117                                                       SDLoc(Op));
9118   case ISD::UINT_TO_FP:
9119   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
9120   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9121 
9122   // Lower 64-bit shifts.
9123   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
9124   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
9125   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
9126 
9127   // Vector-related lowering.
9128   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9129   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9130   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9131   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9132   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
9133   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9134   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9135   case ISD::MUL:                return LowerMUL(Op, DAG);
9136 
9137   // For counter-based loop handling.
9138   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
9139 
9140   // Frame & Return address.
9141   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9142   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9143 
9144   case ISD::INTRINSIC_VOID:
9145     return LowerINTRINSIC_VOID(Op, DAG);
9146   case ISD::SREM:
9147   case ISD::UREM:
9148     return LowerREM(Op, DAG);
9149   }
9150 }
9151 
9152 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9153                                            SmallVectorImpl<SDValue>&Results,
9154                                            SelectionDAG &DAG) const {
9155   SDLoc dl(N);
9156   switch (N->getOpcode()) {
9157   default:
9158     llvm_unreachable("Do not know how to custom type legalize this operation!");
9159   case ISD::READCYCLECOUNTER: {
9160     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9161     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9162 
9163     Results.push_back(RTB);
9164     Results.push_back(RTB.getValue(1));
9165     Results.push_back(RTB.getValue(2));
9166     break;
9167   }
9168   case ISD::INTRINSIC_W_CHAIN: {
9169     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9170         Intrinsic::ppc_is_decremented_ctr_nonzero)
9171       break;
9172 
9173     assert(N->getValueType(0) == MVT::i1 &&
9174            "Unexpected result type for CTR decrement intrinsic");
9175     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
9176                                  N->getValueType(0));
9177     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
9178     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
9179                                  N->getOperand(1));
9180 
9181     Results.push_back(NewInt);
9182     Results.push_back(NewInt.getValue(1));
9183     break;
9184   }
9185   case ISD::VAARG: {
9186     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
9187       return;
9188 
9189     EVT VT = N->getValueType(0);
9190 
9191     if (VT == MVT::i64) {
9192       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
9193 
9194       Results.push_back(NewNode);
9195       Results.push_back(NewNode.getValue(1));
9196     }
9197     return;
9198   }
9199   case ISD::FP_ROUND_INREG: {
9200     assert(N->getValueType(0) == MVT::ppcf128);
9201     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
9202     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
9203                              MVT::f64, N->getOperand(0),
9204                              DAG.getIntPtrConstant(0, dl));
9205     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
9206                              MVT::f64, N->getOperand(0),
9207                              DAG.getIntPtrConstant(1, dl));
9208 
9209     // Add the two halves of the long double in round-to-zero mode.
9210     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
9211 
9212     // We know the low half is about to be thrown away, so just use something
9213     // convenient.
9214     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
9215                                 FPreg, FPreg));
9216     return;
9217   }
9218   case ISD::FP_TO_SINT:
9219   case ISD::FP_TO_UINT:
9220     // LowerFP_TO_INT() can only handle f32 and f64.
9221     if (N->getOperand(0).getValueType() == MVT::ppcf128)
9222       return;
9223     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
9224     return;
9225   }
9226 }
9227 
9228 //===----------------------------------------------------------------------===//
9229 //  Other Lowering Code
9230 //===----------------------------------------------------------------------===//
9231 
9232 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
9233   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9234   Function *Func = Intrinsic::getDeclaration(M, Id);
9235   return Builder.CreateCall(Func, {});
9236 }
9237 
9238 // The mappings for emitLeading/TrailingFence is taken from
9239 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
9240 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
9241                                                  Instruction *Inst,
9242                                                  AtomicOrdering Ord) const {
9243   if (Ord == AtomicOrdering::SequentiallyConsistent)
9244     return callIntrinsic(Builder, Intrinsic::ppc_sync);
9245   if (isReleaseOrStronger(Ord))
9246     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9247   return nullptr;
9248 }
9249 
9250 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
9251                                                   Instruction *Inst,
9252                                                   AtomicOrdering Ord) const {
9253   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
9254     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
9255     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
9256     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
9257     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
9258       return Builder.CreateCall(
9259           Intrinsic::getDeclaration(
9260               Builder.GetInsertBlock()->getParent()->getParent(),
9261               Intrinsic::ppc_cfence, {Inst->getType()}),
9262           {Inst});
9263     // FIXME: Can use isync for rmw operation.
9264     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9265   }
9266   return nullptr;
9267 }
9268 
9269 MachineBasicBlock *
9270 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
9271                                     unsigned AtomicSize,
9272                                     unsigned BinOpcode,
9273                                     unsigned CmpOpcode,
9274                                     unsigned CmpPred) const {
9275   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9276   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9277 
9278   auto LoadMnemonic = PPC::LDARX;
9279   auto StoreMnemonic = PPC::STDCX;
9280   switch (AtomicSize) {
9281   default:
9282     llvm_unreachable("Unexpected size of atomic entity");
9283   case 1:
9284     LoadMnemonic = PPC::LBARX;
9285     StoreMnemonic = PPC::STBCX;
9286     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9287     break;
9288   case 2:
9289     LoadMnemonic = PPC::LHARX;
9290     StoreMnemonic = PPC::STHCX;
9291     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9292     break;
9293   case 4:
9294     LoadMnemonic = PPC::LWARX;
9295     StoreMnemonic = PPC::STWCX;
9296     break;
9297   case 8:
9298     LoadMnemonic = PPC::LDARX;
9299     StoreMnemonic = PPC::STDCX;
9300     break;
9301   }
9302 
9303   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9304   MachineFunction *F = BB->getParent();
9305   MachineFunction::iterator It = ++BB->getIterator();
9306 
9307   unsigned dest = MI.getOperand(0).getReg();
9308   unsigned ptrA = MI.getOperand(1).getReg();
9309   unsigned ptrB = MI.getOperand(2).getReg();
9310   unsigned incr = MI.getOperand(3).getReg();
9311   DebugLoc dl = MI.getDebugLoc();
9312 
9313   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9314   MachineBasicBlock *loop2MBB =
9315     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9316   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9317   F->insert(It, loopMBB);
9318   if (CmpOpcode)
9319     F->insert(It, loop2MBB);
9320   F->insert(It, exitMBB);
9321   exitMBB->splice(exitMBB->begin(), BB,
9322                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9323   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9324 
9325   MachineRegisterInfo &RegInfo = F->getRegInfo();
9326   unsigned TmpReg = (!BinOpcode) ? incr :
9327     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
9328                                            : &PPC::GPRCRegClass);
9329 
9330   //  thisMBB:
9331   //   ...
9332   //   fallthrough --> loopMBB
9333   BB->addSuccessor(loopMBB);
9334 
9335   //  loopMBB:
9336   //   l[wd]arx dest, ptr
9337   //   add r0, dest, incr
9338   //   st[wd]cx. r0, ptr
9339   //   bne- loopMBB
9340   //   fallthrough --> exitMBB
9341 
9342   // For max/min...
9343   //  loopMBB:
9344   //   l[wd]arx dest, ptr
9345   //   cmpl?[wd] incr, dest
9346   //   bgt exitMBB
9347   //  loop2MBB:
9348   //   st[wd]cx. dest, ptr
9349   //   bne- loopMBB
9350   //   fallthrough --> exitMBB
9351 
9352   BB = loopMBB;
9353   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9354     .addReg(ptrA).addReg(ptrB);
9355   if (BinOpcode)
9356     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
9357   if (CmpOpcode) {
9358     // Signed comparisons of byte or halfword values must be sign-extended.
9359     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
9360       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9361       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
9362               ExtReg).addReg(dest);
9363       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9364         .addReg(incr).addReg(ExtReg);
9365     } else
9366       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9367         .addReg(incr).addReg(dest);
9368 
9369     BuildMI(BB, dl, TII->get(PPC::BCC))
9370       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9371     BB->addSuccessor(loop2MBB);
9372     BB->addSuccessor(exitMBB);
9373     BB = loop2MBB;
9374   }
9375   BuildMI(BB, dl, TII->get(StoreMnemonic))
9376     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
9377   BuildMI(BB, dl, TII->get(PPC::BCC))
9378     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9379   BB->addSuccessor(loopMBB);
9380   BB->addSuccessor(exitMBB);
9381 
9382   //  exitMBB:
9383   //   ...
9384   BB = exitMBB;
9385   return BB;
9386 }
9387 
9388 MachineBasicBlock *
9389 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
9390                                             MachineBasicBlock *BB,
9391                                             bool is8bit, // operation
9392                                             unsigned BinOpcode,
9393                                             unsigned CmpOpcode,
9394                                             unsigned CmpPred) const {
9395   // If we support part-word atomic mnemonics, just use them
9396   if (Subtarget.hasPartwordAtomics())
9397     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
9398                             CmpOpcode, CmpPred);
9399 
9400   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9401   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9402   // In 64 bit mode we have to use 64 bits for addresses, even though the
9403   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
9404   // registers without caring whether they're 32 or 64, but here we're
9405   // doing actual arithmetic on the addresses.
9406   bool is64bit = Subtarget.isPPC64();
9407   bool isLittleEndian = Subtarget.isLittleEndian();
9408   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9409 
9410   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9411   MachineFunction *F = BB->getParent();
9412   MachineFunction::iterator It = ++BB->getIterator();
9413 
9414   unsigned dest = MI.getOperand(0).getReg();
9415   unsigned ptrA = MI.getOperand(1).getReg();
9416   unsigned ptrB = MI.getOperand(2).getReg();
9417   unsigned incr = MI.getOperand(3).getReg();
9418   DebugLoc dl = MI.getDebugLoc();
9419 
9420   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9421   MachineBasicBlock *loop2MBB =
9422     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9423   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9424   F->insert(It, loopMBB);
9425   if (CmpOpcode)
9426     F->insert(It, loop2MBB);
9427   F->insert(It, exitMBB);
9428   exitMBB->splice(exitMBB->begin(), BB,
9429                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9430   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9431 
9432   MachineRegisterInfo &RegInfo = F->getRegInfo();
9433   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9434                                           : &PPC::GPRCRegClass;
9435   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9436   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9437   unsigned ShiftReg =
9438     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9439   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
9440   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9441   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9442   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9443   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9444   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
9445   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9446   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9447   unsigned Ptr1Reg;
9448   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
9449 
9450   //  thisMBB:
9451   //   ...
9452   //   fallthrough --> loopMBB
9453   BB->addSuccessor(loopMBB);
9454 
9455   // The 4-byte load must be aligned, while a char or short may be
9456   // anywhere in the word.  Hence all this nasty bookkeeping code.
9457   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9458   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9459   //   xori shift, shift1, 24 [16]
9460   //   rlwinm ptr, ptr1, 0, 0, 29
9461   //   slw incr2, incr, shift
9462   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9463   //   slw mask, mask2, shift
9464   //  loopMBB:
9465   //   lwarx tmpDest, ptr
9466   //   add tmp, tmpDest, incr2
9467   //   andc tmp2, tmpDest, mask
9468   //   and tmp3, tmp, mask
9469   //   or tmp4, tmp3, tmp2
9470   //   stwcx. tmp4, ptr
9471   //   bne- loopMBB
9472   //   fallthrough --> exitMBB
9473   //   srw dest, tmpDest, shift
9474   if (ptrA != ZeroReg) {
9475     Ptr1Reg = RegInfo.createVirtualRegister(RC);
9476     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9477       .addReg(ptrA).addReg(ptrB);
9478   } else {
9479     Ptr1Reg = ptrB;
9480   }
9481   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9482       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9483   if (!isLittleEndian)
9484     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9485         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9486   if (is64bit)
9487     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9488       .addReg(Ptr1Reg).addImm(0).addImm(61);
9489   else
9490     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9491       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9492   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9493       .addReg(incr).addReg(ShiftReg);
9494   if (is8bit)
9495     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9496   else {
9497     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9498     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9499   }
9500   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9501       .addReg(Mask2Reg).addReg(ShiftReg);
9502 
9503   BB = loopMBB;
9504   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9505     .addReg(ZeroReg).addReg(PtrReg);
9506   if (BinOpcode)
9507     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9508       .addReg(Incr2Reg).addReg(TmpDestReg);
9509   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9510     .addReg(TmpDestReg).addReg(MaskReg);
9511   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9512     .addReg(TmpReg).addReg(MaskReg);
9513   if (CmpOpcode) {
9514     // For unsigned comparisons, we can directly compare the shifted values.
9515     // For signed comparisons we shift and sign extend.
9516     unsigned SReg = RegInfo.createVirtualRegister(RC);
9517     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9518       .addReg(TmpDestReg).addReg(MaskReg);
9519     unsigned ValueReg = SReg;
9520     unsigned CmpReg = Incr2Reg;
9521     if (CmpOpcode == PPC::CMPW) {
9522       ValueReg = RegInfo.createVirtualRegister(RC);
9523       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9524         .addReg(SReg).addReg(ShiftReg);
9525       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9526       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9527         .addReg(ValueReg);
9528       ValueReg = ValueSReg;
9529       CmpReg = incr;
9530     }
9531     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9532       .addReg(CmpReg).addReg(ValueReg);
9533     BuildMI(BB, dl, TII->get(PPC::BCC))
9534       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9535     BB->addSuccessor(loop2MBB);
9536     BB->addSuccessor(exitMBB);
9537     BB = loop2MBB;
9538   }
9539   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9540     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9541   BuildMI(BB, dl, TII->get(PPC::STWCX))
9542     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9543   BuildMI(BB, dl, TII->get(PPC::BCC))
9544     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9545   BB->addSuccessor(loopMBB);
9546   BB->addSuccessor(exitMBB);
9547 
9548   //  exitMBB:
9549   //   ...
9550   BB = exitMBB;
9551   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9552     .addReg(ShiftReg);
9553   return BB;
9554 }
9555 
9556 llvm::MachineBasicBlock *
9557 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9558                                     MachineBasicBlock *MBB) const {
9559   DebugLoc DL = MI.getDebugLoc();
9560   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9561   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9562 
9563   MachineFunction *MF = MBB->getParent();
9564   MachineRegisterInfo &MRI = MF->getRegInfo();
9565 
9566   const BasicBlock *BB = MBB->getBasicBlock();
9567   MachineFunction::iterator I = ++MBB->getIterator();
9568 
9569   // Memory Reference
9570   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9571   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9572 
9573   unsigned DstReg = MI.getOperand(0).getReg();
9574   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9575   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9576   unsigned mainDstReg = MRI.createVirtualRegister(RC);
9577   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9578 
9579   MVT PVT = getPointerTy(MF->getDataLayout());
9580   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9581          "Invalid Pointer Size!");
9582   // For v = setjmp(buf), we generate
9583   //
9584   // thisMBB:
9585   //  SjLjSetup mainMBB
9586   //  bl mainMBB
9587   //  v_restore = 1
9588   //  b sinkMBB
9589   //
9590   // mainMBB:
9591   //  buf[LabelOffset] = LR
9592   //  v_main = 0
9593   //
9594   // sinkMBB:
9595   //  v = phi(main, restore)
9596   //
9597 
9598   MachineBasicBlock *thisMBB = MBB;
9599   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9600   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9601   MF->insert(I, mainMBB);
9602   MF->insert(I, sinkMBB);
9603 
9604   MachineInstrBuilder MIB;
9605 
9606   // Transfer the remainder of BB and its successor edges to sinkMBB.
9607   sinkMBB->splice(sinkMBB->begin(), MBB,
9608                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9609   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9610 
9611   // Note that the structure of the jmp_buf used here is not compatible
9612   // with that used by libc, and is not designed to be. Specifically, it
9613   // stores only those 'reserved' registers that LLVM does not otherwise
9614   // understand how to spill. Also, by convention, by the time this
9615   // intrinsic is called, Clang has already stored the frame address in the
9616   // first slot of the buffer and stack address in the third. Following the
9617   // X86 target code, we'll store the jump address in the second slot. We also
9618   // need to save the TOC pointer (R2) to handle jumps between shared
9619   // libraries, and that will be stored in the fourth slot. The thread
9620   // identifier (R13) is not affected.
9621 
9622   // thisMBB:
9623   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9624   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9625   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9626 
9627   // Prepare IP either in reg.
9628   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9629   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9630   unsigned BufReg = MI.getOperand(1).getReg();
9631 
9632   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9633     setUsesTOCBasePtr(*MBB->getParent());
9634     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9635             .addReg(PPC::X2)
9636             .addImm(TOCOffset)
9637             .addReg(BufReg);
9638     MIB.setMemRefs(MMOBegin, MMOEnd);
9639   }
9640 
9641   // Naked functions never have a base pointer, and so we use r1. For all
9642   // other functions, this decision must be delayed until during PEI.
9643   unsigned BaseReg;
9644   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9645     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9646   else
9647     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9648 
9649   MIB = BuildMI(*thisMBB, MI, DL,
9650                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9651             .addReg(BaseReg)
9652             .addImm(BPOffset)
9653             .addReg(BufReg);
9654   MIB.setMemRefs(MMOBegin, MMOEnd);
9655 
9656   // Setup
9657   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9658   MIB.addRegMask(TRI->getNoPreservedMask());
9659 
9660   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9661 
9662   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9663           .addMBB(mainMBB);
9664   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9665 
9666   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9667   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9668 
9669   // mainMBB:
9670   //  mainDstReg = 0
9671   MIB =
9672       BuildMI(mainMBB, DL,
9673               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9674 
9675   // Store IP
9676   if (Subtarget.isPPC64()) {
9677     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9678             .addReg(LabelReg)
9679             .addImm(LabelOffset)
9680             .addReg(BufReg);
9681   } else {
9682     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9683             .addReg(LabelReg)
9684             .addImm(LabelOffset)
9685             .addReg(BufReg);
9686   }
9687 
9688   MIB.setMemRefs(MMOBegin, MMOEnd);
9689 
9690   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9691   mainMBB->addSuccessor(sinkMBB);
9692 
9693   // sinkMBB:
9694   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9695           TII->get(PPC::PHI), DstReg)
9696     .addReg(mainDstReg).addMBB(mainMBB)
9697     .addReg(restoreDstReg).addMBB(thisMBB);
9698 
9699   MI.eraseFromParent();
9700   return sinkMBB;
9701 }
9702 
9703 MachineBasicBlock *
9704 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9705                                      MachineBasicBlock *MBB) const {
9706   DebugLoc DL = MI.getDebugLoc();
9707   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9708 
9709   MachineFunction *MF = MBB->getParent();
9710   MachineRegisterInfo &MRI = MF->getRegInfo();
9711 
9712   // Memory Reference
9713   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9714   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9715 
9716   MVT PVT = getPointerTy(MF->getDataLayout());
9717   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9718          "Invalid Pointer Size!");
9719 
9720   const TargetRegisterClass *RC =
9721     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9722   unsigned Tmp = MRI.createVirtualRegister(RC);
9723   // Since FP is only updated here but NOT referenced, it's treated as GPR.
9724   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9725   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9726   unsigned BP =
9727       (PVT == MVT::i64)
9728           ? PPC::X30
9729           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9730                                                               : PPC::R30);
9731 
9732   MachineInstrBuilder MIB;
9733 
9734   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9735   const int64_t SPOffset    = 2 * PVT.getStoreSize();
9736   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9737   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9738 
9739   unsigned BufReg = MI.getOperand(0).getReg();
9740 
9741   // Reload FP (the jumped-to function may not have had a
9742   // frame pointer, and if so, then its r31 will be restored
9743   // as necessary).
9744   if (PVT == MVT::i64) {
9745     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9746             .addImm(0)
9747             .addReg(BufReg);
9748   } else {
9749     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9750             .addImm(0)
9751             .addReg(BufReg);
9752   }
9753   MIB.setMemRefs(MMOBegin, MMOEnd);
9754 
9755   // Reload IP
9756   if (PVT == MVT::i64) {
9757     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9758             .addImm(LabelOffset)
9759             .addReg(BufReg);
9760   } else {
9761     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9762             .addImm(LabelOffset)
9763             .addReg(BufReg);
9764   }
9765   MIB.setMemRefs(MMOBegin, MMOEnd);
9766 
9767   // Reload SP
9768   if (PVT == MVT::i64) {
9769     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9770             .addImm(SPOffset)
9771             .addReg(BufReg);
9772   } else {
9773     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9774             .addImm(SPOffset)
9775             .addReg(BufReg);
9776   }
9777   MIB.setMemRefs(MMOBegin, MMOEnd);
9778 
9779   // Reload BP
9780   if (PVT == MVT::i64) {
9781     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9782             .addImm(BPOffset)
9783             .addReg(BufReg);
9784   } else {
9785     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9786             .addImm(BPOffset)
9787             .addReg(BufReg);
9788   }
9789   MIB.setMemRefs(MMOBegin, MMOEnd);
9790 
9791   // Reload TOC
9792   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9793     setUsesTOCBasePtr(*MBB->getParent());
9794     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9795             .addImm(TOCOffset)
9796             .addReg(BufReg);
9797 
9798     MIB.setMemRefs(MMOBegin, MMOEnd);
9799   }
9800 
9801   // Jump
9802   BuildMI(*MBB, MI, DL,
9803           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9804   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9805 
9806   MI.eraseFromParent();
9807   return MBB;
9808 }
9809 
9810 MachineBasicBlock *
9811 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9812                                                MachineBasicBlock *BB) const {
9813   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9814       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9815     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9816         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9817       // Call lowering should have added an r2 operand to indicate a dependence
9818       // on the TOC base pointer value. It can't however, because there is no
9819       // way to mark the dependence as implicit there, and so the stackmap code
9820       // will confuse it with a regular operand. Instead, add the dependence
9821       // here.
9822       setUsesTOCBasePtr(*BB->getParent());
9823       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9824     }
9825 
9826     return emitPatchPoint(MI, BB);
9827   }
9828 
9829   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9830       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9831     return emitEHSjLjSetJmp(MI, BB);
9832   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9833              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9834     return emitEHSjLjLongJmp(MI, BB);
9835   }
9836 
9837   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9838 
9839   // To "insert" these instructions we actually have to insert their
9840   // control-flow patterns.
9841   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9842   MachineFunction::iterator It = ++BB->getIterator();
9843 
9844   MachineFunction *F = BB->getParent();
9845 
9846   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9847        MI.getOpcode() == PPC::SELECT_CC_I8 ||
9848        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9849     SmallVector<MachineOperand, 2> Cond;
9850     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9851         MI.getOpcode() == PPC::SELECT_CC_I8)
9852       Cond.push_back(MI.getOperand(4));
9853     else
9854       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9855     Cond.push_back(MI.getOperand(1));
9856 
9857     DebugLoc dl = MI.getDebugLoc();
9858     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9859                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9860   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9861              MI.getOpcode() == PPC::SELECT_CC_I8 ||
9862              MI.getOpcode() == PPC::SELECT_CC_F4 ||
9863              MI.getOpcode() == PPC::SELECT_CC_F8 ||
9864              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9865              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9866              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9867              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9868              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9869              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9870              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9871              MI.getOpcode() == PPC::SELECT_I4 ||
9872              MI.getOpcode() == PPC::SELECT_I8 ||
9873              MI.getOpcode() == PPC::SELECT_F4 ||
9874              MI.getOpcode() == PPC::SELECT_F8 ||
9875              MI.getOpcode() == PPC::SELECT_QFRC ||
9876              MI.getOpcode() == PPC::SELECT_QSRC ||
9877              MI.getOpcode() == PPC::SELECT_QBRC ||
9878              MI.getOpcode() == PPC::SELECT_VRRC ||
9879              MI.getOpcode() == PPC::SELECT_VSFRC ||
9880              MI.getOpcode() == PPC::SELECT_VSSRC ||
9881              MI.getOpcode() == PPC::SELECT_VSRC) {
9882     // The incoming instruction knows the destination vreg to set, the
9883     // condition code register to branch on, the true/false values to
9884     // select between, and a branch opcode to use.
9885 
9886     //  thisMBB:
9887     //  ...
9888     //   TrueVal = ...
9889     //   cmpTY ccX, r1, r2
9890     //   bCC copy1MBB
9891     //   fallthrough --> copy0MBB
9892     MachineBasicBlock *thisMBB = BB;
9893     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9894     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9895     DebugLoc dl = MI.getDebugLoc();
9896     F->insert(It, copy0MBB);
9897     F->insert(It, sinkMBB);
9898 
9899     // Transfer the remainder of BB and its successor edges to sinkMBB.
9900     sinkMBB->splice(sinkMBB->begin(), BB,
9901                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9902     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9903 
9904     // Next, add the true and fallthrough blocks as its successors.
9905     BB->addSuccessor(copy0MBB);
9906     BB->addSuccessor(sinkMBB);
9907 
9908     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9909         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9910         MI.getOpcode() == PPC::SELECT_QFRC ||
9911         MI.getOpcode() == PPC::SELECT_QSRC ||
9912         MI.getOpcode() == PPC::SELECT_QBRC ||
9913         MI.getOpcode() == PPC::SELECT_VRRC ||
9914         MI.getOpcode() == PPC::SELECT_VSFRC ||
9915         MI.getOpcode() == PPC::SELECT_VSSRC ||
9916         MI.getOpcode() == PPC::SELECT_VSRC) {
9917       BuildMI(BB, dl, TII->get(PPC::BC))
9918           .addReg(MI.getOperand(1).getReg())
9919           .addMBB(sinkMBB);
9920     } else {
9921       unsigned SelectPred = MI.getOperand(4).getImm();
9922       BuildMI(BB, dl, TII->get(PPC::BCC))
9923           .addImm(SelectPred)
9924           .addReg(MI.getOperand(1).getReg())
9925           .addMBB(sinkMBB);
9926     }
9927 
9928     //  copy0MBB:
9929     //   %FalseValue = ...
9930     //   # fallthrough to sinkMBB
9931     BB = copy0MBB;
9932 
9933     // Update machine-CFG edges
9934     BB->addSuccessor(sinkMBB);
9935 
9936     //  sinkMBB:
9937     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9938     //  ...
9939     BB = sinkMBB;
9940     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9941         .addReg(MI.getOperand(3).getReg())
9942         .addMBB(copy0MBB)
9943         .addReg(MI.getOperand(2).getReg())
9944         .addMBB(thisMBB);
9945   } else if (MI.getOpcode() == PPC::ReadTB) {
9946     // To read the 64-bit time-base register on a 32-bit target, we read the
9947     // two halves. Should the counter have wrapped while it was being read, we
9948     // need to try again.
9949     // ...
9950     // readLoop:
9951     // mfspr Rx,TBU # load from TBU
9952     // mfspr Ry,TB  # load from TB
9953     // mfspr Rz,TBU # load from TBU
9954     // cmpw crX,Rx,Rz # check if 'old'='new'
9955     // bne readLoop   # branch if they're not equal
9956     // ...
9957 
9958     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9959     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9960     DebugLoc dl = MI.getDebugLoc();
9961     F->insert(It, readMBB);
9962     F->insert(It, sinkMBB);
9963 
9964     // Transfer the remainder of BB and its successor edges to sinkMBB.
9965     sinkMBB->splice(sinkMBB->begin(), BB,
9966                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9967     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9968 
9969     BB->addSuccessor(readMBB);
9970     BB = readMBB;
9971 
9972     MachineRegisterInfo &RegInfo = F->getRegInfo();
9973     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9974     unsigned LoReg = MI.getOperand(0).getReg();
9975     unsigned HiReg = MI.getOperand(1).getReg();
9976 
9977     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9978     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9979     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9980 
9981     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9982 
9983     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9984       .addReg(HiReg).addReg(ReadAgainReg);
9985     BuildMI(BB, dl, TII->get(PPC::BCC))
9986       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9987 
9988     BB->addSuccessor(readMBB);
9989     BB->addSuccessor(sinkMBB);
9990   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9991     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9992   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9993     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9994   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9995     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9996   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9997     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9998 
9999   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10000     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10001   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10002     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10003   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10004     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10005   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10006     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10007 
10008   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10009     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10010   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10011     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10012   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10013     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10014   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10015     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10016 
10017   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10018     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10019   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10020     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10021   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10022     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10023   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10024     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10025 
10026   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10027     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10028   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10029     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10030   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10031     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10032   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10033     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10034 
10035   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10036     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10037   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10038     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10039   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10040     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10041   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10042     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10043 
10044   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10045     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10046   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10047     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10048   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10049     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10050   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10051     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10052 
10053   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10054     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10055   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10056     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10057   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10058     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10059   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10060     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10061 
10062   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10063     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10064   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10065     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10066   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10067     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10068   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10069     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10070 
10071   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10072     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10073   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10074     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10075   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10076     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10077   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10078     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10079 
10080   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10081     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10082   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10083     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10084   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10085     BB = EmitAtomicBinary(MI, BB, 4, 0);
10086   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10087     BB = EmitAtomicBinary(MI, BB, 8, 0);
10088   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10089            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10090            (Subtarget.hasPartwordAtomics() &&
10091             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10092            (Subtarget.hasPartwordAtomics() &&
10093             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10094     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10095 
10096     auto LoadMnemonic = PPC::LDARX;
10097     auto StoreMnemonic = PPC::STDCX;
10098     switch (MI.getOpcode()) {
10099     default:
10100       llvm_unreachable("Compare and swap of unknown size");
10101     case PPC::ATOMIC_CMP_SWAP_I8:
10102       LoadMnemonic = PPC::LBARX;
10103       StoreMnemonic = PPC::STBCX;
10104       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10105       break;
10106     case PPC::ATOMIC_CMP_SWAP_I16:
10107       LoadMnemonic = PPC::LHARX;
10108       StoreMnemonic = PPC::STHCX;
10109       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10110       break;
10111     case PPC::ATOMIC_CMP_SWAP_I32:
10112       LoadMnemonic = PPC::LWARX;
10113       StoreMnemonic = PPC::STWCX;
10114       break;
10115     case PPC::ATOMIC_CMP_SWAP_I64:
10116       LoadMnemonic = PPC::LDARX;
10117       StoreMnemonic = PPC::STDCX;
10118       break;
10119     }
10120     unsigned dest = MI.getOperand(0).getReg();
10121     unsigned ptrA = MI.getOperand(1).getReg();
10122     unsigned ptrB = MI.getOperand(2).getReg();
10123     unsigned oldval = MI.getOperand(3).getReg();
10124     unsigned newval = MI.getOperand(4).getReg();
10125     DebugLoc dl = MI.getDebugLoc();
10126 
10127     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10128     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10129     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10130     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10131     F->insert(It, loop1MBB);
10132     F->insert(It, loop2MBB);
10133     F->insert(It, midMBB);
10134     F->insert(It, exitMBB);
10135     exitMBB->splice(exitMBB->begin(), BB,
10136                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10137     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10138 
10139     //  thisMBB:
10140     //   ...
10141     //   fallthrough --> loopMBB
10142     BB->addSuccessor(loop1MBB);
10143 
10144     // loop1MBB:
10145     //   l[bhwd]arx dest, ptr
10146     //   cmp[wd] dest, oldval
10147     //   bne- midMBB
10148     // loop2MBB:
10149     //   st[bhwd]cx. newval, ptr
10150     //   bne- loopMBB
10151     //   b exitBB
10152     // midMBB:
10153     //   st[bhwd]cx. dest, ptr
10154     // exitBB:
10155     BB = loop1MBB;
10156     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10157       .addReg(ptrA).addReg(ptrB);
10158     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
10159       .addReg(oldval).addReg(dest);
10160     BuildMI(BB, dl, TII->get(PPC::BCC))
10161       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10162     BB->addSuccessor(loop2MBB);
10163     BB->addSuccessor(midMBB);
10164 
10165     BB = loop2MBB;
10166     BuildMI(BB, dl, TII->get(StoreMnemonic))
10167       .addReg(newval).addReg(ptrA).addReg(ptrB);
10168     BuildMI(BB, dl, TII->get(PPC::BCC))
10169       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10170     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10171     BB->addSuccessor(loop1MBB);
10172     BB->addSuccessor(exitMBB);
10173 
10174     BB = midMBB;
10175     BuildMI(BB, dl, TII->get(StoreMnemonic))
10176       .addReg(dest).addReg(ptrA).addReg(ptrB);
10177     BB->addSuccessor(exitMBB);
10178 
10179     //  exitMBB:
10180     //   ...
10181     BB = exitMBB;
10182   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
10183              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
10184     // We must use 64-bit registers for addresses when targeting 64-bit,
10185     // since we're actually doing arithmetic on them.  Other registers
10186     // can be 32-bit.
10187     bool is64bit = Subtarget.isPPC64();
10188     bool isLittleEndian = Subtarget.isLittleEndian();
10189     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
10190 
10191     unsigned dest = MI.getOperand(0).getReg();
10192     unsigned ptrA = MI.getOperand(1).getReg();
10193     unsigned ptrB = MI.getOperand(2).getReg();
10194     unsigned oldval = MI.getOperand(3).getReg();
10195     unsigned newval = MI.getOperand(4).getReg();
10196     DebugLoc dl = MI.getDebugLoc();
10197 
10198     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10199     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10200     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10201     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10202     F->insert(It, loop1MBB);
10203     F->insert(It, loop2MBB);
10204     F->insert(It, midMBB);
10205     F->insert(It, exitMBB);
10206     exitMBB->splice(exitMBB->begin(), BB,
10207                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10208     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10209 
10210     MachineRegisterInfo &RegInfo = F->getRegInfo();
10211     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
10212                                             : &PPC::GPRCRegClass;
10213     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10214     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
10215     unsigned ShiftReg =
10216       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
10217     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
10218     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
10219     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
10220     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
10221     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
10222     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
10223     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
10224     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
10225     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
10226     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
10227     unsigned Ptr1Reg;
10228     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
10229     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10230     //  thisMBB:
10231     //   ...
10232     //   fallthrough --> loopMBB
10233     BB->addSuccessor(loop1MBB);
10234 
10235     // The 4-byte load must be aligned, while a char or short may be
10236     // anywhere in the word.  Hence all this nasty bookkeeping code.
10237     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10238     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10239     //   xori shift, shift1, 24 [16]
10240     //   rlwinm ptr, ptr1, 0, 0, 29
10241     //   slw newval2, newval, shift
10242     //   slw oldval2, oldval,shift
10243     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10244     //   slw mask, mask2, shift
10245     //   and newval3, newval2, mask
10246     //   and oldval3, oldval2, mask
10247     // loop1MBB:
10248     //   lwarx tmpDest, ptr
10249     //   and tmp, tmpDest, mask
10250     //   cmpw tmp, oldval3
10251     //   bne- midMBB
10252     // loop2MBB:
10253     //   andc tmp2, tmpDest, mask
10254     //   or tmp4, tmp2, newval3
10255     //   stwcx. tmp4, ptr
10256     //   bne- loop1MBB
10257     //   b exitBB
10258     // midMBB:
10259     //   stwcx. tmpDest, ptr
10260     // exitBB:
10261     //   srw dest, tmpDest, shift
10262     if (ptrA != ZeroReg) {
10263       Ptr1Reg = RegInfo.createVirtualRegister(RC);
10264       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10265         .addReg(ptrA).addReg(ptrB);
10266     } else {
10267       Ptr1Reg = ptrB;
10268     }
10269     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
10270         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
10271     if (!isLittleEndian)
10272       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
10273           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
10274     if (is64bit)
10275       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10276         .addReg(Ptr1Reg).addImm(0).addImm(61);
10277     else
10278       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10279         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
10280     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
10281         .addReg(newval).addReg(ShiftReg);
10282     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
10283         .addReg(oldval).addReg(ShiftReg);
10284     if (is8bit)
10285       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10286     else {
10287       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10288       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10289         .addReg(Mask3Reg).addImm(65535);
10290     }
10291     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10292         .addReg(Mask2Reg).addReg(ShiftReg);
10293     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
10294         .addReg(NewVal2Reg).addReg(MaskReg);
10295     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
10296         .addReg(OldVal2Reg).addReg(MaskReg);
10297 
10298     BB = loop1MBB;
10299     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10300         .addReg(ZeroReg).addReg(PtrReg);
10301     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
10302         .addReg(TmpDestReg).addReg(MaskReg);
10303     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
10304         .addReg(TmpReg).addReg(OldVal3Reg);
10305     BuildMI(BB, dl, TII->get(PPC::BCC))
10306         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10307     BB->addSuccessor(loop2MBB);
10308     BB->addSuccessor(midMBB);
10309 
10310     BB = loop2MBB;
10311     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
10312         .addReg(TmpDestReg).addReg(MaskReg);
10313     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
10314         .addReg(Tmp2Reg).addReg(NewVal3Reg);
10315     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
10316         .addReg(ZeroReg).addReg(PtrReg);
10317     BuildMI(BB, dl, TII->get(PPC::BCC))
10318       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10319     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10320     BB->addSuccessor(loop1MBB);
10321     BB->addSuccessor(exitMBB);
10322 
10323     BB = midMBB;
10324     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
10325       .addReg(ZeroReg).addReg(PtrReg);
10326     BB->addSuccessor(exitMBB);
10327 
10328     //  exitMBB:
10329     //   ...
10330     BB = exitMBB;
10331     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
10332       .addReg(ShiftReg);
10333   } else if (MI.getOpcode() == PPC::FADDrtz) {
10334     // This pseudo performs an FADD with rounding mode temporarily forced
10335     // to round-to-zero.  We emit this via custom inserter since the FPSCR
10336     // is not modeled at the SelectionDAG level.
10337     unsigned Dest = MI.getOperand(0).getReg();
10338     unsigned Src1 = MI.getOperand(1).getReg();
10339     unsigned Src2 = MI.getOperand(2).getReg();
10340     DebugLoc dl = MI.getDebugLoc();
10341 
10342     MachineRegisterInfo &RegInfo = F->getRegInfo();
10343     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
10344 
10345     // Save FPSCR value.
10346     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
10347 
10348     // Set rounding mode to round-to-zero.
10349     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
10350     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
10351 
10352     // Perform addition.
10353     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
10354 
10355     // Restore FPSCR value.
10356     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
10357   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10358              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
10359              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10360              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
10361     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10362                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
10363                           ? PPC::ANDIo8
10364                           : PPC::ANDIo;
10365     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10366                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
10367 
10368     MachineRegisterInfo &RegInfo = F->getRegInfo();
10369     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
10370                                                   &PPC::GPRCRegClass :
10371                                                   &PPC::G8RCRegClass);
10372 
10373     DebugLoc dl = MI.getDebugLoc();
10374     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
10375         .addReg(MI.getOperand(1).getReg())
10376         .addImm(1);
10377     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
10378             MI.getOperand(0).getReg())
10379         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
10380   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
10381     DebugLoc Dl = MI.getDebugLoc();
10382     MachineRegisterInfo &RegInfo = F->getRegInfo();
10383     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10384     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
10385     return BB;
10386   } else {
10387     llvm_unreachable("Unexpected instr type to insert");
10388   }
10389 
10390   MI.eraseFromParent(); // The pseudo instruction is gone now.
10391   return BB;
10392 }
10393 
10394 //===----------------------------------------------------------------------===//
10395 // Target Optimization Hooks
10396 //===----------------------------------------------------------------------===//
10397 
10398 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
10399   // For the estimates, convergence is quadratic, so we essentially double the
10400   // number of digits correct after every iteration. For both FRE and FRSQRTE,
10401   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
10402   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
10403   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
10404   if (VT.getScalarType() == MVT::f64)
10405     RefinementSteps++;
10406   return RefinementSteps;
10407 }
10408 
10409 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
10410                                            int Enabled, int &RefinementSteps,
10411                                            bool &UseOneConstNR,
10412                                            bool Reciprocal) const {
10413   EVT VT = Operand.getValueType();
10414   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
10415       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
10416       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10417       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10418       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10419       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10420     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10421       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10422 
10423     UseOneConstNR = true;
10424     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
10425   }
10426   return SDValue();
10427 }
10428 
10429 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
10430                                             int Enabled,
10431                                             int &RefinementSteps) const {
10432   EVT VT = Operand.getValueType();
10433   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
10434       (VT == MVT::f64 && Subtarget.hasFRE()) ||
10435       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10436       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10437       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10438       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10439     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10440       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10441     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
10442   }
10443   return SDValue();
10444 }
10445 
10446 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
10447   // Note: This functionality is used only when unsafe-fp-math is enabled, and
10448   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
10449   // enabled for division), this functionality is redundant with the default
10450   // combiner logic (once the division -> reciprocal/multiply transformation
10451   // has taken place). As a result, this matters more for older cores than for
10452   // newer ones.
10453 
10454   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10455   // reciprocal if there are two or more FDIVs (for embedded cores with only
10456   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10457   switch (Subtarget.getDarwinDirective()) {
10458   default:
10459     return 3;
10460   case PPC::DIR_440:
10461   case PPC::DIR_A2:
10462   case PPC::DIR_E500mc:
10463   case PPC::DIR_E5500:
10464     return 2;
10465   }
10466 }
10467 
10468 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10469 // collapsed, and so we need to look through chains of them.
10470 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10471                                      int64_t& Offset, SelectionDAG &DAG) {
10472   if (DAG.isBaseWithConstantOffset(Loc)) {
10473     Base = Loc.getOperand(0);
10474     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10475 
10476     // The base might itself be a base plus an offset, and if so, accumulate
10477     // that as well.
10478     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10479   }
10480 }
10481 
10482 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10483                             unsigned Bytes, int Dist,
10484                             SelectionDAG &DAG) {
10485   if (VT.getSizeInBits() / 8 != Bytes)
10486     return false;
10487 
10488   SDValue BaseLoc = Base->getBasePtr();
10489   if (Loc.getOpcode() == ISD::FrameIndex) {
10490     if (BaseLoc.getOpcode() != ISD::FrameIndex)
10491       return false;
10492     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10493     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
10494     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10495     int FS  = MFI.getObjectSize(FI);
10496     int BFS = MFI.getObjectSize(BFI);
10497     if (FS != BFS || FS != (int)Bytes) return false;
10498     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10499   }
10500 
10501   SDValue Base1 = Loc, Base2 = BaseLoc;
10502   int64_t Offset1 = 0, Offset2 = 0;
10503   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10504   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10505   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10506     return true;
10507 
10508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10509   const GlobalValue *GV1 = nullptr;
10510   const GlobalValue *GV2 = nullptr;
10511   Offset1 = 0;
10512   Offset2 = 0;
10513   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10514   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10515   if (isGA1 && isGA2 && GV1 == GV2)
10516     return Offset1 == (Offset2 + Dist*Bytes);
10517   return false;
10518 }
10519 
10520 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10521 // not enforce equality of the chain operands.
10522 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10523                             unsigned Bytes, int Dist,
10524                             SelectionDAG &DAG) {
10525   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10526     EVT VT = LS->getMemoryVT();
10527     SDValue Loc = LS->getBasePtr();
10528     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10529   }
10530 
10531   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10532     EVT VT;
10533     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10534     default: return false;
10535     case Intrinsic::ppc_qpx_qvlfd:
10536     case Intrinsic::ppc_qpx_qvlfda:
10537       VT = MVT::v4f64;
10538       break;
10539     case Intrinsic::ppc_qpx_qvlfs:
10540     case Intrinsic::ppc_qpx_qvlfsa:
10541       VT = MVT::v4f32;
10542       break;
10543     case Intrinsic::ppc_qpx_qvlfcd:
10544     case Intrinsic::ppc_qpx_qvlfcda:
10545       VT = MVT::v2f64;
10546       break;
10547     case Intrinsic::ppc_qpx_qvlfcs:
10548     case Intrinsic::ppc_qpx_qvlfcsa:
10549       VT = MVT::v2f32;
10550       break;
10551     case Intrinsic::ppc_qpx_qvlfiwa:
10552     case Intrinsic::ppc_qpx_qvlfiwz:
10553     case Intrinsic::ppc_altivec_lvx:
10554     case Intrinsic::ppc_altivec_lvxl:
10555     case Intrinsic::ppc_vsx_lxvw4x:
10556     case Intrinsic::ppc_vsx_lxvw4x_be:
10557       VT = MVT::v4i32;
10558       break;
10559     case Intrinsic::ppc_vsx_lxvd2x:
10560     case Intrinsic::ppc_vsx_lxvd2x_be:
10561       VT = MVT::v2f64;
10562       break;
10563     case Intrinsic::ppc_altivec_lvebx:
10564       VT = MVT::i8;
10565       break;
10566     case Intrinsic::ppc_altivec_lvehx:
10567       VT = MVT::i16;
10568       break;
10569     case Intrinsic::ppc_altivec_lvewx:
10570       VT = MVT::i32;
10571       break;
10572     }
10573 
10574     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10575   }
10576 
10577   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10578     EVT VT;
10579     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10580     default: return false;
10581     case Intrinsic::ppc_qpx_qvstfd:
10582     case Intrinsic::ppc_qpx_qvstfda:
10583       VT = MVT::v4f64;
10584       break;
10585     case Intrinsic::ppc_qpx_qvstfs:
10586     case Intrinsic::ppc_qpx_qvstfsa:
10587       VT = MVT::v4f32;
10588       break;
10589     case Intrinsic::ppc_qpx_qvstfcd:
10590     case Intrinsic::ppc_qpx_qvstfcda:
10591       VT = MVT::v2f64;
10592       break;
10593     case Intrinsic::ppc_qpx_qvstfcs:
10594     case Intrinsic::ppc_qpx_qvstfcsa:
10595       VT = MVT::v2f32;
10596       break;
10597     case Intrinsic::ppc_qpx_qvstfiw:
10598     case Intrinsic::ppc_qpx_qvstfiwa:
10599     case Intrinsic::ppc_altivec_stvx:
10600     case Intrinsic::ppc_altivec_stvxl:
10601     case Intrinsic::ppc_vsx_stxvw4x:
10602       VT = MVT::v4i32;
10603       break;
10604     case Intrinsic::ppc_vsx_stxvd2x:
10605       VT = MVT::v2f64;
10606       break;
10607     case Intrinsic::ppc_vsx_stxvw4x_be:
10608       VT = MVT::v4i32;
10609       break;
10610     case Intrinsic::ppc_vsx_stxvd2x_be:
10611       VT = MVT::v2f64;
10612       break;
10613     case Intrinsic::ppc_altivec_stvebx:
10614       VT = MVT::i8;
10615       break;
10616     case Intrinsic::ppc_altivec_stvehx:
10617       VT = MVT::i16;
10618       break;
10619     case Intrinsic::ppc_altivec_stvewx:
10620       VT = MVT::i32;
10621       break;
10622     }
10623 
10624     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10625   }
10626 
10627   return false;
10628 }
10629 
10630 // Return true is there is a nearyby consecutive load to the one provided
10631 // (regardless of alignment). We search up and down the chain, looking though
10632 // token factors and other loads (but nothing else). As a result, a true result
10633 // indicates that it is safe to create a new consecutive load adjacent to the
10634 // load provided.
10635 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10636   SDValue Chain = LD->getChain();
10637   EVT VT = LD->getMemoryVT();
10638 
10639   SmallSet<SDNode *, 16> LoadRoots;
10640   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10641   SmallSet<SDNode *, 16> Visited;
10642 
10643   // First, search up the chain, branching to follow all token-factor operands.
10644   // If we find a consecutive load, then we're done, otherwise, record all
10645   // nodes just above the top-level loads and token factors.
10646   while (!Queue.empty()) {
10647     SDNode *ChainNext = Queue.pop_back_val();
10648     if (!Visited.insert(ChainNext).second)
10649       continue;
10650 
10651     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10652       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10653         return true;
10654 
10655       if (!Visited.count(ChainLD->getChain().getNode()))
10656         Queue.push_back(ChainLD->getChain().getNode());
10657     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10658       for (const SDUse &O : ChainNext->ops())
10659         if (!Visited.count(O.getNode()))
10660           Queue.push_back(O.getNode());
10661     } else
10662       LoadRoots.insert(ChainNext);
10663   }
10664 
10665   // Second, search down the chain, starting from the top-level nodes recorded
10666   // in the first phase. These top-level nodes are the nodes just above all
10667   // loads and token factors. Starting with their uses, recursively look though
10668   // all loads (just the chain uses) and token factors to find a consecutive
10669   // load.
10670   Visited.clear();
10671   Queue.clear();
10672 
10673   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10674        IE = LoadRoots.end(); I != IE; ++I) {
10675     Queue.push_back(*I);
10676 
10677     while (!Queue.empty()) {
10678       SDNode *LoadRoot = Queue.pop_back_val();
10679       if (!Visited.insert(LoadRoot).second)
10680         continue;
10681 
10682       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10683         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10684           return true;
10685 
10686       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10687            UE = LoadRoot->use_end(); UI != UE; ++UI)
10688         if (((isa<MemSDNode>(*UI) &&
10689             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10690             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10691           Queue.push_back(*UI);
10692     }
10693   }
10694 
10695   return false;
10696 }
10697 
10698 /// This function is called when we have proved that a SETCC node can be replaced
10699 /// by subtraction (and other supporting instructions) so that the result of
10700 /// comparison is kept in a GPR instead of CR. This function is purely for
10701 /// codegen purposes and has some flags to guide the codegen process.
10702 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10703                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10704   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10705 
10706   // Zero extend the operands to the largest legal integer. Originally, they
10707   // must be of a strictly smaller size.
10708   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10709                          DAG.getConstant(Size, DL, MVT::i32));
10710   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10711                          DAG.getConstant(Size, DL, MVT::i32));
10712 
10713   // Swap if needed. Depends on the condition code.
10714   if (Swap)
10715     std::swap(Op0, Op1);
10716 
10717   // Subtract extended integers.
10718   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10719 
10720   // Move the sign bit to the least significant position and zero out the rest.
10721   // Now the least significant bit carries the result of original comparison.
10722   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10723                              DAG.getConstant(Size - 1, DL, MVT::i32));
10724   auto Final = Shifted;
10725 
10726   // Complement the result if needed. Based on the condition code.
10727   if (Complement)
10728     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10729                         DAG.getConstant(1, DL, MVT::i64));
10730 
10731   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10732 }
10733 
10734 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10735                                                   DAGCombinerInfo &DCI) const {
10736   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10737 
10738   SelectionDAG &DAG = DCI.DAG;
10739   SDLoc DL(N);
10740 
10741   // Size of integers being compared has a critical role in the following
10742   // analysis, so we prefer to do this when all types are legal.
10743   if (!DCI.isAfterLegalizeVectorOps())
10744     return SDValue();
10745 
10746   // If all users of SETCC extend its value to a legal integer type
10747   // then we replace SETCC with a subtraction
10748   for (SDNode::use_iterator UI = N->use_begin(),
10749        UE = N->use_end(); UI != UE; ++UI) {
10750     if (UI->getOpcode() != ISD::ZERO_EXTEND)
10751       return SDValue();
10752   }
10753 
10754   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10755   auto OpSize = N->getOperand(0).getValueSizeInBits();
10756 
10757   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10758 
10759   if (OpSize < Size) {
10760     switch (CC) {
10761     default: break;
10762     case ISD::SETULT:
10763       return generateEquivalentSub(N, Size, false, false, DL, DAG);
10764     case ISD::SETULE:
10765       return generateEquivalentSub(N, Size, true, true, DL, DAG);
10766     case ISD::SETUGT:
10767       return generateEquivalentSub(N, Size, false, true, DL, DAG);
10768     case ISD::SETUGE:
10769       return generateEquivalentSub(N, Size, true, false, DL, DAG);
10770     }
10771   }
10772 
10773   return SDValue();
10774 }
10775 
10776 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10777                                                   DAGCombinerInfo &DCI) const {
10778   SelectionDAG &DAG = DCI.DAG;
10779   SDLoc dl(N);
10780 
10781   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10782   // If we're tracking CR bits, we need to be careful that we don't have:
10783   //   trunc(binary-ops(zext(x), zext(y)))
10784   // or
10785   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10786   // such that we're unnecessarily moving things into GPRs when it would be
10787   // better to keep them in CR bits.
10788 
10789   // Note that trunc here can be an actual i1 trunc, or can be the effective
10790   // truncation that comes from a setcc or select_cc.
10791   if (N->getOpcode() == ISD::TRUNCATE &&
10792       N->getValueType(0) != MVT::i1)
10793     return SDValue();
10794 
10795   if (N->getOperand(0).getValueType() != MVT::i32 &&
10796       N->getOperand(0).getValueType() != MVT::i64)
10797     return SDValue();
10798 
10799   if (N->getOpcode() == ISD::SETCC ||
10800       N->getOpcode() == ISD::SELECT_CC) {
10801     // If we're looking at a comparison, then we need to make sure that the
10802     // high bits (all except for the first) don't matter the result.
10803     ISD::CondCode CC =
10804       cast<CondCodeSDNode>(N->getOperand(
10805         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10806     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10807 
10808     if (ISD::isSignedIntSetCC(CC)) {
10809       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10810           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10811         return SDValue();
10812     } else if (ISD::isUnsignedIntSetCC(CC)) {
10813       if (!DAG.MaskedValueIsZero(N->getOperand(0),
10814                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10815           !DAG.MaskedValueIsZero(N->getOperand(1),
10816                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
10817         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10818                                              : SDValue());
10819     } else {
10820       // This is neither a signed nor an unsigned comparison, just make sure
10821       // that the high bits are equal.
10822       KnownBits Op1Known, Op2Known;
10823       DAG.computeKnownBits(N->getOperand(0), Op1Known);
10824       DAG.computeKnownBits(N->getOperand(1), Op2Known);
10825 
10826       // We don't really care about what is known about the first bit (if
10827       // anything), so clear it in all masks prior to comparing them.
10828       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
10829       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
10830 
10831       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
10832         return SDValue();
10833     }
10834   }
10835 
10836   // We now know that the higher-order bits are irrelevant, we just need to
10837   // make sure that all of the intermediate operations are bit operations, and
10838   // all inputs are extensions.
10839   if (N->getOperand(0).getOpcode() != ISD::AND &&
10840       N->getOperand(0).getOpcode() != ISD::OR  &&
10841       N->getOperand(0).getOpcode() != ISD::XOR &&
10842       N->getOperand(0).getOpcode() != ISD::SELECT &&
10843       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10844       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10845       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10846       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10847       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10848     return SDValue();
10849 
10850   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10851       N->getOperand(1).getOpcode() != ISD::AND &&
10852       N->getOperand(1).getOpcode() != ISD::OR  &&
10853       N->getOperand(1).getOpcode() != ISD::XOR &&
10854       N->getOperand(1).getOpcode() != ISD::SELECT &&
10855       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10856       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10857       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10858       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10859       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10860     return SDValue();
10861 
10862   SmallVector<SDValue, 4> Inputs;
10863   SmallVector<SDValue, 8> BinOps, PromOps;
10864   SmallPtrSet<SDNode *, 16> Visited;
10865 
10866   for (unsigned i = 0; i < 2; ++i) {
10867     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10868           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10869           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10870           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10871         isa<ConstantSDNode>(N->getOperand(i)))
10872       Inputs.push_back(N->getOperand(i));
10873     else
10874       BinOps.push_back(N->getOperand(i));
10875 
10876     if (N->getOpcode() == ISD::TRUNCATE)
10877       break;
10878   }
10879 
10880   // Visit all inputs, collect all binary operations (and, or, xor and
10881   // select) that are all fed by extensions.
10882   while (!BinOps.empty()) {
10883     SDValue BinOp = BinOps.back();
10884     BinOps.pop_back();
10885 
10886     if (!Visited.insert(BinOp.getNode()).second)
10887       continue;
10888 
10889     PromOps.push_back(BinOp);
10890 
10891     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10892       // The condition of the select is not promoted.
10893       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10894         continue;
10895       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10896         continue;
10897 
10898       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10899             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10900             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10901            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10902           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10903         Inputs.push_back(BinOp.getOperand(i));
10904       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10905                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10906                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10907                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10908                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10909                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10910                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10911                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10912                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10913         BinOps.push_back(BinOp.getOperand(i));
10914       } else {
10915         // We have an input that is not an extension or another binary
10916         // operation; we'll abort this transformation.
10917         return SDValue();
10918       }
10919     }
10920   }
10921 
10922   // Make sure that this is a self-contained cluster of operations (which
10923   // is not quite the same thing as saying that everything has only one
10924   // use).
10925   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10926     if (isa<ConstantSDNode>(Inputs[i]))
10927       continue;
10928 
10929     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10930                               UE = Inputs[i].getNode()->use_end();
10931          UI != UE; ++UI) {
10932       SDNode *User = *UI;
10933       if (User != N && !Visited.count(User))
10934         return SDValue();
10935 
10936       // Make sure that we're not going to promote the non-output-value
10937       // operand(s) or SELECT or SELECT_CC.
10938       // FIXME: Although we could sometimes handle this, and it does occur in
10939       // practice that one of the condition inputs to the select is also one of
10940       // the outputs, we currently can't deal with this.
10941       if (User->getOpcode() == ISD::SELECT) {
10942         if (User->getOperand(0) == Inputs[i])
10943           return SDValue();
10944       } else if (User->getOpcode() == ISD::SELECT_CC) {
10945         if (User->getOperand(0) == Inputs[i] ||
10946             User->getOperand(1) == Inputs[i])
10947           return SDValue();
10948       }
10949     }
10950   }
10951 
10952   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10953     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10954                               UE = PromOps[i].getNode()->use_end();
10955          UI != UE; ++UI) {
10956       SDNode *User = *UI;
10957       if (User != N && !Visited.count(User))
10958         return SDValue();
10959 
10960       // Make sure that we're not going to promote the non-output-value
10961       // operand(s) or SELECT or SELECT_CC.
10962       // FIXME: Although we could sometimes handle this, and it does occur in
10963       // practice that one of the condition inputs to the select is also one of
10964       // the outputs, we currently can't deal with this.
10965       if (User->getOpcode() == ISD::SELECT) {
10966         if (User->getOperand(0) == PromOps[i])
10967           return SDValue();
10968       } else if (User->getOpcode() == ISD::SELECT_CC) {
10969         if (User->getOperand(0) == PromOps[i] ||
10970             User->getOperand(1) == PromOps[i])
10971           return SDValue();
10972       }
10973     }
10974   }
10975 
10976   // Replace all inputs with the extension operand.
10977   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10978     // Constants may have users outside the cluster of to-be-promoted nodes,
10979     // and so we need to replace those as we do the promotions.
10980     if (isa<ConstantSDNode>(Inputs[i]))
10981       continue;
10982     else
10983       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10984   }
10985 
10986   std::list<HandleSDNode> PromOpHandles;
10987   for (auto &PromOp : PromOps)
10988     PromOpHandles.emplace_back(PromOp);
10989 
10990   // Replace all operations (these are all the same, but have a different
10991   // (i1) return type). DAG.getNode will validate that the types of
10992   // a binary operator match, so go through the list in reverse so that
10993   // we've likely promoted both operands first. Any intermediate truncations or
10994   // extensions disappear.
10995   while (!PromOpHandles.empty()) {
10996     SDValue PromOp = PromOpHandles.back().getValue();
10997     PromOpHandles.pop_back();
10998 
10999     if (PromOp.getOpcode() == ISD::TRUNCATE ||
11000         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
11001         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
11002         PromOp.getOpcode() == ISD::ANY_EXTEND) {
11003       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
11004           PromOp.getOperand(0).getValueType() != MVT::i1) {
11005         // The operand is not yet ready (see comment below).
11006         PromOpHandles.emplace_front(PromOp);
11007         continue;
11008       }
11009 
11010       SDValue RepValue = PromOp.getOperand(0);
11011       if (isa<ConstantSDNode>(RepValue))
11012         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
11013 
11014       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
11015       continue;
11016     }
11017 
11018     unsigned C;
11019     switch (PromOp.getOpcode()) {
11020     default:             C = 0; break;
11021     case ISD::SELECT:    C = 1; break;
11022     case ISD::SELECT_CC: C = 2; break;
11023     }
11024 
11025     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11026          PromOp.getOperand(C).getValueType() != MVT::i1) ||
11027         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11028          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
11029       // The to-be-promoted operands of this node have not yet been
11030       // promoted (this should be rare because we're going through the
11031       // list backward, but if one of the operands has several users in
11032       // this cluster of to-be-promoted nodes, it is possible).
11033       PromOpHandles.emplace_front(PromOp);
11034       continue;
11035     }
11036 
11037     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11038                                 PromOp.getNode()->op_end());
11039 
11040     // If there are any constant inputs, make sure they're replaced now.
11041     for (unsigned i = 0; i < 2; ++i)
11042       if (isa<ConstantSDNode>(Ops[C+i]))
11043         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
11044 
11045     DAG.ReplaceAllUsesOfValueWith(PromOp,
11046       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
11047   }
11048 
11049   // Now we're left with the initial truncation itself.
11050   if (N->getOpcode() == ISD::TRUNCATE)
11051     return N->getOperand(0);
11052 
11053   // Otherwise, this is a comparison. The operands to be compared have just
11054   // changed type (to i1), but everything else is the same.
11055   return SDValue(N, 0);
11056 }
11057 
11058 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
11059                                                   DAGCombinerInfo &DCI) const {
11060   SelectionDAG &DAG = DCI.DAG;
11061   SDLoc dl(N);
11062 
11063   // If we're tracking CR bits, we need to be careful that we don't have:
11064   //   zext(binary-ops(trunc(x), trunc(y)))
11065   // or
11066   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
11067   // such that we're unnecessarily moving things into CR bits that can more
11068   // efficiently stay in GPRs. Note that if we're not certain that the high
11069   // bits are set as required by the final extension, we still may need to do
11070   // some masking to get the proper behavior.
11071 
11072   // This same functionality is important on PPC64 when dealing with
11073   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
11074   // the return values of functions. Because it is so similar, it is handled
11075   // here as well.
11076 
11077   if (N->getValueType(0) != MVT::i32 &&
11078       N->getValueType(0) != MVT::i64)
11079     return SDValue();
11080 
11081   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
11082         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
11083     return SDValue();
11084 
11085   if (N->getOperand(0).getOpcode() != ISD::AND &&
11086       N->getOperand(0).getOpcode() != ISD::OR  &&
11087       N->getOperand(0).getOpcode() != ISD::XOR &&
11088       N->getOperand(0).getOpcode() != ISD::SELECT &&
11089       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
11090     return SDValue();
11091 
11092   SmallVector<SDValue, 4> Inputs;
11093   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
11094   SmallPtrSet<SDNode *, 16> Visited;
11095 
11096   // Visit all inputs, collect all binary operations (and, or, xor and
11097   // select) that are all fed by truncations.
11098   while (!BinOps.empty()) {
11099     SDValue BinOp = BinOps.back();
11100     BinOps.pop_back();
11101 
11102     if (!Visited.insert(BinOp.getNode()).second)
11103       continue;
11104 
11105     PromOps.push_back(BinOp);
11106 
11107     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11108       // The condition of the select is not promoted.
11109       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11110         continue;
11111       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11112         continue;
11113 
11114       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11115           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11116         Inputs.push_back(BinOp.getOperand(i));
11117       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11118                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11119                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11120                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11121                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
11122         BinOps.push_back(BinOp.getOperand(i));
11123       } else {
11124         // We have an input that is not a truncation or another binary
11125         // operation; we'll abort this transformation.
11126         return SDValue();
11127       }
11128     }
11129   }
11130 
11131   // The operands of a select that must be truncated when the select is
11132   // promoted because the operand is actually part of the to-be-promoted set.
11133   DenseMap<SDNode *, EVT> SelectTruncOp[2];
11134 
11135   // Make sure that this is a self-contained cluster of operations (which
11136   // is not quite the same thing as saying that everything has only one
11137   // use).
11138   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11139     if (isa<ConstantSDNode>(Inputs[i]))
11140       continue;
11141 
11142     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11143                               UE = Inputs[i].getNode()->use_end();
11144          UI != UE; ++UI) {
11145       SDNode *User = *UI;
11146       if (User != N && !Visited.count(User))
11147         return SDValue();
11148 
11149       // If we're going to promote the non-output-value operand(s) or SELECT or
11150       // SELECT_CC, record them for truncation.
11151       if (User->getOpcode() == ISD::SELECT) {
11152         if (User->getOperand(0) == Inputs[i])
11153           SelectTruncOp[0].insert(std::make_pair(User,
11154                                     User->getOperand(0).getValueType()));
11155       } else if (User->getOpcode() == ISD::SELECT_CC) {
11156         if (User->getOperand(0) == Inputs[i])
11157           SelectTruncOp[0].insert(std::make_pair(User,
11158                                     User->getOperand(0).getValueType()));
11159         if (User->getOperand(1) == Inputs[i])
11160           SelectTruncOp[1].insert(std::make_pair(User,
11161                                     User->getOperand(1).getValueType()));
11162       }
11163     }
11164   }
11165 
11166   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11167     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11168                               UE = PromOps[i].getNode()->use_end();
11169          UI != UE; ++UI) {
11170       SDNode *User = *UI;
11171       if (User != N && !Visited.count(User))
11172         return SDValue();
11173 
11174       // If we're going to promote the non-output-value operand(s) or SELECT or
11175       // SELECT_CC, record them for truncation.
11176       if (User->getOpcode() == ISD::SELECT) {
11177         if (User->getOperand(0) == PromOps[i])
11178           SelectTruncOp[0].insert(std::make_pair(User,
11179                                     User->getOperand(0).getValueType()));
11180       } else if (User->getOpcode() == ISD::SELECT_CC) {
11181         if (User->getOperand(0) == PromOps[i])
11182           SelectTruncOp[0].insert(std::make_pair(User,
11183                                     User->getOperand(0).getValueType()));
11184         if (User->getOperand(1) == PromOps[i])
11185           SelectTruncOp[1].insert(std::make_pair(User,
11186                                     User->getOperand(1).getValueType()));
11187       }
11188     }
11189   }
11190 
11191   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
11192   bool ReallyNeedsExt = false;
11193   if (N->getOpcode() != ISD::ANY_EXTEND) {
11194     // If all of the inputs are not already sign/zero extended, then
11195     // we'll still need to do that at the end.
11196     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11197       if (isa<ConstantSDNode>(Inputs[i]))
11198         continue;
11199 
11200       unsigned OpBits =
11201         Inputs[i].getOperand(0).getValueSizeInBits();
11202       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
11203 
11204       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
11205            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
11206                                   APInt::getHighBitsSet(OpBits,
11207                                                         OpBits-PromBits))) ||
11208           (N->getOpcode() == ISD::SIGN_EXTEND &&
11209            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
11210              (OpBits-(PromBits-1)))) {
11211         ReallyNeedsExt = true;
11212         break;
11213       }
11214     }
11215   }
11216 
11217   // Replace all inputs, either with the truncation operand, or a
11218   // truncation or extension to the final output type.
11219   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11220     // Constant inputs need to be replaced with the to-be-promoted nodes that
11221     // use them because they might have users outside of the cluster of
11222     // promoted nodes.
11223     if (isa<ConstantSDNode>(Inputs[i]))
11224       continue;
11225 
11226     SDValue InSrc = Inputs[i].getOperand(0);
11227     if (Inputs[i].getValueType() == N->getValueType(0))
11228       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
11229     else if (N->getOpcode() == ISD::SIGN_EXTEND)
11230       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11231         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
11232     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11233       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11234         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
11235     else
11236       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11237         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
11238   }
11239 
11240   std::list<HandleSDNode> PromOpHandles;
11241   for (auto &PromOp : PromOps)
11242     PromOpHandles.emplace_back(PromOp);
11243 
11244   // Replace all operations (these are all the same, but have a different
11245   // (promoted) return type). DAG.getNode will validate that the types of
11246   // a binary operator match, so go through the list in reverse so that
11247   // we've likely promoted both operands first.
11248   while (!PromOpHandles.empty()) {
11249     SDValue PromOp = PromOpHandles.back().getValue();
11250     PromOpHandles.pop_back();
11251 
11252     unsigned C;
11253     switch (PromOp.getOpcode()) {
11254     default:             C = 0; break;
11255     case ISD::SELECT:    C = 1; break;
11256     case ISD::SELECT_CC: C = 2; break;
11257     }
11258 
11259     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11260          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
11261         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11262          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
11263       // The to-be-promoted operands of this node have not yet been
11264       // promoted (this should be rare because we're going through the
11265       // list backward, but if one of the operands has several users in
11266       // this cluster of to-be-promoted nodes, it is possible).
11267       PromOpHandles.emplace_front(PromOp);
11268       continue;
11269     }
11270 
11271     // For SELECT and SELECT_CC nodes, we do a similar check for any
11272     // to-be-promoted comparison inputs.
11273     if (PromOp.getOpcode() == ISD::SELECT ||
11274         PromOp.getOpcode() == ISD::SELECT_CC) {
11275       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
11276            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
11277           (SelectTruncOp[1].count(PromOp.getNode()) &&
11278            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
11279         PromOpHandles.emplace_front(PromOp);
11280         continue;
11281       }
11282     }
11283 
11284     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11285                                 PromOp.getNode()->op_end());
11286 
11287     // If this node has constant inputs, then they'll need to be promoted here.
11288     for (unsigned i = 0; i < 2; ++i) {
11289       if (!isa<ConstantSDNode>(Ops[C+i]))
11290         continue;
11291       if (Ops[C+i].getValueType() == N->getValueType(0))
11292         continue;
11293 
11294       if (N->getOpcode() == ISD::SIGN_EXTEND)
11295         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11296       else if (N->getOpcode() == ISD::ZERO_EXTEND)
11297         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11298       else
11299         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11300     }
11301 
11302     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
11303     // truncate them again to the original value type.
11304     if (PromOp.getOpcode() == ISD::SELECT ||
11305         PromOp.getOpcode() == ISD::SELECT_CC) {
11306       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
11307       if (SI0 != SelectTruncOp[0].end())
11308         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
11309       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
11310       if (SI1 != SelectTruncOp[1].end())
11311         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
11312     }
11313 
11314     DAG.ReplaceAllUsesOfValueWith(PromOp,
11315       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
11316   }
11317 
11318   // Now we're left with the initial extension itself.
11319   if (!ReallyNeedsExt)
11320     return N->getOperand(0);
11321 
11322   // To zero extend, just mask off everything except for the first bit (in the
11323   // i1 case).
11324   if (N->getOpcode() == ISD::ZERO_EXTEND)
11325     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
11326                        DAG.getConstant(APInt::getLowBitsSet(
11327                                          N->getValueSizeInBits(0), PromBits),
11328                                        dl, N->getValueType(0)));
11329 
11330   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
11331          "Invalid extension type");
11332   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
11333   SDValue ShiftCst =
11334       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
11335   return DAG.getNode(
11336       ISD::SRA, dl, N->getValueType(0),
11337       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
11338       ShiftCst);
11339 }
11340 
11341 /// \brief Reduces the number of fp-to-int conversion when building a vector.
11342 ///
11343 /// If this vector is built out of floating to integer conversions,
11344 /// transform it to a vector built out of floating point values followed by a
11345 /// single floating to integer conversion of the vector.
11346 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
11347 /// becomes (fptosi (build_vector ($A, $B, ...)))
11348 SDValue PPCTargetLowering::
11349 combineElementTruncationToVectorTruncation(SDNode *N,
11350                                            DAGCombinerInfo &DCI) const {
11351   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11352          "Should be called with a BUILD_VECTOR node");
11353 
11354   SelectionDAG &DAG = DCI.DAG;
11355   SDLoc dl(N);
11356 
11357   SDValue FirstInput = N->getOperand(0);
11358   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
11359          "The input operand must be an fp-to-int conversion.");
11360 
11361   // This combine happens after legalization so the fp_to_[su]i nodes are
11362   // already converted to PPCSISD nodes.
11363   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
11364   if (FirstConversion == PPCISD::FCTIDZ ||
11365       FirstConversion == PPCISD::FCTIDUZ ||
11366       FirstConversion == PPCISD::FCTIWZ ||
11367       FirstConversion == PPCISD::FCTIWUZ) {
11368     bool IsSplat = true;
11369     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
11370       FirstConversion == PPCISD::FCTIWUZ;
11371     EVT SrcVT = FirstInput.getOperand(0).getValueType();
11372     SmallVector<SDValue, 4> Ops;
11373     EVT TargetVT = N->getValueType(0);
11374     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11375       if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
11376         return SDValue();
11377       unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
11378       if (NextConversion != FirstConversion)
11379         return SDValue();
11380       if (N->getOperand(i) != FirstInput)
11381         IsSplat = false;
11382     }
11383 
11384     // If this is a splat, we leave it as-is since there will be only a single
11385     // fp-to-int conversion followed by a splat of the integer. This is better
11386     // for 32-bit and smaller ints and neutral for 64-bit ints.
11387     if (IsSplat)
11388       return SDValue();
11389 
11390     // Now that we know we have the right type of node, get its operands
11391     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11392       SDValue In = N->getOperand(i).getOperand(0);
11393       // For 32-bit values, we need to add an FP_ROUND node.
11394       if (Is32Bit) {
11395         if (In.isUndef())
11396           Ops.push_back(DAG.getUNDEF(SrcVT));
11397         else {
11398           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
11399                                       MVT::f32, In.getOperand(0),
11400                                       DAG.getIntPtrConstant(1, dl));
11401           Ops.push_back(Trunc);
11402         }
11403       } else
11404         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
11405     }
11406 
11407     unsigned Opcode;
11408     if (FirstConversion == PPCISD::FCTIDZ ||
11409         FirstConversion == PPCISD::FCTIWZ)
11410       Opcode = ISD::FP_TO_SINT;
11411     else
11412       Opcode = ISD::FP_TO_UINT;
11413 
11414     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
11415     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
11416     return DAG.getNode(Opcode, dl, TargetVT, BV);
11417   }
11418   return SDValue();
11419 }
11420 
11421 /// \brief Reduce the number of loads when building a vector.
11422 ///
11423 /// Building a vector out of multiple loads can be converted to a load
11424 /// of the vector type if the loads are consecutive. If the loads are
11425 /// consecutive but in descending order, a shuffle is added at the end
11426 /// to reorder the vector.
11427 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
11428   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11429          "Should be called with a BUILD_VECTOR node");
11430 
11431   SDLoc dl(N);
11432   bool InputsAreConsecutiveLoads = true;
11433   bool InputsAreReverseConsecutive = true;
11434   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
11435   SDValue FirstInput = N->getOperand(0);
11436   bool IsRoundOfExtLoad = false;
11437 
11438   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
11439       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
11440     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
11441     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
11442   }
11443   // Not a build vector of (possibly fp_rounded) loads.
11444   if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
11445     return SDValue();
11446 
11447   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
11448     // If any inputs are fp_round(extload), they all must be.
11449     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
11450       return SDValue();
11451 
11452     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
11453       N->getOperand(i);
11454     if (NextInput.getOpcode() != ISD::LOAD)
11455       return SDValue();
11456 
11457     SDValue PreviousInput =
11458       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11459     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11460     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11461 
11462     // If any inputs are fp_round(extload), they all must be.
11463     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11464       return SDValue();
11465 
11466     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11467       InputsAreConsecutiveLoads = false;
11468     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11469       InputsAreReverseConsecutive = false;
11470 
11471     // Exit early if the loads are neither consecutive nor reverse consecutive.
11472     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11473       return SDValue();
11474   }
11475 
11476   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11477          "The loads cannot be both consecutive and reverse consecutive.");
11478 
11479   SDValue FirstLoadOp =
11480     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11481   SDValue LastLoadOp =
11482     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11483                        N->getOperand(N->getNumOperands()-1);
11484 
11485   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11486   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11487   if (InputsAreConsecutiveLoads) {
11488     assert(LD1 && "Input needs to be a LoadSDNode.");
11489     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11490                        LD1->getBasePtr(), LD1->getPointerInfo(),
11491                        LD1->getAlignment());
11492   }
11493   if (InputsAreReverseConsecutive) {
11494     assert(LDL && "Input needs to be a LoadSDNode.");
11495     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11496                                LDL->getBasePtr(), LDL->getPointerInfo(),
11497                                LDL->getAlignment());
11498     SmallVector<int, 16> Ops;
11499     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11500       Ops.push_back(i);
11501 
11502     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11503                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11504   }
11505   return SDValue();
11506 }
11507 
11508 // This function adds the required vector_shuffle needed to get
11509 // the elements of the vector extract in the correct position
11510 // as specified by the CorrectElems encoding.
11511 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
11512                                       SDValue Input, uint64_t Elems,
11513                                       uint64_t CorrectElems) {
11514   SDLoc dl(N);
11515 
11516   unsigned NumElems = Input.getValueType().getVectorNumElements();
11517   SmallVector<int, 16> ShuffleMask(NumElems, -1);
11518 
11519   // Knowing the element indices being extracted from the original
11520   // vector and the order in which they're being inserted, just put
11521   // them at element indices required for the instruction.
11522   for (unsigned i = 0; i < N->getNumOperands(); i++) {
11523     if (DAG.getDataLayout().isLittleEndian())
11524       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
11525     else
11526       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
11527     CorrectElems = CorrectElems >> 8;
11528     Elems = Elems >> 8;
11529   }
11530 
11531   SDValue Shuffle =
11532       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
11533                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
11534 
11535   EVT Ty = N->getValueType(0);
11536   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
11537   return BV;
11538 }
11539 
11540 // Look for build vector patterns where input operands come from sign
11541 // extended vector_extract elements of specific indices. If the correct indices
11542 // aren't used, add a vector shuffle to fix up the indices and create a new
11543 // PPCISD:SExtVElems node which selects the vector sign extend instructions
11544 // during instruction selection.
11545 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
11546   // This array encodes the indices that the vector sign extend instructions
11547   // extract from when extending from one type to another for both BE and LE.
11548   // The right nibble of each byte corresponds to the LE incides.
11549   // and the left nibble of each byte corresponds to the BE incides.
11550   // For example: 0x3074B8FC  byte->word
11551   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
11552   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
11553   // For example: 0x000070F8  byte->double word
11554   // For LE: the allowed indices are: 0x0,0x8
11555   // For BE: the allowed indices are: 0x7,0xF
11556   uint64_t TargetElems[] = {
11557       0x3074B8FC, // b->w
11558       0x000070F8, // b->d
11559       0x10325476, // h->w
11560       0x00003074, // h->d
11561       0x00001032, // w->d
11562   };
11563 
11564   uint64_t Elems = 0;
11565   int Index;
11566   SDValue Input;
11567 
11568   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
11569     if (!Op)
11570       return false;
11571     if (Op.getOpcode() != ISD::SIGN_EXTEND)
11572       return false;
11573 
11574     SDValue Extract = Op.getOperand(0);
11575     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11576       return false;
11577 
11578     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
11579     if (!ExtOp)
11580       return false;
11581 
11582     Index = ExtOp->getZExtValue();
11583     if (Input && Input != Extract.getOperand(0))
11584       return false;
11585 
11586     if (!Input)
11587       Input = Extract.getOperand(0);
11588 
11589     Elems = Elems << 8;
11590     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
11591     Elems |= Index;
11592 
11593     return true;
11594   };
11595 
11596   // If the build vector operands aren't sign extended vector extracts,
11597   // of the same input vector, then return.
11598   for (unsigned i = 0; i < N->getNumOperands(); i++) {
11599     if (!isSExtOfVecExtract(N->getOperand(i))) {
11600       return SDValue();
11601     }
11602   }
11603 
11604   // If the vector extract indicies are not correct, add the appropriate
11605   // vector_shuffle.
11606   int TgtElemArrayIdx;
11607   int InputSize = Input.getValueType().getScalarSizeInBits();
11608   int OutputSize = N->getValueType(0).getScalarSizeInBits();
11609   if (InputSize + OutputSize == 40)
11610     TgtElemArrayIdx = 0;
11611   else if (InputSize + OutputSize == 72)
11612     TgtElemArrayIdx = 1;
11613   else if (InputSize + OutputSize == 48)
11614     TgtElemArrayIdx = 2;
11615   else if (InputSize + OutputSize == 80)
11616     TgtElemArrayIdx = 3;
11617   else if (InputSize + OutputSize == 96)
11618     TgtElemArrayIdx = 4;
11619   else
11620     return SDValue();
11621 
11622   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
11623   CorrectElems = DAG.getDataLayout().isLittleEndian()
11624                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
11625                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
11626   if (Elems != CorrectElems) {
11627     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
11628   }
11629 
11630   // Regular lowering will catch cases where a shuffle is not needed.
11631   return SDValue();
11632 }
11633 
11634 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11635                                                  DAGCombinerInfo &DCI) const {
11636   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11637          "Should be called with a BUILD_VECTOR node");
11638 
11639   SelectionDAG &DAG = DCI.DAG;
11640   SDLoc dl(N);
11641 
11642   if (!Subtarget.hasVSX())
11643     return SDValue();
11644 
11645   // The target independent DAG combiner will leave a build_vector of
11646   // float-to-int conversions intact. We can generate MUCH better code for
11647   // a float-to-int conversion of a vector of floats.
11648   SDValue FirstInput = N->getOperand(0);
11649   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11650     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11651     if (Reduced)
11652       return Reduced;
11653   }
11654 
11655   // If we're building a vector out of consecutive loads, just load that
11656   // vector type.
11657   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11658   if (Reduced)
11659     return Reduced;
11660 
11661   // If we're building a vector out of extended elements from another vector
11662   // we have P9 vector integer extend instructions.
11663   if (Subtarget.hasP9Altivec()) {
11664     Reduced = combineBVOfVecSExt(N, DAG);
11665     if (Reduced)
11666       return Reduced;
11667   }
11668 
11669 
11670   if (N->getValueType(0) != MVT::v2f64)
11671     return SDValue();
11672 
11673   // Looking for:
11674   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11675   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11676       FirstInput.getOpcode() != ISD::UINT_TO_FP)
11677     return SDValue();
11678   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11679       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11680     return SDValue();
11681   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11682     return SDValue();
11683 
11684   SDValue Ext1 = FirstInput.getOperand(0);
11685   SDValue Ext2 = N->getOperand(1).getOperand(0);
11686   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11687      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11688     return SDValue();
11689 
11690   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11691   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11692   if (!Ext1Op || !Ext2Op)
11693     return SDValue();
11694   if (Ext1.getValueType() != MVT::i32 ||
11695       Ext2.getValueType() != MVT::i32)
11696   if (Ext1.getOperand(0) != Ext2.getOperand(0))
11697     return SDValue();
11698 
11699   int FirstElem = Ext1Op->getZExtValue();
11700   int SecondElem = Ext2Op->getZExtValue();
11701   int SubvecIdx;
11702   if (FirstElem == 0 && SecondElem == 1)
11703     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11704   else if (FirstElem == 2 && SecondElem == 3)
11705     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11706   else
11707     return SDValue();
11708 
11709   SDValue SrcVec = Ext1.getOperand(0);
11710   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11711     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11712   return DAG.getNode(NodeType, dl, MVT::v2f64,
11713                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11714 }
11715 
11716 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11717                                               DAGCombinerInfo &DCI) const {
11718   assert((N->getOpcode() == ISD::SINT_TO_FP ||
11719           N->getOpcode() == ISD::UINT_TO_FP) &&
11720          "Need an int -> FP conversion node here");
11721 
11722   if (useSoftFloat() || !Subtarget.has64BitSupport())
11723     return SDValue();
11724 
11725   SelectionDAG &DAG = DCI.DAG;
11726   SDLoc dl(N);
11727   SDValue Op(N, 0);
11728 
11729   SDValue FirstOperand(Op.getOperand(0));
11730   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11731     (FirstOperand.getValueType() == MVT::i8 ||
11732      FirstOperand.getValueType() == MVT::i16);
11733   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11734     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11735     bool DstDouble = Op.getValueType() == MVT::f64;
11736     unsigned ConvOp = Signed ?
11737       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
11738       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11739     SDValue WidthConst =
11740       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11741                             dl, false);
11742     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11743     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11744     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11745                                          DAG.getVTList(MVT::f64, MVT::Other),
11746                                          Ops, MVT::i8, LDN->getMemOperand());
11747 
11748     // For signed conversion, we need to sign-extend the value in the VSR
11749     if (Signed) {
11750       SDValue ExtOps[] = { Ld, WidthConst };
11751       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11752       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11753     } else
11754       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11755   }
11756 
11757   // Don't handle ppc_fp128 here or i1 conversions.
11758   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11759     return SDValue();
11760   if (Op.getOperand(0).getValueType() == MVT::i1)
11761     return SDValue();
11762 
11763   // For i32 intermediate values, unfortunately, the conversion functions
11764   // leave the upper 32 bits of the value are undefined. Within the set of
11765   // scalar instructions, we have no method for zero- or sign-extending the
11766   // value. Thus, we cannot handle i32 intermediate values here.
11767   if (Op.getOperand(0).getValueType() == MVT::i32)
11768     return SDValue();
11769 
11770   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11771          "UINT_TO_FP is supported only with FPCVT");
11772 
11773   // If we have FCFIDS, then use it when converting to single-precision.
11774   // Otherwise, convert to double-precision and then round.
11775   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11776                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11777                                                             : PPCISD::FCFIDS)
11778                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11779                                                             : PPCISD::FCFID);
11780   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11781                   ? MVT::f32
11782                   : MVT::f64;
11783 
11784   // If we're converting from a float, to an int, and back to a float again,
11785   // then we don't need the store/load pair at all.
11786   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11787        Subtarget.hasFPCVT()) ||
11788       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11789     SDValue Src = Op.getOperand(0).getOperand(0);
11790     if (Src.getValueType() == MVT::f32) {
11791       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11792       DCI.AddToWorklist(Src.getNode());
11793     } else if (Src.getValueType() != MVT::f64) {
11794       // Make sure that we don't pick up a ppc_fp128 source value.
11795       return SDValue();
11796     }
11797 
11798     unsigned FCTOp =
11799       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11800                                                         PPCISD::FCTIDUZ;
11801 
11802     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11803     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11804 
11805     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11806       FP = DAG.getNode(ISD::FP_ROUND, dl,
11807                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11808       DCI.AddToWorklist(FP.getNode());
11809     }
11810 
11811     return FP;
11812   }
11813 
11814   return SDValue();
11815 }
11816 
11817 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11818 // builtins) into loads with swaps.
11819 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11820                                               DAGCombinerInfo &DCI) const {
11821   SelectionDAG &DAG = DCI.DAG;
11822   SDLoc dl(N);
11823   SDValue Chain;
11824   SDValue Base;
11825   MachineMemOperand *MMO;
11826 
11827   switch (N->getOpcode()) {
11828   default:
11829     llvm_unreachable("Unexpected opcode for little endian VSX load");
11830   case ISD::LOAD: {
11831     LoadSDNode *LD = cast<LoadSDNode>(N);
11832     Chain = LD->getChain();
11833     Base = LD->getBasePtr();
11834     MMO = LD->getMemOperand();
11835     // If the MMO suggests this isn't a load of a full vector, leave
11836     // things alone.  For a built-in, we have to make the change for
11837     // correctness, so if there is a size problem that will be a bug.
11838     if (MMO->getSize() < 16)
11839       return SDValue();
11840     break;
11841   }
11842   case ISD::INTRINSIC_W_CHAIN: {
11843     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11844     Chain = Intrin->getChain();
11845     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11846     // us what we want. Get operand 2 instead.
11847     Base = Intrin->getOperand(2);
11848     MMO = Intrin->getMemOperand();
11849     break;
11850   }
11851   }
11852 
11853   MVT VecTy = N->getValueType(0).getSimpleVT();
11854 
11855   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
11856   // aligned and the type is a vector with elements up to 4 bytes
11857   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11858       && VecTy.getScalarSizeInBits() <= 32 ) {
11859     return SDValue();
11860   }
11861 
11862   SDValue LoadOps[] = { Chain, Base };
11863   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11864                                          DAG.getVTList(MVT::v2f64, MVT::Other),
11865                                          LoadOps, MVT::v2f64, MMO);
11866 
11867   DCI.AddToWorklist(Load.getNode());
11868   Chain = Load.getValue(1);
11869   SDValue Swap = DAG.getNode(
11870       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11871   DCI.AddToWorklist(Swap.getNode());
11872 
11873   // Add a bitcast if the resulting load type doesn't match v2f64.
11874   if (VecTy != MVT::v2f64) {
11875     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
11876     DCI.AddToWorklist(N.getNode());
11877     // Package {bitcast value, swap's chain} to match Load's shape.
11878     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
11879                        N, Swap.getValue(1));
11880   }
11881 
11882   return Swap;
11883 }
11884 
11885 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
11886 // builtins) into stores with swaps.
11887 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
11888                                                DAGCombinerInfo &DCI) const {
11889   SelectionDAG &DAG = DCI.DAG;
11890   SDLoc dl(N);
11891   SDValue Chain;
11892   SDValue Base;
11893   unsigned SrcOpnd;
11894   MachineMemOperand *MMO;
11895 
11896   switch (N->getOpcode()) {
11897   default:
11898     llvm_unreachable("Unexpected opcode for little endian VSX store");
11899   case ISD::STORE: {
11900     StoreSDNode *ST = cast<StoreSDNode>(N);
11901     Chain = ST->getChain();
11902     Base = ST->getBasePtr();
11903     MMO = ST->getMemOperand();
11904     SrcOpnd = 1;
11905     // If the MMO suggests this isn't a store of a full vector, leave
11906     // things alone.  For a built-in, we have to make the change for
11907     // correctness, so if there is a size problem that will be a bug.
11908     if (MMO->getSize() < 16)
11909       return SDValue();
11910     break;
11911   }
11912   case ISD::INTRINSIC_VOID: {
11913     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11914     Chain = Intrin->getChain();
11915     // Intrin->getBasePtr() oddly does not get what we want.
11916     Base = Intrin->getOperand(3);
11917     MMO = Intrin->getMemOperand();
11918     SrcOpnd = 2;
11919     break;
11920   }
11921   }
11922 
11923   SDValue Src = N->getOperand(SrcOpnd);
11924   MVT VecTy = Src.getValueType().getSimpleVT();
11925 
11926   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
11927   // aligned and the type is a vector with elements up to 4 bytes
11928   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11929       && VecTy.getScalarSizeInBits() <= 32 ) {
11930     return SDValue();
11931   }
11932 
11933   // All stores are done as v2f64 and possible bit cast.
11934   if (VecTy != MVT::v2f64) {
11935     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
11936     DCI.AddToWorklist(Src.getNode());
11937   }
11938 
11939   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
11940                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
11941   DCI.AddToWorklist(Swap.getNode());
11942   Chain = Swap.getValue(1);
11943   SDValue StoreOps[] = { Chain, Swap, Base };
11944   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
11945                                           DAG.getVTList(MVT::Other),
11946                                           StoreOps, VecTy, MMO);
11947   DCI.AddToWorklist(Store.getNode());
11948   return Store;
11949 }
11950 
11951 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
11952                                              DAGCombinerInfo &DCI) const {
11953   SelectionDAG &DAG = DCI.DAG;
11954   SDLoc dl(N);
11955   switch (N->getOpcode()) {
11956   default: break;
11957   case ISD::SHL:
11958     return combineSHL(N, DCI);
11959   case ISD::SRA:
11960     return combineSRA(N, DCI);
11961   case ISD::SRL:
11962     return combineSRL(N, DCI);
11963   case PPCISD::SHL:
11964     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
11965         return N->getOperand(0);
11966     break;
11967   case PPCISD::SRL:
11968     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
11969         return N->getOperand(0);
11970     break;
11971   case PPCISD::SRA:
11972     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11973       if (C->isNullValue() ||   //  0 >>s V -> 0.
11974           C->isAllOnesValue())    // -1 >>s V -> -1.
11975         return N->getOperand(0);
11976     }
11977     break;
11978   case ISD::SIGN_EXTEND:
11979   case ISD::ZERO_EXTEND:
11980   case ISD::ANY_EXTEND:
11981     return DAGCombineExtBoolTrunc(N, DCI);
11982   case ISD::TRUNCATE:
11983   case ISD::SETCC:
11984   case ISD::SELECT_CC:
11985     return DAGCombineTruncBoolExt(N, DCI);
11986   case ISD::SINT_TO_FP:
11987   case ISD::UINT_TO_FP:
11988     return combineFPToIntToFP(N, DCI);
11989   case ISD::STORE: {
11990     EVT Op1VT = N->getOperand(1).getValueType();
11991     bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
11992       (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
11993 
11994     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
11995     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
11996         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
11997         ValidTypeForStoreFltAsInt &&
11998         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
11999       SDValue Val = N->getOperand(1).getOperand(0);
12000       if (Val.getValueType() == MVT::f32) {
12001         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
12002         DCI.AddToWorklist(Val.getNode());
12003       }
12004       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
12005       DCI.AddToWorklist(Val.getNode());
12006 
12007       if (Op1VT == MVT::i32) {
12008         SDValue Ops[] = {
12009           N->getOperand(0), Val, N->getOperand(2),
12010           DAG.getValueType(N->getOperand(1).getValueType())
12011         };
12012 
12013         Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
12014                 DAG.getVTList(MVT::Other), Ops,
12015                 cast<StoreSDNode>(N)->getMemoryVT(),
12016                 cast<StoreSDNode>(N)->getMemOperand());
12017       } else {
12018         unsigned WidthInBytes =
12019           N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
12020         SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
12021 
12022         SDValue Ops[] = {
12023           N->getOperand(0), Val, N->getOperand(2), WidthConst,
12024           DAG.getValueType(N->getOperand(1).getValueType())
12025         };
12026         Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
12027                                       DAG.getVTList(MVT::Other), Ops,
12028                                       cast<StoreSDNode>(N)->getMemoryVT(),
12029                                       cast<StoreSDNode>(N)->getMemOperand());
12030       }
12031 
12032       DCI.AddToWorklist(Val.getNode());
12033       return Val;
12034     }
12035 
12036     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
12037     if (cast<StoreSDNode>(N)->isUnindexed() &&
12038         N->getOperand(1).getOpcode() == ISD::BSWAP &&
12039         N->getOperand(1).getNode()->hasOneUse() &&
12040         (N->getOperand(1).getValueType() == MVT::i32 ||
12041          N->getOperand(1).getValueType() == MVT::i16 ||
12042          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
12043           N->getOperand(1).getValueType() == MVT::i64))) {
12044       SDValue BSwapOp = N->getOperand(1).getOperand(0);
12045       // Do an any-extend to 32-bits if this is a half-word input.
12046       if (BSwapOp.getValueType() == MVT::i16)
12047         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
12048 
12049       // If the type of BSWAP operand is wider than stored memory width
12050       // it need to be shifted to the right side before STBRX.
12051       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
12052       if (Op1VT.bitsGT(mVT)) {
12053         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
12054         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
12055                               DAG.getConstant(Shift, dl, MVT::i32));
12056         // Need to truncate if this is a bswap of i64 stored as i32/i16.
12057         if (Op1VT == MVT::i64)
12058           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
12059       }
12060 
12061       SDValue Ops[] = {
12062         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
12063       };
12064       return
12065         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
12066                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
12067                                 cast<StoreSDNode>(N)->getMemOperand());
12068     }
12069 
12070     // For little endian, VSX stores require generating xxswapd/lxvd2x.
12071     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12072     EVT VT = N->getOperand(1).getValueType();
12073     if (VT.isSimple()) {
12074       MVT StoreVT = VT.getSimpleVT();
12075       if (Subtarget.needsSwapsForVSXMemOps() &&
12076           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
12077            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
12078         return expandVSXStoreForLE(N, DCI);
12079     }
12080     break;
12081   }
12082   case ISD::LOAD: {
12083     LoadSDNode *LD = cast<LoadSDNode>(N);
12084     EVT VT = LD->getValueType(0);
12085 
12086     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12087     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12088     if (VT.isSimple()) {
12089       MVT LoadVT = VT.getSimpleVT();
12090       if (Subtarget.needsSwapsForVSXMemOps() &&
12091           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
12092            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
12093         return expandVSXLoadForLE(N, DCI);
12094     }
12095 
12096     // We sometimes end up with a 64-bit integer load, from which we extract
12097     // two single-precision floating-point numbers. This happens with
12098     // std::complex<float>, and other similar structures, because of the way we
12099     // canonicalize structure copies. However, if we lack direct moves,
12100     // then the final bitcasts from the extracted integer values to the
12101     // floating-point numbers turn into store/load pairs. Even with direct moves,
12102     // just loading the two floating-point numbers is likely better.
12103     auto ReplaceTwoFloatLoad = [&]() {
12104       if (VT != MVT::i64)
12105         return false;
12106 
12107       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
12108           LD->isVolatile())
12109         return false;
12110 
12111       //  We're looking for a sequence like this:
12112       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
12113       //      t16: i64 = srl t13, Constant:i32<32>
12114       //    t17: i32 = truncate t16
12115       //  t18: f32 = bitcast t17
12116       //    t19: i32 = truncate t13
12117       //  t20: f32 = bitcast t19
12118 
12119       if (!LD->hasNUsesOfValue(2, 0))
12120         return false;
12121 
12122       auto UI = LD->use_begin();
12123       while (UI.getUse().getResNo() != 0) ++UI;
12124       SDNode *Trunc = *UI++;
12125       while (UI.getUse().getResNo() != 0) ++UI;
12126       SDNode *RightShift = *UI;
12127       if (Trunc->getOpcode() != ISD::TRUNCATE)
12128         std::swap(Trunc, RightShift);
12129 
12130       if (Trunc->getOpcode() != ISD::TRUNCATE ||
12131           Trunc->getValueType(0) != MVT::i32 ||
12132           !Trunc->hasOneUse())
12133         return false;
12134       if (RightShift->getOpcode() != ISD::SRL ||
12135           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
12136           RightShift->getConstantOperandVal(1) != 32 ||
12137           !RightShift->hasOneUse())
12138         return false;
12139 
12140       SDNode *Trunc2 = *RightShift->use_begin();
12141       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
12142           Trunc2->getValueType(0) != MVT::i32 ||
12143           !Trunc2->hasOneUse())
12144         return false;
12145 
12146       SDNode *Bitcast = *Trunc->use_begin();
12147       SDNode *Bitcast2 = *Trunc2->use_begin();
12148 
12149       if (Bitcast->getOpcode() != ISD::BITCAST ||
12150           Bitcast->getValueType(0) != MVT::f32)
12151         return false;
12152       if (Bitcast2->getOpcode() != ISD::BITCAST ||
12153           Bitcast2->getValueType(0) != MVT::f32)
12154         return false;
12155 
12156       if (Subtarget.isLittleEndian())
12157         std::swap(Bitcast, Bitcast2);
12158 
12159       // Bitcast has the second float (in memory-layout order) and Bitcast2
12160       // has the first one.
12161 
12162       SDValue BasePtr = LD->getBasePtr();
12163       if (LD->isIndexed()) {
12164         assert(LD->getAddressingMode() == ISD::PRE_INC &&
12165                "Non-pre-inc AM on PPC?");
12166         BasePtr =
12167           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12168                       LD->getOffset());
12169       }
12170 
12171       auto MMOFlags =
12172           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
12173       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
12174                                       LD->getPointerInfo(), LD->getAlignment(),
12175                                       MMOFlags, LD->getAAInfo());
12176       SDValue AddPtr =
12177         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
12178                     BasePtr, DAG.getIntPtrConstant(4, dl));
12179       SDValue FloatLoad2 = DAG.getLoad(
12180           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
12181           LD->getPointerInfo().getWithOffset(4),
12182           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
12183 
12184       if (LD->isIndexed()) {
12185         // Note that DAGCombine should re-form any pre-increment load(s) from
12186         // what is produced here if that makes sense.
12187         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
12188       }
12189 
12190       DCI.CombineTo(Bitcast2, FloatLoad);
12191       DCI.CombineTo(Bitcast, FloatLoad2);
12192 
12193       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
12194                                     SDValue(FloatLoad2.getNode(), 1));
12195       return true;
12196     };
12197 
12198     if (ReplaceTwoFloatLoad())
12199       return SDValue(N, 0);
12200 
12201     EVT MemVT = LD->getMemoryVT();
12202     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
12203     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
12204     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
12205     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
12206     if (LD->isUnindexed() && VT.isVector() &&
12207         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
12208           // P8 and later hardware should just use LOAD.
12209           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
12210                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
12211          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
12212           LD->getAlignment() >= ScalarABIAlignment)) &&
12213         LD->getAlignment() < ABIAlignment) {
12214       // This is a type-legal unaligned Altivec or QPX load.
12215       SDValue Chain = LD->getChain();
12216       SDValue Ptr = LD->getBasePtr();
12217       bool isLittleEndian = Subtarget.isLittleEndian();
12218 
12219       // This implements the loading of unaligned vectors as described in
12220       // the venerable Apple Velocity Engine overview. Specifically:
12221       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
12222       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
12223       //
12224       // The general idea is to expand a sequence of one or more unaligned
12225       // loads into an alignment-based permutation-control instruction (lvsl
12226       // or lvsr), a series of regular vector loads (which always truncate
12227       // their input address to an aligned address), and a series of
12228       // permutations.  The results of these permutations are the requested
12229       // loaded values.  The trick is that the last "extra" load is not taken
12230       // from the address you might suspect (sizeof(vector) bytes after the
12231       // last requested load), but rather sizeof(vector) - 1 bytes after the
12232       // last requested vector. The point of this is to avoid a page fault if
12233       // the base address happened to be aligned. This works because if the
12234       // base address is aligned, then adding less than a full vector length
12235       // will cause the last vector in the sequence to be (re)loaded.
12236       // Otherwise, the next vector will be fetched as you might suspect was
12237       // necessary.
12238 
12239       // We might be able to reuse the permutation generation from
12240       // a different base address offset from this one by an aligned amount.
12241       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
12242       // optimization later.
12243       Intrinsic::ID Intr, IntrLD, IntrPerm;
12244       MVT PermCntlTy, PermTy, LDTy;
12245       if (Subtarget.hasAltivec()) {
12246         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
12247                                  Intrinsic::ppc_altivec_lvsl;
12248         IntrLD = Intrinsic::ppc_altivec_lvx;
12249         IntrPerm = Intrinsic::ppc_altivec_vperm;
12250         PermCntlTy = MVT::v16i8;
12251         PermTy = MVT::v4i32;
12252         LDTy = MVT::v4i32;
12253       } else {
12254         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
12255                                        Intrinsic::ppc_qpx_qvlpcls;
12256         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
12257                                        Intrinsic::ppc_qpx_qvlfs;
12258         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
12259         PermCntlTy = MVT::v4f64;
12260         PermTy = MVT::v4f64;
12261         LDTy = MemVT.getSimpleVT();
12262       }
12263 
12264       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
12265 
12266       // Create the new MMO for the new base load. It is like the original MMO,
12267       // but represents an area in memory almost twice the vector size centered
12268       // on the original address. If the address is unaligned, we might start
12269       // reading up to (sizeof(vector)-1) bytes below the address of the
12270       // original unaligned load.
12271       MachineFunction &MF = DAG.getMachineFunction();
12272       MachineMemOperand *BaseMMO =
12273         MF.getMachineMemOperand(LD->getMemOperand(),
12274                                 -(long)MemVT.getStoreSize()+1,
12275                                 2*MemVT.getStoreSize()-1);
12276 
12277       // Create the new base load.
12278       SDValue LDXIntID =
12279           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
12280       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
12281       SDValue BaseLoad =
12282         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12283                                 DAG.getVTList(PermTy, MVT::Other),
12284                                 BaseLoadOps, LDTy, BaseMMO);
12285 
12286       // Note that the value of IncOffset (which is provided to the next
12287       // load's pointer info offset value, and thus used to calculate the
12288       // alignment), and the value of IncValue (which is actually used to
12289       // increment the pointer value) are different! This is because we
12290       // require the next load to appear to be aligned, even though it
12291       // is actually offset from the base pointer by a lesser amount.
12292       int IncOffset = VT.getSizeInBits() / 8;
12293       int IncValue = IncOffset;
12294 
12295       // Walk (both up and down) the chain looking for another load at the real
12296       // (aligned) offset (the alignment of the other load does not matter in
12297       // this case). If found, then do not use the offset reduction trick, as
12298       // that will prevent the loads from being later combined (as they would
12299       // otherwise be duplicates).
12300       if (!findConsecutiveLoad(LD, DAG))
12301         --IncValue;
12302 
12303       SDValue Increment =
12304           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
12305       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
12306 
12307       MachineMemOperand *ExtraMMO =
12308         MF.getMachineMemOperand(LD->getMemOperand(),
12309                                 1, 2*MemVT.getStoreSize()-1);
12310       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
12311       SDValue ExtraLoad =
12312         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12313                                 DAG.getVTList(PermTy, MVT::Other),
12314                                 ExtraLoadOps, LDTy, ExtraMMO);
12315 
12316       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
12317         BaseLoad.getValue(1), ExtraLoad.getValue(1));
12318 
12319       // Because vperm has a big-endian bias, we must reverse the order
12320       // of the input vectors and complement the permute control vector
12321       // when generating little endian code.  We have already handled the
12322       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
12323       // and ExtraLoad here.
12324       SDValue Perm;
12325       if (isLittleEndian)
12326         Perm = BuildIntrinsicOp(IntrPerm,
12327                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
12328       else
12329         Perm = BuildIntrinsicOp(IntrPerm,
12330                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
12331 
12332       if (VT != PermTy)
12333         Perm = Subtarget.hasAltivec() ?
12334                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
12335                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
12336                                DAG.getTargetConstant(1, dl, MVT::i64));
12337                                // second argument is 1 because this rounding
12338                                // is always exact.
12339 
12340       // The output of the permutation is our loaded result, the TokenFactor is
12341       // our new chain.
12342       DCI.CombineTo(N, Perm, TF);
12343       return SDValue(N, 0);
12344     }
12345     }
12346     break;
12347     case ISD::INTRINSIC_WO_CHAIN: {
12348       bool isLittleEndian = Subtarget.isLittleEndian();
12349       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12350       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
12351                                            : Intrinsic::ppc_altivec_lvsl);
12352       if ((IID == Intr ||
12353            IID == Intrinsic::ppc_qpx_qvlpcld  ||
12354            IID == Intrinsic::ppc_qpx_qvlpcls) &&
12355         N->getOperand(1)->getOpcode() == ISD::ADD) {
12356         SDValue Add = N->getOperand(1);
12357 
12358         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
12359                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
12360 
12361         if (DAG.MaskedValueIsZero(Add->getOperand(1),
12362                                   APInt::getAllOnesValue(Bits /* alignment */)
12363                                       .zext(Add.getScalarValueSizeInBits()))) {
12364           SDNode *BasePtr = Add->getOperand(0).getNode();
12365           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12366                                     UE = BasePtr->use_end();
12367                UI != UE; ++UI) {
12368             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12369                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
12370               // We've found another LVSL/LVSR, and this address is an aligned
12371               // multiple of that one. The results will be the same, so use the
12372               // one we've just found instead.
12373 
12374               return SDValue(*UI, 0);
12375             }
12376           }
12377         }
12378 
12379         if (isa<ConstantSDNode>(Add->getOperand(1))) {
12380           SDNode *BasePtr = Add->getOperand(0).getNode();
12381           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12382                UE = BasePtr->use_end(); UI != UE; ++UI) {
12383             if (UI->getOpcode() == ISD::ADD &&
12384                 isa<ConstantSDNode>(UI->getOperand(1)) &&
12385                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
12386                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
12387                 (1ULL << Bits) == 0) {
12388               SDNode *OtherAdd = *UI;
12389               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
12390                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
12391                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12392                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
12393                   return SDValue(*VI, 0);
12394                 }
12395               }
12396             }
12397           }
12398         }
12399       }
12400     }
12401 
12402     break;
12403   case ISD::INTRINSIC_W_CHAIN:
12404     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12405     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12406     if (Subtarget.needsSwapsForVSXMemOps()) {
12407       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12408       default:
12409         break;
12410       case Intrinsic::ppc_vsx_lxvw4x:
12411       case Intrinsic::ppc_vsx_lxvd2x:
12412         return expandVSXLoadForLE(N, DCI);
12413       }
12414     }
12415     break;
12416   case ISD::INTRINSIC_VOID:
12417     // For little endian, VSX stores require generating xxswapd/stxvd2x.
12418     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12419     if (Subtarget.needsSwapsForVSXMemOps()) {
12420       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12421       default:
12422         break;
12423       case Intrinsic::ppc_vsx_stxvw4x:
12424       case Intrinsic::ppc_vsx_stxvd2x:
12425         return expandVSXStoreForLE(N, DCI);
12426       }
12427     }
12428     break;
12429   case ISD::BSWAP:
12430     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
12431     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
12432         N->getOperand(0).hasOneUse() &&
12433         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
12434          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
12435           N->getValueType(0) == MVT::i64))) {
12436       SDValue Load = N->getOperand(0);
12437       LoadSDNode *LD = cast<LoadSDNode>(Load);
12438       // Create the byte-swapping load.
12439       SDValue Ops[] = {
12440         LD->getChain(),    // Chain
12441         LD->getBasePtr(),  // Ptr
12442         DAG.getValueType(N->getValueType(0)) // VT
12443       };
12444       SDValue BSLoad =
12445         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
12446                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
12447                                               MVT::i64 : MVT::i32, MVT::Other),
12448                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
12449 
12450       // If this is an i16 load, insert the truncate.
12451       SDValue ResVal = BSLoad;
12452       if (N->getValueType(0) == MVT::i16)
12453         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
12454 
12455       // First, combine the bswap away.  This makes the value produced by the
12456       // load dead.
12457       DCI.CombineTo(N, ResVal);
12458 
12459       // Next, combine the load away, we give it a bogus result value but a real
12460       // chain result.  The result value is dead because the bswap is dead.
12461       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
12462 
12463       // Return N so it doesn't get rechecked!
12464       return SDValue(N, 0);
12465     }
12466     break;
12467   case PPCISD::VCMP:
12468     // If a VCMPo node already exists with exactly the same operands as this
12469     // node, use its result instead of this node (VCMPo computes both a CR6 and
12470     // a normal output).
12471     //
12472     if (!N->getOperand(0).hasOneUse() &&
12473         !N->getOperand(1).hasOneUse() &&
12474         !N->getOperand(2).hasOneUse()) {
12475 
12476       // Scan all of the users of the LHS, looking for VCMPo's that match.
12477       SDNode *VCMPoNode = nullptr;
12478 
12479       SDNode *LHSN = N->getOperand(0).getNode();
12480       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
12481            UI != E; ++UI)
12482         if (UI->getOpcode() == PPCISD::VCMPo &&
12483             UI->getOperand(1) == N->getOperand(1) &&
12484             UI->getOperand(2) == N->getOperand(2) &&
12485             UI->getOperand(0) == N->getOperand(0)) {
12486           VCMPoNode = *UI;
12487           break;
12488         }
12489 
12490       // If there is no VCMPo node, or if the flag value has a single use, don't
12491       // transform this.
12492       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
12493         break;
12494 
12495       // Look at the (necessarily single) use of the flag value.  If it has a
12496       // chain, this transformation is more complex.  Note that multiple things
12497       // could use the value result, which we should ignore.
12498       SDNode *FlagUser = nullptr;
12499       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
12500            FlagUser == nullptr; ++UI) {
12501         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
12502         SDNode *User = *UI;
12503         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
12504           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
12505             FlagUser = User;
12506             break;
12507           }
12508         }
12509       }
12510 
12511       // If the user is a MFOCRF instruction, we know this is safe.
12512       // Otherwise we give up for right now.
12513       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
12514         return SDValue(VCMPoNode, 0);
12515     }
12516     break;
12517   case ISD::BRCOND: {
12518     SDValue Cond = N->getOperand(1);
12519     SDValue Target = N->getOperand(2);
12520 
12521     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12522         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
12523           Intrinsic::ppc_is_decremented_ctr_nonzero) {
12524 
12525       // We now need to make the intrinsic dead (it cannot be instruction
12526       // selected).
12527       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
12528       assert(Cond.getNode()->hasOneUse() &&
12529              "Counter decrement has more than one use");
12530 
12531       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
12532                          N->getOperand(0), Target);
12533     }
12534   }
12535   break;
12536   case ISD::BR_CC: {
12537     // If this is a branch on an altivec predicate comparison, lower this so
12538     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
12539     // lowering is done pre-legalize, because the legalizer lowers the predicate
12540     // compare down to code that is difficult to reassemble.
12541     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
12542     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
12543 
12544     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
12545     // value. If so, pass-through the AND to get to the intrinsic.
12546     if (LHS.getOpcode() == ISD::AND &&
12547         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12548         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
12549           Intrinsic::ppc_is_decremented_ctr_nonzero &&
12550         isa<ConstantSDNode>(LHS.getOperand(1)) &&
12551         !isNullConstant(LHS.getOperand(1)))
12552       LHS = LHS.getOperand(0);
12553 
12554     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12555         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
12556           Intrinsic::ppc_is_decremented_ctr_nonzero &&
12557         isa<ConstantSDNode>(RHS)) {
12558       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
12559              "Counter decrement comparison is not EQ or NE");
12560 
12561       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12562       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
12563                     (CC == ISD::SETNE && !Val);
12564 
12565       // We now need to make the intrinsic dead (it cannot be instruction
12566       // selected).
12567       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
12568       assert(LHS.getNode()->hasOneUse() &&
12569              "Counter decrement has more than one use");
12570 
12571       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
12572                          N->getOperand(0), N->getOperand(4));
12573     }
12574 
12575     int CompareOpc;
12576     bool isDot;
12577 
12578     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12579         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
12580         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
12581       assert(isDot && "Can't compare against a vector result!");
12582 
12583       // If this is a comparison against something other than 0/1, then we know
12584       // that the condition is never/always true.
12585       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12586       if (Val != 0 && Val != 1) {
12587         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
12588           return N->getOperand(0);
12589         // Always !=, turn it into an unconditional branch.
12590         return DAG.getNode(ISD::BR, dl, MVT::Other,
12591                            N->getOperand(0), N->getOperand(4));
12592       }
12593 
12594       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
12595 
12596       // Create the PPCISD altivec 'dot' comparison node.
12597       SDValue Ops[] = {
12598         LHS.getOperand(2),  // LHS of compare
12599         LHS.getOperand(3),  // RHS of compare
12600         DAG.getConstant(CompareOpc, dl, MVT::i32)
12601       };
12602       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
12603       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
12604 
12605       // Unpack the result based on how the target uses it.
12606       PPC::Predicate CompOpc;
12607       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
12608       default:  // Can't happen, don't crash on invalid number though.
12609       case 0:   // Branch on the value of the EQ bit of CR6.
12610         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
12611         break;
12612       case 1:   // Branch on the inverted value of the EQ bit of CR6.
12613         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
12614         break;
12615       case 2:   // Branch on the value of the LT bit of CR6.
12616         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
12617         break;
12618       case 3:   // Branch on the inverted value of the LT bit of CR6.
12619         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
12620         break;
12621       }
12622 
12623       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
12624                          DAG.getConstant(CompOpc, dl, MVT::i32),
12625                          DAG.getRegister(PPC::CR6, MVT::i32),
12626                          N->getOperand(4), CompNode.getValue(1));
12627     }
12628     break;
12629   }
12630   case ISD::BUILD_VECTOR:
12631     return DAGCombineBuildVector(N, DCI);
12632   }
12633 
12634   return SDValue();
12635 }
12636 
12637 SDValue
12638 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12639                                   SelectionDAG &DAG,
12640                                   std::vector<SDNode *> *Created) const {
12641   // fold (sdiv X, pow2)
12642   EVT VT = N->getValueType(0);
12643   if (VT == MVT::i64 && !Subtarget.isPPC64())
12644     return SDValue();
12645   if ((VT != MVT::i32 && VT != MVT::i64) ||
12646       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12647     return SDValue();
12648 
12649   SDLoc DL(N);
12650   SDValue N0 = N->getOperand(0);
12651 
12652   bool IsNegPow2 = (-Divisor).isPowerOf2();
12653   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12654   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12655 
12656   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12657   if (Created)
12658     Created->push_back(Op.getNode());
12659 
12660   if (IsNegPow2) {
12661     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12662     if (Created)
12663       Created->push_back(Op.getNode());
12664   }
12665 
12666   return Op;
12667 }
12668 
12669 //===----------------------------------------------------------------------===//
12670 // Inline Assembly Support
12671 //===----------------------------------------------------------------------===//
12672 
12673 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12674                                                       KnownBits &Known,
12675                                                       const APInt &DemandedElts,
12676                                                       const SelectionDAG &DAG,
12677                                                       unsigned Depth) const {
12678   Known.resetAll();
12679   switch (Op.getOpcode()) {
12680   default: break;
12681   case PPCISD::LBRX: {
12682     // lhbrx is known to have the top bits cleared out.
12683     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12684       Known.Zero = 0xFFFF0000;
12685     break;
12686   }
12687   case ISD::INTRINSIC_WO_CHAIN: {
12688     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12689     default: break;
12690     case Intrinsic::ppc_altivec_vcmpbfp_p:
12691     case Intrinsic::ppc_altivec_vcmpeqfp_p:
12692     case Intrinsic::ppc_altivec_vcmpequb_p:
12693     case Intrinsic::ppc_altivec_vcmpequh_p:
12694     case Intrinsic::ppc_altivec_vcmpequw_p:
12695     case Intrinsic::ppc_altivec_vcmpequd_p:
12696     case Intrinsic::ppc_altivec_vcmpgefp_p:
12697     case Intrinsic::ppc_altivec_vcmpgtfp_p:
12698     case Intrinsic::ppc_altivec_vcmpgtsb_p:
12699     case Intrinsic::ppc_altivec_vcmpgtsh_p:
12700     case Intrinsic::ppc_altivec_vcmpgtsw_p:
12701     case Intrinsic::ppc_altivec_vcmpgtsd_p:
12702     case Intrinsic::ppc_altivec_vcmpgtub_p:
12703     case Intrinsic::ppc_altivec_vcmpgtuh_p:
12704     case Intrinsic::ppc_altivec_vcmpgtuw_p:
12705     case Intrinsic::ppc_altivec_vcmpgtud_p:
12706       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
12707       break;
12708     }
12709   }
12710   }
12711 }
12712 
12713 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12714   switch (Subtarget.getDarwinDirective()) {
12715   default: break;
12716   case PPC::DIR_970:
12717   case PPC::DIR_PWR4:
12718   case PPC::DIR_PWR5:
12719   case PPC::DIR_PWR5X:
12720   case PPC::DIR_PWR6:
12721   case PPC::DIR_PWR6X:
12722   case PPC::DIR_PWR7:
12723   case PPC::DIR_PWR8:
12724   case PPC::DIR_PWR9: {
12725     if (!ML)
12726       break;
12727 
12728     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12729 
12730     // For small loops (between 5 and 8 instructions), align to a 32-byte
12731     // boundary so that the entire loop fits in one instruction-cache line.
12732     uint64_t LoopSize = 0;
12733     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12734       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12735         LoopSize += TII->getInstSizeInBytes(*J);
12736         if (LoopSize > 32)
12737           break;
12738       }
12739 
12740     if (LoopSize > 16 && LoopSize <= 32)
12741       return 5;
12742 
12743     break;
12744   }
12745   }
12746 
12747   return TargetLowering::getPrefLoopAlignment(ML);
12748 }
12749 
12750 /// getConstraintType - Given a constraint, return the type of
12751 /// constraint it is for this target.
12752 PPCTargetLowering::ConstraintType
12753 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12754   if (Constraint.size() == 1) {
12755     switch (Constraint[0]) {
12756     default: break;
12757     case 'b':
12758     case 'r':
12759     case 'f':
12760     case 'd':
12761     case 'v':
12762     case 'y':
12763       return C_RegisterClass;
12764     case 'Z':
12765       // FIXME: While Z does indicate a memory constraint, it specifically
12766       // indicates an r+r address (used in conjunction with the 'y' modifier
12767       // in the replacement string). Currently, we're forcing the base
12768       // register to be r0 in the asm printer (which is interpreted as zero)
12769       // and forming the complete address in the second register. This is
12770       // suboptimal.
12771       return C_Memory;
12772     }
12773   } else if (Constraint == "wc") { // individual CR bits.
12774     return C_RegisterClass;
12775   } else if (Constraint == "wa" || Constraint == "wd" ||
12776              Constraint == "wf" || Constraint == "ws") {
12777     return C_RegisterClass; // VSX registers.
12778   }
12779   return TargetLowering::getConstraintType(Constraint);
12780 }
12781 
12782 /// Examine constraint type and operand type and determine a weight value.
12783 /// This object must already have been set up with the operand type
12784 /// and the current alternative constraint selected.
12785 TargetLowering::ConstraintWeight
12786 PPCTargetLowering::getSingleConstraintMatchWeight(
12787     AsmOperandInfo &info, const char *constraint) const {
12788   ConstraintWeight weight = CW_Invalid;
12789   Value *CallOperandVal = info.CallOperandVal;
12790     // If we don't have a value, we can't do a match,
12791     // but allow it at the lowest weight.
12792   if (!CallOperandVal)
12793     return CW_Default;
12794   Type *type = CallOperandVal->getType();
12795 
12796   // Look at the constraint type.
12797   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12798     return CW_Register; // an individual CR bit.
12799   else if ((StringRef(constraint) == "wa" ||
12800             StringRef(constraint) == "wd" ||
12801             StringRef(constraint) == "wf") &&
12802            type->isVectorTy())
12803     return CW_Register;
12804   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12805     return CW_Register;
12806 
12807   switch (*constraint) {
12808   default:
12809     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12810     break;
12811   case 'b':
12812     if (type->isIntegerTy())
12813       weight = CW_Register;
12814     break;
12815   case 'f':
12816     if (type->isFloatTy())
12817       weight = CW_Register;
12818     break;
12819   case 'd':
12820     if (type->isDoubleTy())
12821       weight = CW_Register;
12822     break;
12823   case 'v':
12824     if (type->isVectorTy())
12825       weight = CW_Register;
12826     break;
12827   case 'y':
12828     weight = CW_Register;
12829     break;
12830   case 'Z':
12831     weight = CW_Memory;
12832     break;
12833   }
12834   return weight;
12835 }
12836 
12837 std::pair<unsigned, const TargetRegisterClass *>
12838 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12839                                                 StringRef Constraint,
12840                                                 MVT VT) const {
12841   if (Constraint.size() == 1) {
12842     // GCC RS6000 Constraint Letters
12843     switch (Constraint[0]) {
12844     case 'b':   // R1-R31
12845       if (VT == MVT::i64 && Subtarget.isPPC64())
12846         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12847       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12848     case 'r':   // R0-R31
12849       if (VT == MVT::i64 && Subtarget.isPPC64())
12850         return std::make_pair(0U, &PPC::G8RCRegClass);
12851       return std::make_pair(0U, &PPC::GPRCRegClass);
12852     // 'd' and 'f' constraints are both defined to be "the floating point
12853     // registers", where one is for 32-bit and the other for 64-bit. We don't
12854     // really care overly much here so just give them all the same reg classes.
12855     case 'd':
12856     case 'f':
12857       if (VT == MVT::f32 || VT == MVT::i32)
12858         return std::make_pair(0U, &PPC::F4RCRegClass);
12859       if (VT == MVT::f64 || VT == MVT::i64)
12860         return std::make_pair(0U, &PPC::F8RCRegClass);
12861       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12862         return std::make_pair(0U, &PPC::QFRCRegClass);
12863       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12864         return std::make_pair(0U, &PPC::QSRCRegClass);
12865       break;
12866     case 'v':
12867       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12868         return std::make_pair(0U, &PPC::QFRCRegClass);
12869       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12870         return std::make_pair(0U, &PPC::QSRCRegClass);
12871       if (Subtarget.hasAltivec())
12872         return std::make_pair(0U, &PPC::VRRCRegClass);
12873     case 'y':   // crrc
12874       return std::make_pair(0U, &PPC::CRRCRegClass);
12875     }
12876   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
12877     // An individual CR bit.
12878     return std::make_pair(0U, &PPC::CRBITRCRegClass);
12879   } else if ((Constraint == "wa" || Constraint == "wd" ||
12880              Constraint == "wf") && Subtarget.hasVSX()) {
12881     return std::make_pair(0U, &PPC::VSRCRegClass);
12882   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
12883     if (VT == MVT::f32 && Subtarget.hasP8Vector())
12884       return std::make_pair(0U, &PPC::VSSRCRegClass);
12885     else
12886       return std::make_pair(0U, &PPC::VSFRCRegClass);
12887   }
12888 
12889   std::pair<unsigned, const TargetRegisterClass *> R =
12890       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12891 
12892   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
12893   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
12894   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
12895   // register.
12896   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
12897   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
12898   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
12899       PPC::GPRCRegClass.contains(R.first))
12900     return std::make_pair(TRI->getMatchingSuperReg(R.first,
12901                             PPC::sub_32, &PPC::G8RCRegClass),
12902                           &PPC::G8RCRegClass);
12903 
12904   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
12905   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
12906     R.first = PPC::CR0;
12907     R.second = &PPC::CRRCRegClass;
12908   }
12909 
12910   return R;
12911 }
12912 
12913 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12914 /// vector.  If it is invalid, don't add anything to Ops.
12915 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12916                                                      std::string &Constraint,
12917                                                      std::vector<SDValue>&Ops,
12918                                                      SelectionDAG &DAG) const {
12919   SDValue Result;
12920 
12921   // Only support length 1 constraints.
12922   if (Constraint.length() > 1) return;
12923 
12924   char Letter = Constraint[0];
12925   switch (Letter) {
12926   default: break;
12927   case 'I':
12928   case 'J':
12929   case 'K':
12930   case 'L':
12931   case 'M':
12932   case 'N':
12933   case 'O':
12934   case 'P': {
12935     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
12936     if (!CST) return; // Must be an immediate to match.
12937     SDLoc dl(Op);
12938     int64_t Value = CST->getSExtValue();
12939     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
12940                          // numbers are printed as such.
12941     switch (Letter) {
12942     default: llvm_unreachable("Unknown constraint letter!");
12943     case 'I':  // "I" is a signed 16-bit constant.
12944       if (isInt<16>(Value))
12945         Result = DAG.getTargetConstant(Value, dl, TCVT);
12946       break;
12947     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
12948       if (isShiftedUInt<16, 16>(Value))
12949         Result = DAG.getTargetConstant(Value, dl, TCVT);
12950       break;
12951     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
12952       if (isShiftedInt<16, 16>(Value))
12953         Result = DAG.getTargetConstant(Value, dl, TCVT);
12954       break;
12955     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
12956       if (isUInt<16>(Value))
12957         Result = DAG.getTargetConstant(Value, dl, TCVT);
12958       break;
12959     case 'M':  // "M" is a constant that is greater than 31.
12960       if (Value > 31)
12961         Result = DAG.getTargetConstant(Value, dl, TCVT);
12962       break;
12963     case 'N':  // "N" is a positive constant that is an exact power of two.
12964       if (Value > 0 && isPowerOf2_64(Value))
12965         Result = DAG.getTargetConstant(Value, dl, TCVT);
12966       break;
12967     case 'O':  // "O" is the constant zero.
12968       if (Value == 0)
12969         Result = DAG.getTargetConstant(Value, dl, TCVT);
12970       break;
12971     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
12972       if (isInt<16>(-Value))
12973         Result = DAG.getTargetConstant(Value, dl, TCVT);
12974       break;
12975     }
12976     break;
12977   }
12978   }
12979 
12980   if (Result.getNode()) {
12981     Ops.push_back(Result);
12982     return;
12983   }
12984 
12985   // Handle standard constraint letters.
12986   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12987 }
12988 
12989 // isLegalAddressingMode - Return true if the addressing mode represented
12990 // by AM is legal for this target, for a load/store of the specified type.
12991 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12992                                               const AddrMode &AM, Type *Ty,
12993                                               unsigned AS, Instruction *I) const {
12994   // PPC does not allow r+i addressing modes for vectors!
12995   if (Ty->isVectorTy() && AM.BaseOffs != 0)
12996     return false;
12997 
12998   // PPC allows a sign-extended 16-bit immediate field.
12999   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
13000     return false;
13001 
13002   // No global is ever allowed as a base.
13003   if (AM.BaseGV)
13004     return false;
13005 
13006   // PPC only support r+r,
13007   switch (AM.Scale) {
13008   case 0:  // "r+i" or just "i", depending on HasBaseReg.
13009     break;
13010   case 1:
13011     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
13012       return false;
13013     // Otherwise we have r+r or r+i.
13014     break;
13015   case 2:
13016     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
13017       return false;
13018     // Allow 2*r as r+r.
13019     break;
13020   default:
13021     // No other scales are supported.
13022     return false;
13023   }
13024 
13025   return true;
13026 }
13027 
13028 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
13029                                            SelectionDAG &DAG) const {
13030   MachineFunction &MF = DAG.getMachineFunction();
13031   MachineFrameInfo &MFI = MF.getFrameInfo();
13032   MFI.setReturnAddressIsTaken(true);
13033 
13034   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13035     return SDValue();
13036 
13037   SDLoc dl(Op);
13038   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13039 
13040   // Make sure the function does not optimize away the store of the RA to
13041   // the stack.
13042   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
13043   FuncInfo->setLRStoreRequired();
13044   bool isPPC64 = Subtarget.isPPC64();
13045   auto PtrVT = getPointerTy(MF.getDataLayout());
13046 
13047   if (Depth > 0) {
13048     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13049     SDValue Offset =
13050         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
13051                         isPPC64 ? MVT::i64 : MVT::i32);
13052     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13053                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
13054                        MachinePointerInfo());
13055   }
13056 
13057   // Just load the return address off the stack.
13058   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
13059   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
13060                      MachinePointerInfo());
13061 }
13062 
13063 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
13064                                           SelectionDAG &DAG) const {
13065   SDLoc dl(Op);
13066   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13067 
13068   MachineFunction &MF = DAG.getMachineFunction();
13069   MachineFrameInfo &MFI = MF.getFrameInfo();
13070   MFI.setFrameAddressIsTaken(true);
13071 
13072   EVT PtrVT = getPointerTy(MF.getDataLayout());
13073   bool isPPC64 = PtrVT == MVT::i64;
13074 
13075   // Naked functions never have a frame pointer, and so we use r1. For all
13076   // other functions, this decision must be delayed until during PEI.
13077   unsigned FrameReg;
13078   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
13079     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
13080   else
13081     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
13082 
13083   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
13084                                          PtrVT);
13085   while (Depth--)
13086     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
13087                             FrameAddr, MachinePointerInfo());
13088   return FrameAddr;
13089 }
13090 
13091 // FIXME? Maybe this could be a TableGen attribute on some registers and
13092 // this table could be generated automatically from RegInfo.
13093 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
13094                                               SelectionDAG &DAG) const {
13095   bool isPPC64 = Subtarget.isPPC64();
13096   bool isDarwinABI = Subtarget.isDarwinABI();
13097 
13098   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
13099       (!isPPC64 && VT != MVT::i32))
13100     report_fatal_error("Invalid register global variable type");
13101 
13102   bool is64Bit = isPPC64 && VT == MVT::i64;
13103   unsigned Reg = StringSwitch<unsigned>(RegName)
13104                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
13105                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
13106                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
13107                                   (is64Bit ? PPC::X13 : PPC::R13))
13108                    .Default(0);
13109 
13110   if (Reg)
13111     return Reg;
13112   report_fatal_error("Invalid register name global variable");
13113 }
13114 
13115 bool
13116 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13117   // The PowerPC target isn't yet aware of offsets.
13118   return false;
13119 }
13120 
13121 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13122                                            const CallInst &I,
13123                                            unsigned Intrinsic) const {
13124   switch (Intrinsic) {
13125   case Intrinsic::ppc_qpx_qvlfd:
13126   case Intrinsic::ppc_qpx_qvlfs:
13127   case Intrinsic::ppc_qpx_qvlfcd:
13128   case Intrinsic::ppc_qpx_qvlfcs:
13129   case Intrinsic::ppc_qpx_qvlfiwa:
13130   case Intrinsic::ppc_qpx_qvlfiwz:
13131   case Intrinsic::ppc_altivec_lvx:
13132   case Intrinsic::ppc_altivec_lvxl:
13133   case Intrinsic::ppc_altivec_lvebx:
13134   case Intrinsic::ppc_altivec_lvehx:
13135   case Intrinsic::ppc_altivec_lvewx:
13136   case Intrinsic::ppc_vsx_lxvd2x:
13137   case Intrinsic::ppc_vsx_lxvw4x: {
13138     EVT VT;
13139     switch (Intrinsic) {
13140     case Intrinsic::ppc_altivec_lvebx:
13141       VT = MVT::i8;
13142       break;
13143     case Intrinsic::ppc_altivec_lvehx:
13144       VT = MVT::i16;
13145       break;
13146     case Intrinsic::ppc_altivec_lvewx:
13147       VT = MVT::i32;
13148       break;
13149     case Intrinsic::ppc_vsx_lxvd2x:
13150       VT = MVT::v2f64;
13151       break;
13152     case Intrinsic::ppc_qpx_qvlfd:
13153       VT = MVT::v4f64;
13154       break;
13155     case Intrinsic::ppc_qpx_qvlfs:
13156       VT = MVT::v4f32;
13157       break;
13158     case Intrinsic::ppc_qpx_qvlfcd:
13159       VT = MVT::v2f64;
13160       break;
13161     case Intrinsic::ppc_qpx_qvlfcs:
13162       VT = MVT::v2f32;
13163       break;
13164     default:
13165       VT = MVT::v4i32;
13166       break;
13167     }
13168 
13169     Info.opc = ISD::INTRINSIC_W_CHAIN;
13170     Info.memVT = VT;
13171     Info.ptrVal = I.getArgOperand(0);
13172     Info.offset = -VT.getStoreSize()+1;
13173     Info.size = 2*VT.getStoreSize()-1;
13174     Info.align = 1;
13175     Info.vol = false;
13176     Info.readMem = true;
13177     Info.writeMem = false;
13178     return true;
13179   }
13180   case Intrinsic::ppc_qpx_qvlfda:
13181   case Intrinsic::ppc_qpx_qvlfsa:
13182   case Intrinsic::ppc_qpx_qvlfcda:
13183   case Intrinsic::ppc_qpx_qvlfcsa:
13184   case Intrinsic::ppc_qpx_qvlfiwaa:
13185   case Intrinsic::ppc_qpx_qvlfiwza: {
13186     EVT VT;
13187     switch (Intrinsic) {
13188     case Intrinsic::ppc_qpx_qvlfda:
13189       VT = MVT::v4f64;
13190       break;
13191     case Intrinsic::ppc_qpx_qvlfsa:
13192       VT = MVT::v4f32;
13193       break;
13194     case Intrinsic::ppc_qpx_qvlfcda:
13195       VT = MVT::v2f64;
13196       break;
13197     case Intrinsic::ppc_qpx_qvlfcsa:
13198       VT = MVT::v2f32;
13199       break;
13200     default:
13201       VT = MVT::v4i32;
13202       break;
13203     }
13204 
13205     Info.opc = ISD::INTRINSIC_W_CHAIN;
13206     Info.memVT = VT;
13207     Info.ptrVal = I.getArgOperand(0);
13208     Info.offset = 0;
13209     Info.size = VT.getStoreSize();
13210     Info.align = 1;
13211     Info.vol = false;
13212     Info.readMem = true;
13213     Info.writeMem = false;
13214     return true;
13215   }
13216   case Intrinsic::ppc_qpx_qvstfd:
13217   case Intrinsic::ppc_qpx_qvstfs:
13218   case Intrinsic::ppc_qpx_qvstfcd:
13219   case Intrinsic::ppc_qpx_qvstfcs:
13220   case Intrinsic::ppc_qpx_qvstfiw:
13221   case Intrinsic::ppc_altivec_stvx:
13222   case Intrinsic::ppc_altivec_stvxl:
13223   case Intrinsic::ppc_altivec_stvebx:
13224   case Intrinsic::ppc_altivec_stvehx:
13225   case Intrinsic::ppc_altivec_stvewx:
13226   case Intrinsic::ppc_vsx_stxvd2x:
13227   case Intrinsic::ppc_vsx_stxvw4x: {
13228     EVT VT;
13229     switch (Intrinsic) {
13230     case Intrinsic::ppc_altivec_stvebx:
13231       VT = MVT::i8;
13232       break;
13233     case Intrinsic::ppc_altivec_stvehx:
13234       VT = MVT::i16;
13235       break;
13236     case Intrinsic::ppc_altivec_stvewx:
13237       VT = MVT::i32;
13238       break;
13239     case Intrinsic::ppc_vsx_stxvd2x:
13240       VT = MVT::v2f64;
13241       break;
13242     case Intrinsic::ppc_qpx_qvstfd:
13243       VT = MVT::v4f64;
13244       break;
13245     case Intrinsic::ppc_qpx_qvstfs:
13246       VT = MVT::v4f32;
13247       break;
13248     case Intrinsic::ppc_qpx_qvstfcd:
13249       VT = MVT::v2f64;
13250       break;
13251     case Intrinsic::ppc_qpx_qvstfcs:
13252       VT = MVT::v2f32;
13253       break;
13254     default:
13255       VT = MVT::v4i32;
13256       break;
13257     }
13258 
13259     Info.opc = ISD::INTRINSIC_VOID;
13260     Info.memVT = VT;
13261     Info.ptrVal = I.getArgOperand(1);
13262     Info.offset = -VT.getStoreSize()+1;
13263     Info.size = 2*VT.getStoreSize()-1;
13264     Info.align = 1;
13265     Info.vol = false;
13266     Info.readMem = false;
13267     Info.writeMem = true;
13268     return true;
13269   }
13270   case Intrinsic::ppc_qpx_qvstfda:
13271   case Intrinsic::ppc_qpx_qvstfsa:
13272   case Intrinsic::ppc_qpx_qvstfcda:
13273   case Intrinsic::ppc_qpx_qvstfcsa:
13274   case Intrinsic::ppc_qpx_qvstfiwa: {
13275     EVT VT;
13276     switch (Intrinsic) {
13277     case Intrinsic::ppc_qpx_qvstfda:
13278       VT = MVT::v4f64;
13279       break;
13280     case Intrinsic::ppc_qpx_qvstfsa:
13281       VT = MVT::v4f32;
13282       break;
13283     case Intrinsic::ppc_qpx_qvstfcda:
13284       VT = MVT::v2f64;
13285       break;
13286     case Intrinsic::ppc_qpx_qvstfcsa:
13287       VT = MVT::v2f32;
13288       break;
13289     default:
13290       VT = MVT::v4i32;
13291       break;
13292     }
13293 
13294     Info.opc = ISD::INTRINSIC_VOID;
13295     Info.memVT = VT;
13296     Info.ptrVal = I.getArgOperand(1);
13297     Info.offset = 0;
13298     Info.size = VT.getStoreSize();
13299     Info.align = 1;
13300     Info.vol = false;
13301     Info.readMem = false;
13302     Info.writeMem = true;
13303     return true;
13304   }
13305   default:
13306     break;
13307   }
13308 
13309   return false;
13310 }
13311 
13312 /// getOptimalMemOpType - Returns the target specific optimal type for load
13313 /// and store operations as a result of memset, memcpy, and memmove
13314 /// lowering. If DstAlign is zero that means it's safe to destination
13315 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
13316 /// means there isn't a need to check it against alignment requirement,
13317 /// probably because the source does not need to be loaded. If 'IsMemset' is
13318 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
13319 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
13320 /// source is constant so it does not need to be loaded.
13321 /// It returns EVT::Other if the type should be determined using generic
13322 /// target-independent logic.
13323 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
13324                                            unsigned DstAlign, unsigned SrcAlign,
13325                                            bool IsMemset, bool ZeroMemset,
13326                                            bool MemcpyStrSrc,
13327                                            MachineFunction &MF) const {
13328   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
13329     const Function *F = MF.getFunction();
13330     // When expanding a memset, require at least two QPX instructions to cover
13331     // the cost of loading the value to be stored from the constant pool.
13332     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
13333        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
13334         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
13335       return MVT::v4f64;
13336     }
13337 
13338     // We should use Altivec/VSX loads and stores when available. For unaligned
13339     // addresses, unaligned VSX loads are only fast starting with the P8.
13340     if (Subtarget.hasAltivec() && Size >= 16 &&
13341         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
13342          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
13343       return MVT::v4i32;
13344   }
13345 
13346   if (Subtarget.isPPC64()) {
13347     return MVT::i64;
13348   }
13349 
13350   return MVT::i32;
13351 }
13352 
13353 /// \brief Returns true if it is beneficial to convert a load of a constant
13354 /// to just the constant itself.
13355 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13356                                                           Type *Ty) const {
13357   assert(Ty->isIntegerTy());
13358 
13359   unsigned BitSize = Ty->getPrimitiveSizeInBits();
13360   return !(BitSize == 0 || BitSize > 64);
13361 }
13362 
13363 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13364   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13365     return false;
13366   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13367   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13368   return NumBits1 == 64 && NumBits2 == 32;
13369 }
13370 
13371 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13372   if (!VT1.isInteger() || !VT2.isInteger())
13373     return false;
13374   unsigned NumBits1 = VT1.getSizeInBits();
13375   unsigned NumBits2 = VT2.getSizeInBits();
13376   return NumBits1 == 64 && NumBits2 == 32;
13377 }
13378 
13379 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13380   // Generally speaking, zexts are not free, but they are free when they can be
13381   // folded with other operations.
13382   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
13383     EVT MemVT = LD->getMemoryVT();
13384     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
13385          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
13386         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
13387          LD->getExtensionType() == ISD::ZEXTLOAD))
13388       return true;
13389   }
13390 
13391   // FIXME: Add other cases...
13392   //  - 32-bit shifts with a zext to i64
13393   //  - zext after ctlz, bswap, etc.
13394   //  - zext after and by a constant mask
13395 
13396   return TargetLowering::isZExtFree(Val, VT2);
13397 }
13398 
13399 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
13400   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
13401          "invalid fpext types");
13402   return true;
13403 }
13404 
13405 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13406   return isInt<16>(Imm) || isUInt<16>(Imm);
13407 }
13408 
13409 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13410   return isInt<16>(Imm) || isUInt<16>(Imm);
13411 }
13412 
13413 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
13414                                                        unsigned,
13415                                                        unsigned,
13416                                                        bool *Fast) const {
13417   if (DisablePPCUnaligned)
13418     return false;
13419 
13420   // PowerPC supports unaligned memory access for simple non-vector types.
13421   // Although accessing unaligned addresses is not as efficient as accessing
13422   // aligned addresses, it is generally more efficient than manual expansion,
13423   // and generally only traps for software emulation when crossing page
13424   // boundaries.
13425 
13426   if (!VT.isSimple())
13427     return false;
13428 
13429   if (VT.getSimpleVT().isVector()) {
13430     if (Subtarget.hasVSX()) {
13431       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
13432           VT != MVT::v4f32 && VT != MVT::v4i32)
13433         return false;
13434     } else {
13435       return false;
13436     }
13437   }
13438 
13439   if (VT == MVT::ppcf128)
13440     return false;
13441 
13442   if (Fast)
13443     *Fast = true;
13444 
13445   return true;
13446 }
13447 
13448 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13449   VT = VT.getScalarType();
13450 
13451   if (!VT.isSimple())
13452     return false;
13453 
13454   switch (VT.getSimpleVT().SimpleTy) {
13455   case MVT::f32:
13456   case MVT::f64:
13457     return true;
13458   default:
13459     break;
13460   }
13461 
13462   return false;
13463 }
13464 
13465 const MCPhysReg *
13466 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
13467   // LR is a callee-save register, but we must treat it as clobbered by any call
13468   // site. Hence we include LR in the scratch registers, which are in turn added
13469   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
13470   // to CTR, which is used by any indirect call.
13471   static const MCPhysReg ScratchRegs[] = {
13472     PPC::X12, PPC::LR8, PPC::CTR8, 0
13473   };
13474 
13475   return ScratchRegs;
13476 }
13477 
13478 unsigned PPCTargetLowering::getExceptionPointerRegister(
13479     const Constant *PersonalityFn) const {
13480   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
13481 }
13482 
13483 unsigned PPCTargetLowering::getExceptionSelectorRegister(
13484     const Constant *PersonalityFn) const {
13485   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
13486 }
13487 
13488 bool
13489 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
13490                      EVT VT , unsigned DefinedValues) const {
13491   if (VT == MVT::v2i64)
13492     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
13493 
13494   if (Subtarget.hasVSX() || Subtarget.hasQPX())
13495     return true;
13496 
13497   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
13498 }
13499 
13500 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
13501   if (DisableILPPref || Subtarget.enableMachineScheduler())
13502     return TargetLowering::getSchedulingPreference(N);
13503 
13504   return Sched::ILP;
13505 }
13506 
13507 // Create a fast isel object.
13508 FastISel *
13509 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
13510                                   const TargetLibraryInfo *LibInfo) const {
13511   return PPC::createFastISel(FuncInfo, LibInfo);
13512 }
13513 
13514 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13515   if (Subtarget.isDarwinABI()) return;
13516   if (!Subtarget.isPPC64()) return;
13517 
13518   // Update IsSplitCSR in PPCFunctionInfo
13519   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
13520   PFI->setIsSplitCSR(true);
13521 }
13522 
13523 void PPCTargetLowering::insertCopiesSplitCSR(
13524   MachineBasicBlock *Entry,
13525   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13526   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13527   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13528   if (!IStart)
13529     return;
13530 
13531   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13532   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13533   MachineBasicBlock::iterator MBBI = Entry->begin();
13534   for (const MCPhysReg *I = IStart; *I; ++I) {
13535     const TargetRegisterClass *RC = nullptr;
13536     if (PPC::G8RCRegClass.contains(*I))
13537       RC = &PPC::G8RCRegClass;
13538     else if (PPC::F8RCRegClass.contains(*I))
13539       RC = &PPC::F8RCRegClass;
13540     else if (PPC::CRRCRegClass.contains(*I))
13541       RC = &PPC::CRRCRegClass;
13542     else if (PPC::VRRCRegClass.contains(*I))
13543       RC = &PPC::VRRCRegClass;
13544     else
13545       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13546 
13547     unsigned NewVR = MRI->createVirtualRegister(RC);
13548     // Create copy from CSR to a virtual register.
13549     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13550     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13551     // nounwind. If we want to generalize this later, we may need to emit
13552     // CFI pseudo-instructions.
13553     assert(Entry->getParent()->getFunction()->hasFnAttribute(
13554              Attribute::NoUnwind) &&
13555            "Function should be nounwind in insertCopiesSplitCSR!");
13556     Entry->addLiveIn(*I);
13557     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13558       .addReg(*I);
13559 
13560     // Insert the copy-back instructions right before the terminator
13561     for (auto *Exit : Exits)
13562       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13563               TII->get(TargetOpcode::COPY), *I)
13564         .addReg(NewVR);
13565   }
13566 }
13567 
13568 // Override to enable LOAD_STACK_GUARD lowering on Linux.
13569 bool PPCTargetLowering::useLoadStackGuardNode() const {
13570   if (!Subtarget.isTargetLinux())
13571     return TargetLowering::useLoadStackGuardNode();
13572   return true;
13573 }
13574 
13575 // Override to disable global variable loading on Linux.
13576 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
13577   if (!Subtarget.isTargetLinux())
13578     return TargetLowering::insertSSPDeclarations(M);
13579 }
13580 
13581 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13582   if (!VT.isSimple() || !Subtarget.hasVSX())
13583     return false;
13584 
13585   switch(VT.getSimpleVT().SimpleTy) {
13586   default:
13587     // For FP types that are currently not supported by PPC backend, return
13588     // false. Examples: f16, f80.
13589     return false;
13590   case MVT::f32:
13591   case MVT::f64:
13592   case MVT::ppcf128:
13593     return Imm.isPosZero();
13594   }
13595 }
13596 
13597 // For vector shift operation op, fold
13598 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
13599 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
13600                                   SelectionDAG &DAG) {
13601   SDValue N0 = N->getOperand(0);
13602   SDValue N1 = N->getOperand(1);
13603   EVT VT = N0.getValueType();
13604   unsigned OpSizeInBits = VT.getScalarSizeInBits();
13605   unsigned Opcode = N->getOpcode();
13606   unsigned TargetOpcode;
13607 
13608   switch (Opcode) {
13609   default:
13610     llvm_unreachable("Unexpected shift operation");
13611   case ISD::SHL:
13612     TargetOpcode = PPCISD::SHL;
13613     break;
13614   case ISD::SRL:
13615     TargetOpcode = PPCISD::SRL;
13616     break;
13617   case ISD::SRA:
13618     TargetOpcode = PPCISD::SRA;
13619     break;
13620   }
13621 
13622   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
13623       N1->getOpcode() == ISD::AND)
13624     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
13625       if (Mask->getZExtValue() == OpSizeInBits - 1)
13626         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
13627 
13628   return SDValue();
13629 }
13630 
13631 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
13632   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13633     return Value;
13634 
13635   return SDValue();
13636 }
13637 
13638 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
13639   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13640     return Value;
13641 
13642   return SDValue();
13643 }
13644 
13645 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13646   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13647     return Value;
13648 
13649   return SDValue();
13650 }
13651