Bug Summary

File:llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1158, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name PPCISelLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fdenormal-fp-math=ieee,ieee -fdenormal-fp-math-f32=ieee,ieee -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/build-llvm/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/build-llvm/lib/Target/PowerPC -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b=. -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-02-26-193302-13812-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp

/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp

1//===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the PPCISelLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "PPCISelLowering.h"
14#include "MCTargetDesc/PPCPredicates.h"
15#include "PPC.h"
16#include "PPCCCState.h"
17#include "PPCCallingConv.h"
18#include "PPCFrameLowering.h"
19#include "PPCInstrInfo.h"
20#include "PPCMachineFunctionInfo.h"
21#include "PPCPerfectShuffle.h"
22#include "PPCRegisterInfo.h"
23#include "PPCSubtarget.h"
24#include "PPCTargetMachine.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/None.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/ADT/StringSwitch.h"
37#include "llvm/CodeGen/CallingConvLower.h"
38#include "llvm/CodeGen/ISDOpcodes.h"
39#include "llvm/CodeGen/MachineBasicBlock.h"
40#include "llvm/CodeGen/MachineFrameInfo.h"
41#include "llvm/CodeGen/MachineFunction.h"
42#include "llvm/CodeGen/MachineInstr.h"
43#include "llvm/CodeGen/MachineInstrBuilder.h"
44#include "llvm/CodeGen/MachineJumpTableInfo.h"
45#include "llvm/CodeGen/MachineLoopInfo.h"
46#include "llvm/CodeGen/MachineMemOperand.h"
47#include "llvm/CodeGen/MachineModuleInfo.h"
48#include "llvm/CodeGen/MachineOperand.h"
49#include "llvm/CodeGen/MachineRegisterInfo.h"
50#include "llvm/CodeGen/RuntimeLibcalls.h"
51#include "llvm/CodeGen/SelectionDAG.h"
52#include "llvm/CodeGen/SelectionDAGNodes.h"
53#include "llvm/CodeGen/TargetInstrInfo.h"
54#include "llvm/CodeGen/TargetLowering.h"
55#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56#include "llvm/CodeGen/TargetRegisterInfo.h"
57#include "llvm/CodeGen/ValueTypes.h"
58#include "llvm/IR/CallSite.h"
59#include "llvm/IR/CallingConv.h"
60#include "llvm/IR/Constant.h"
61#include "llvm/IR/Constants.h"
62#include "llvm/IR/DataLayout.h"
63#include "llvm/IR/DebugLoc.h"
64#include "llvm/IR/DerivedTypes.h"
65#include "llvm/IR/Function.h"
66#include "llvm/IR/GlobalValue.h"
67#include "llvm/IR/IRBuilder.h"
68#include "llvm/IR/Instructions.h"
69#include "llvm/IR/Intrinsics.h"
70#include "llvm/IR/IntrinsicsPowerPC.h"
71#include "llvm/IR/Module.h"
72#include "llvm/IR/Type.h"
73#include "llvm/IR/Use.h"
74#include "llvm/IR/Value.h"
75#include "llvm/MC/MCContext.h"
76#include "llvm/MC/MCExpr.h"
77#include "llvm/MC/MCRegisterInfo.h"
78#include "llvm/MC/MCSymbolXCOFF.h"
79#include "llvm/Support/AtomicOrdering.h"
80#include "llvm/Support/BranchProbability.h"
81#include "llvm/Support/Casting.h"
82#include "llvm/Support/CodeGen.h"
83#include "llvm/Support/CommandLine.h"
84#include "llvm/Support/Compiler.h"
85#include "llvm/Support/Debug.h"
86#include "llvm/Support/ErrorHandling.h"
87#include "llvm/Support/Format.h"
88#include "llvm/Support/KnownBits.h"
89#include "llvm/Support/MachineValueType.h"
90#include "llvm/Support/MathExtras.h"
91#include "llvm/Support/raw_ostream.h"
92#include "llvm/Target/TargetMachine.h"
93#include "llvm/Target/TargetOptions.h"
94#include <algorithm>
95#include <cassert>
96#include <cstdint>
97#include <iterator>
98#include <list>
99#include <utility>
100#include <vector>
101
102using namespace llvm;
103
104#define DEBUG_TYPE"ppc-lowering" "ppc-lowering"
105
106static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108
109static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111
112static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114
115static cl::opt<bool> DisableSCO("disable-ppc-sco",
116cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117
118static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120
121static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
122cl::desc("enable quad precision float support on ppc"), cl::Hidden);
123
124static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
125cl::desc("use absolute jump tables on ppc"), cl::Hidden);
126
127STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"ppc-lowering", "NumTailCalls"
, "Number of tail calls"}
;
128STATISTIC(NumSiblingCalls, "Number of sibling calls")static llvm::Statistic NumSiblingCalls = {"ppc-lowering", "NumSiblingCalls"
, "Number of sibling calls"}
;
129
130static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
131
132static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
133
134// FIXME: Remove this once the bug has been fixed!
135extern cl::opt<bool> ANDIGlueBug;
136
137PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
138 const PPCSubtarget &STI)
139 : TargetLowering(TM), Subtarget(STI) {
140 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
141 // arguments are at least 4/8 bytes aligned.
142 bool isPPC64 = Subtarget.isPPC64();
143 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
144
145 // Set up the register classes.
146 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
147 if (!useSoftFloat()) {
148 if (hasSPE()) {
149 addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
150 addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
151 } else {
152 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
153 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
154 }
155 }
156
157 // Match BITREVERSE to customized fast code sequence in the td file.
158 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
159 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
160
161 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
162 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
163
164 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
165 for (MVT VT : MVT::integer_valuetypes()) {
166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
167 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
168 }
169
170 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
171
172 // PowerPC has pre-inc load and store's.
173 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
174 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
175 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
176 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
177 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
178 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
179 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
180 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
181 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
182 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
183 if (!Subtarget.hasSPE()) {
184 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
185 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
186 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
187 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
188 }
189
190 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
191 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
192 for (MVT VT : ScalarIntVTs) {
193 setOperationAction(ISD::ADDC, VT, Legal);
194 setOperationAction(ISD::ADDE, VT, Legal);
195 setOperationAction(ISD::SUBC, VT, Legal);
196 setOperationAction(ISD::SUBE, VT, Legal);
197 }
198
199 if (Subtarget.useCRBits()) {
200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
201
202 if (isPPC64 || Subtarget.hasFPCVT()) {
203 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
204 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
205 isPPC64 ? MVT::i64 : MVT::i32);
206 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
207 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
208 isPPC64 ? MVT::i64 : MVT::i32);
209 } else {
210 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
211 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
212 }
213
214 // PowerPC does not support direct load/store of condition registers.
215 setOperationAction(ISD::LOAD, MVT::i1, Custom);
216 setOperationAction(ISD::STORE, MVT::i1, Custom);
217
218 // FIXME: Remove this once the ANDI glue bug is fixed:
219 if (ANDIGlueBug)
220 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
221
222 for (MVT VT : MVT::integer_valuetypes()) {
223 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
224 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
225 setTruncStoreAction(VT, MVT::i1, Expand);
226 }
227
228 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
229 }
230
231 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
232 // PPC (the libcall is not available).
233 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
234 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
235
236 // We do not currently implement these libm ops for PowerPC.
237 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
238 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
239 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
240 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
241 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
242 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
243
244 // PowerPC has no SREM/UREM instructions unless we are on P9
245 // On P9 we may use a hardware instruction to compute the remainder.
246 // The instructions are not legalized directly because in the cases where the
247 // result of both the remainder and the division is required it is more
248 // efficient to compute the remainder from the result of the division rather
249 // than use the remainder instruction.
250 if (Subtarget.isISA3_0()) {
251 setOperationAction(ISD::SREM, MVT::i32, Custom);
252 setOperationAction(ISD::UREM, MVT::i32, Custom);
253 setOperationAction(ISD::SREM, MVT::i64, Custom);
254 setOperationAction(ISD::UREM, MVT::i64, Custom);
255 } else {
256 setOperationAction(ISD::SREM, MVT::i32, Expand);
257 setOperationAction(ISD::UREM, MVT::i32, Expand);
258 setOperationAction(ISD::SREM, MVT::i64, Expand);
259 setOperationAction(ISD::UREM, MVT::i64, Expand);
260 }
261
262 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
263 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
264 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
265 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
266 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
267 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
268 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
269 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
270 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
271
272 // We don't support sin/cos/sqrt/fmod/pow
273 setOperationAction(ISD::FSIN , MVT::f64, Expand);
274 setOperationAction(ISD::FCOS , MVT::f64, Expand);
275 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
276 setOperationAction(ISD::FREM , MVT::f64, Expand);
277 setOperationAction(ISD::FPOW , MVT::f64, Expand);
278 setOperationAction(ISD::FSIN , MVT::f32, Expand);
279 setOperationAction(ISD::FCOS , MVT::f32, Expand);
280 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
281 setOperationAction(ISD::FREM , MVT::f32, Expand);
282 setOperationAction(ISD::FPOW , MVT::f32, Expand);
283 if (Subtarget.hasSPE()) {
284 setOperationAction(ISD::FMA , MVT::f64, Expand);
285 setOperationAction(ISD::FMA , MVT::f32, Expand);
286 } else {
287 setOperationAction(ISD::FMA , MVT::f64, Legal);
288 setOperationAction(ISD::FMA , MVT::f32, Legal);
289 }
290
291 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
292
293 // If we're enabling GP optimizations, use hardware square root
294 if (!Subtarget.hasFSQRT() &&
295 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
296 Subtarget.hasFRE()))
297 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
298
299 if (!Subtarget.hasFSQRT() &&
300 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
301 Subtarget.hasFRES()))
302 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
303
304 if (Subtarget.hasFCPSGN()) {
305 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
306 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
307 } else {
308 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
309 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
310 }
311
312 if (Subtarget.hasFPRND()) {
313 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
314 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
315 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
316 setOperationAction(ISD::FROUND, MVT::f64, Legal);
317
318 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
319 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
320 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
321 setOperationAction(ISD::FROUND, MVT::f32, Legal);
322 }
323
324 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
325 // to speed up scalar BSWAP64.
326 // CTPOP or CTTZ were introduced in P8/P9 respectively
327 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
328 if (Subtarget.hasP9Vector())
329 setOperationAction(ISD::BSWAP, MVT::i64 , Custom);
330 else
331 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
332 if (Subtarget.isISA3_0()) {
333 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
334 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
335 } else {
336 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
337 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
338 }
339
340 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
341 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
342 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
343 } else {
344 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
345 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
346 }
347
348 // PowerPC does not have ROTR
349 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
350 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
351
352 if (!Subtarget.useCRBits()) {
353 // PowerPC does not have Select
354 setOperationAction(ISD::SELECT, MVT::i32, Expand);
355 setOperationAction(ISD::SELECT, MVT::i64, Expand);
356 setOperationAction(ISD::SELECT, MVT::f32, Expand);
357 setOperationAction(ISD::SELECT, MVT::f64, Expand);
358 }
359
360 // PowerPC wants to turn select_cc of FP into fsel when possible.
361 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
362 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
363
364 // PowerPC wants to optimize integer setcc a bit
365 if (!Subtarget.useCRBits())
366 setOperationAction(ISD::SETCC, MVT::i32, Custom);
367
368 // PowerPC does not have BRCOND which requires SetCC
369 if (!Subtarget.useCRBits())
370 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
371
372 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
373
374 if (Subtarget.hasSPE()) {
375 // SPE has built-in conversions
376 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
377 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
378 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
379 } else {
380 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
381 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
382
383 // PowerPC does not have [U|S]INT_TO_FP
384 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
385 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
386 }
387
388 if (Subtarget.hasDirectMove() && isPPC64) {
389 setOperationAction(ISD::BITCAST, MVT::f32, Legal);
390 setOperationAction(ISD::BITCAST, MVT::i32, Legal);
391 setOperationAction(ISD::BITCAST, MVT::i64, Legal);
392 setOperationAction(ISD::BITCAST, MVT::f64, Legal);
393 if (TM.Options.UnsafeFPMath) {
394 setOperationAction(ISD::LRINT, MVT::f64, Legal);
395 setOperationAction(ISD::LRINT, MVT::f32, Legal);
396 setOperationAction(ISD::LLRINT, MVT::f64, Legal);
397 setOperationAction(ISD::LLRINT, MVT::f32, Legal);
398 setOperationAction(ISD::LROUND, MVT::f64, Legal);
399 setOperationAction(ISD::LROUND, MVT::f32, Legal);
400 setOperationAction(ISD::LLROUND, MVT::f64, Legal);
401 setOperationAction(ISD::LLROUND, MVT::f32, Legal);
402 }
403 } else {
404 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
405 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
406 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
407 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
408 }
409
410 // We cannot sextinreg(i1). Expand to shifts.
411 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
412
413 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
414 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
415 // support continuation, user-level threading, and etc.. As a result, no
416 // other SjLj exception interfaces are implemented and please don't build
417 // your own exception handling based on them.
418 // LLVM/Clang supports zero-cost DWARF exception handling.
419 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
420 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
421
422 // We want to legalize GlobalAddress and ConstantPool nodes into the
423 // appropriate instructions to materialize the address.
424 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
425 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
426 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
427 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
428 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
429 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
430 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
431 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
432 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
433 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
434
435 // TRAP is legal.
436 setOperationAction(ISD::TRAP, MVT::Other, Legal);
437
438 // TRAMPOLINE is custom lowered.
439 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
440 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
441
442 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
443 setOperationAction(ISD::VASTART , MVT::Other, Custom);
444
445 if (Subtarget.is64BitELFABI()) {
446 // VAARG always uses double-word chunks, so promote anything smaller.
447 setOperationAction(ISD::VAARG, MVT::i1, Promote);
448 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
449 setOperationAction(ISD::VAARG, MVT::i8, Promote);
450 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
451 setOperationAction(ISD::VAARG, MVT::i16, Promote);
452 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
453 setOperationAction(ISD::VAARG, MVT::i32, Promote);
454 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
455 setOperationAction(ISD::VAARG, MVT::Other, Expand);
456 } else if (Subtarget.is32BitELFABI()) {
457 // VAARG is custom lowered with the 32-bit SVR4 ABI.
458 setOperationAction(ISD::VAARG, MVT::Other, Custom);
459 setOperationAction(ISD::VAARG, MVT::i64, Custom);
460 } else
461 setOperationAction(ISD::VAARG, MVT::Other, Expand);
462
463 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
464 if (Subtarget.is32BitELFABI())
465 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
466 else
467 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
468
469 // Use the default implementation.
470 setOperationAction(ISD::VAEND , MVT::Other, Expand);
471 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
472 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
473 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
474 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
475 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
476 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
477 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
478 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
479
480 // We want to custom lower some of our intrinsics.
481 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
482
483 // To handle counter-based loop conditions.
484 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
485
486 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
487 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
488 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
489 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
490
491 // Comparisons that require checking two conditions.
492 if (Subtarget.hasSPE()) {
493 setCondCodeAction(ISD::SETO, MVT::f32, Expand);
494 setCondCodeAction(ISD::SETO, MVT::f64, Expand);
495 setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
496 setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
497 }
498 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
499 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
500 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
501 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
502 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
503 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
504 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
505 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
506 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
507 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
508 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
509 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
510
511 if (Subtarget.has64BitSupport()) {
512 // They also have instructions for converting between i64 and fp.
513 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
514 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
515 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
516 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
517 // This is just the low 32 bits of a (signed) fp->i64 conversion.
518 // We cannot do this with Promote because i64 is not a legal type.
519 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
520
521 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
522 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
523 } else {
524 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
525 if (Subtarget.hasSPE())
526 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
527 else
528 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
529 }
530
531 // With the instructions enabled under FPCVT, we can do everything.
532 if (Subtarget.hasFPCVT()) {
533 if (Subtarget.has64BitSupport()) {
534 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
535 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
536 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
537 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
538 }
539
540 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
541 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
542 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
543 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
544 }
545
546 if (Subtarget.use64BitRegs()) {
547 // 64-bit PowerPC implementations can support i64 types directly
548 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
549 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
550 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
551 // 64-bit PowerPC wants to expand i128 shifts itself.
552 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
553 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
554 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
555 } else {
556 // 32-bit PowerPC wants to expand i64 shifts itself.
557 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
558 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
559 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
560 }
561
562 if (Subtarget.hasVSX()) {
563 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
564 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
565 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
566 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
567 }
568
569 if (Subtarget.hasAltivec()) {
570 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
571 setOperationAction(ISD::SADDSAT, VT, Legal);
572 setOperationAction(ISD::SSUBSAT, VT, Legal);
573 setOperationAction(ISD::UADDSAT, VT, Legal);
574 setOperationAction(ISD::USUBSAT, VT, Legal);
575 }
576 // First set operation action for all vector types to expand. Then we
577 // will selectively turn on ones that can be effectively codegen'd.
578 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
579 // add/sub are legal for all supported vector VT's.
580 setOperationAction(ISD::ADD, VT, Legal);
581 setOperationAction(ISD::SUB, VT, Legal);
582
583 // For v2i64, these are only valid with P8Vector. This is corrected after
584 // the loop.
585 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
586 setOperationAction(ISD::SMAX, VT, Legal);
587 setOperationAction(ISD::SMIN, VT, Legal);
588 setOperationAction(ISD::UMAX, VT, Legal);
589 setOperationAction(ISD::UMIN, VT, Legal);
590 }
591 else {
592 setOperationAction(ISD::SMAX, VT, Expand);
593 setOperationAction(ISD::SMIN, VT, Expand);
594 setOperationAction(ISD::UMAX, VT, Expand);
595 setOperationAction(ISD::UMIN, VT, Expand);
596 }
597
598 if (Subtarget.hasVSX()) {
599 setOperationAction(ISD::FMAXNUM, VT, Legal);
600 setOperationAction(ISD::FMINNUM, VT, Legal);
601 }
602
603 // Vector instructions introduced in P8
604 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
605 setOperationAction(ISD::CTPOP, VT, Legal);
606 setOperationAction(ISD::CTLZ, VT, Legal);
607 }
608 else {
609 setOperationAction(ISD::CTPOP, VT, Expand);
610 setOperationAction(ISD::CTLZ, VT, Expand);
611 }
612
613 // Vector instructions introduced in P9
614 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
615 setOperationAction(ISD::CTTZ, VT, Legal);
616 else
617 setOperationAction(ISD::CTTZ, VT, Expand);
618
619 // We promote all shuffles to v16i8.
620 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
621 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
622
623 // We promote all non-typed operations to v4i32.
624 setOperationAction(ISD::AND , VT, Promote);
625 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
626 setOperationAction(ISD::OR , VT, Promote);
627 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
628 setOperationAction(ISD::XOR , VT, Promote);
629 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
630 setOperationAction(ISD::LOAD , VT, Promote);
631 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
632 setOperationAction(ISD::SELECT, VT, Promote);
633 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
634 setOperationAction(ISD::VSELECT, VT, Legal);
635 setOperationAction(ISD::SELECT_CC, VT, Promote);
636 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
637 setOperationAction(ISD::STORE, VT, Promote);
638 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
639
640 // No other operations are legal.
641 setOperationAction(ISD::MUL , VT, Expand);
642 setOperationAction(ISD::SDIV, VT, Expand);
643 setOperationAction(ISD::SREM, VT, Expand);
644 setOperationAction(ISD::UDIV, VT, Expand);
645 setOperationAction(ISD::UREM, VT, Expand);
646 setOperationAction(ISD::FDIV, VT, Expand);
647 setOperationAction(ISD::FREM, VT, Expand);
648 setOperationAction(ISD::FNEG, VT, Expand);
649 setOperationAction(ISD::FSQRT, VT, Expand);
650 setOperationAction(ISD::FLOG, VT, Expand);
651 setOperationAction(ISD::FLOG10, VT, Expand);
652 setOperationAction(ISD::FLOG2, VT, Expand);
653 setOperationAction(ISD::FEXP, VT, Expand);
654 setOperationAction(ISD::FEXP2, VT, Expand);
655 setOperationAction(ISD::FSIN, VT, Expand);
656 setOperationAction(ISD::FCOS, VT, Expand);
657 setOperationAction(ISD::FABS, VT, Expand);
658 setOperationAction(ISD::FFLOOR, VT, Expand);
659 setOperationAction(ISD::FCEIL, VT, Expand);
660 setOperationAction(ISD::FTRUNC, VT, Expand);
661 setOperationAction(ISD::FRINT, VT, Expand);
662 setOperationAction(ISD::FNEARBYINT, VT, Expand);
663 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
664 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
665 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
666 setOperationAction(ISD::MULHU, VT, Expand);
667 setOperationAction(ISD::MULHS, VT, Expand);
668 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
669 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
670 setOperationAction(ISD::UDIVREM, VT, Expand);
671 setOperationAction(ISD::SDIVREM, VT, Expand);
672 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
673 setOperationAction(ISD::FPOW, VT, Expand);
674 setOperationAction(ISD::BSWAP, VT, Expand);
675 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
676 setOperationAction(ISD::ROTL, VT, Expand);
677 setOperationAction(ISD::ROTR, VT, Expand);
678
679 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
680 setTruncStoreAction(VT, InnerVT, Expand);
681 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
682 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
683 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
684 }
685 }
686 if (!Subtarget.hasP8Vector()) {
687 setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
688 setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
689 setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
690 setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
691 }
692
693 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
694 setOperationAction(ISD::ABS, VT, Custom);
695
696 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
697 // with merges, splats, etc.
698 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
699
700 // Vector truncates to sub-word integer that fit in an Altivec/VSX register
701 // are cheap, so handle them before they get expanded to scalar.
702 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
703 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
704 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
705 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
706 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
707
708 setOperationAction(ISD::AND , MVT::v4i32, Legal);
709 setOperationAction(ISD::OR , MVT::v4i32, Legal);
710 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
711 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
712 setOperationAction(ISD::SELECT, MVT::v4i32,
713 Subtarget.useCRBits() ? Legal : Expand);
714 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
715 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
716 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
717 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
718 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
719 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
720 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
721 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
722 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
723
724 // Without hasP8Altivec set, v2i64 SMAX isn't available.
725 // But ABS custom lowering requires SMAX support.
726 if (!Subtarget.hasP8Altivec())
727 setOperationAction(ISD::ABS, MVT::v2i64, Expand);
728
729 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
730 if (Subtarget.hasAltivec())
731 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
732 setOperationAction(ISD::ROTL, VT, Legal);
733 // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
734 if (Subtarget.hasP8Altivec())
735 setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
736
737 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
738 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
739 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
740 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
741
742 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
743 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
744
745 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
746 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
747 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
748 }
749
750 if (Subtarget.hasP8Altivec())
751 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
752 else
753 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
754
755 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
756 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
757
758 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
759 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
760
761 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
762 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
763 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
764 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
765
766 // Altivec does not contain unordered floating-point compare instructions
767 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
768 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
769 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
770 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
771
772 if (Subtarget.hasVSX()) {
773 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
775 if (Subtarget.hasP8Vector()) {
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
777 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
778 }
779 if (Subtarget.hasDirectMove() && isPPC64) {
780 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
781 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
782 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
783 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
784 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
785 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
786 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
787 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
788 }
789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
790
791 // The nearbyint variants are not allowed to raise the inexact exception
792 // so we can only code-gen them with unsafe math.
793 if (TM.Options.UnsafeFPMath) {
794 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
795 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
796 }
797
798 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
799 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
800 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
801 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
802 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
803 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
804 setOperationAction(ISD::FROUND, MVT::f64, Legal);
805 setOperationAction(ISD::FRINT, MVT::f64, Legal);
806
807 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
808 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
809 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
810 setOperationAction(ISD::FROUND, MVT::f32, Legal);
811 setOperationAction(ISD::FRINT, MVT::f32, Legal);
812
813 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
814 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
815
816 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
817 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
818
819 // Share the Altivec comparison restrictions.
820 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
821 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
822 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
823 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
824
825 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
826 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
827
828 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
829
830 if (Subtarget.hasP8Vector())
831 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
832
833 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
834
835 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
836 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
837 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
838
839 if (Subtarget.hasP8Altivec()) {
840 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
841 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
842 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
843
844 // 128 bit shifts can be accomplished via 3 instructions for SHL and
845 // SRL, but not for SRA because of the instructions available:
846 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
847 // doing
848 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
849 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
850 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
851
852 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
853 }
854 else {
855 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
856 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
857 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
858
859 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
860
861 // VSX v2i64 only supports non-arithmetic operations.
862 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
863 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
864 }
865
866 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
867 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
868 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
869 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
870
871 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
872
873 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
874 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
875 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
876 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
877
878 // Custom handling for partial vectors of integers converted to
879 // floating point. We already have optimal handling for v2i32 through
880 // the DAG combine, so those aren't necessary.
881 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
882 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
883 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
884 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
885 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
886 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
887 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
888 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
889
890 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
891 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
892 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
893 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
894 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
895 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
896
897 if (Subtarget.hasDirectMove())
898 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
899 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
900
901 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
902 }
903
904 if (Subtarget.hasP8Altivec()) {
905 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
906 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
907 }
908
909 if (Subtarget.hasP9Vector()) {
910 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
912
913 // 128 bit shifts can be accomplished via 3 instructions for SHL and
914 // SRL, but not for SRA because of the instructions available:
915 // VS{RL} and VS{RL}O.
916 setOperationAction(ISD::SHL, MVT::v1i128, Legal);
917 setOperationAction(ISD::SRL, MVT::v1i128, Legal);
918 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
919
920 if (EnableQuadPrecision) {
921 addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
922 setOperationAction(ISD::FADD, MVT::f128, Legal);
923 setOperationAction(ISD::FSUB, MVT::f128, Legal);
924 setOperationAction(ISD::FDIV, MVT::f128, Legal);
925 setOperationAction(ISD::FMUL, MVT::f128, Legal);
926 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
927 // No extending loads to f128 on PPC.
928 for (MVT FPT : MVT::fp_valuetypes())
929 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
930 setOperationAction(ISD::FMA, MVT::f128, Legal);
931 setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
932 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
933 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
934 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
935 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
936 setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
937
938 setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
939 setOperationAction(ISD::FRINT, MVT::f128, Legal);
940 setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
941 setOperationAction(ISD::FCEIL, MVT::f128, Legal);
942 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
943 setOperationAction(ISD::FROUND, MVT::f128, Legal);
944
945 setOperationAction(ISD::SELECT, MVT::f128, Expand);
946 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
947 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
948 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
949 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
950 setOperationAction(ISD::BITCAST, MVT::i128, Custom);
951 // No implementation for these ops for PowerPC.
952 setOperationAction(ISD::FSIN , MVT::f128, Expand);
953 setOperationAction(ISD::FCOS , MVT::f128, Expand);
954 setOperationAction(ISD::FPOW, MVT::f128, Expand);
955 setOperationAction(ISD::FPOWI, MVT::f128, Expand);
956 setOperationAction(ISD::FREM, MVT::f128, Expand);
957 }
958 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
959 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
960 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
961 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
962 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
963 }
964
965 if (Subtarget.hasP9Altivec()) {
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
968
969 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal);
970 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
971 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
972 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal);
973 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
974 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
975 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
976 }
977 }
978
979 if (Subtarget.hasQPX()) {
980 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
981 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
982 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
983 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
984
985 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
986 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
987
988 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
989 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
990
991 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
992 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
993
994 if (!Subtarget.useCRBits())
995 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
996 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
997
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
999 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1000 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1001 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1002 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1003 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1004 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1005
1006 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1007 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1008
1009 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1010 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1011
1012 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1013 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1014 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1015 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1016 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1017 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1018 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1019 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1020 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1021 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1022
1023 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1024 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1025
1026 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1027 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1028
1029 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1030
1031 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1032 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1033 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1034 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1035
1036 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1037 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1038
1039 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
1040 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1041
1042 if (!Subtarget.useCRBits())
1043 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1044 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1045
1046 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1047 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1048 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1049 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1050 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1051 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1052 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1053
1054 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1055 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1056
1057 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1058 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1059 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1060 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1061 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1062 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1063 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1064 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1065 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1066 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1067
1068 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1069 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1070
1071 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1072 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1073
1074 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1075
1076 setOperationAction(ISD::AND , MVT::v4i1, Legal);
1077 setOperationAction(ISD::OR , MVT::v4i1, Legal);
1078 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1079
1080 if (!Subtarget.useCRBits())
1081 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1082 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1083
1084 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
1085 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1086
1087 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1088 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1089 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1090 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1091 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1092 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1093 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1094
1095 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1096 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1097
1098 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1099
1100 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1101 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1102 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1103 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1104
1105 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1106 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1107 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1108 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1109
1110 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1111 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1112
1113 // These need to set FE_INEXACT, and so cannot be vectorized here.
1114 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1115 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1116
1117 if (TM.Options.UnsafeFPMath) {
1118 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1119 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1120
1121 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1122 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1123 } else {
1124 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1125 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1126
1127 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1128 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1129 }
1130 }
1131
1132 if (Subtarget.has64BitSupport())
1133 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1134
1135 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1136
1137 if (!isPPC64) {
1138 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
1139 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1140 }
1141
1142 setBooleanContents(ZeroOrOneBooleanContent);
1143
1144 if (Subtarget.hasAltivec()) {
1145 // Altivec instructions set fields to all zeros or all ones.
1146 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1147 }
1148
1149 if (!isPPC64) {
1150 // These libcalls are not available in 32-bit.
1151 setLibcallName(RTLIB::SHL_I128, nullptr);
1152 setLibcallName(RTLIB::SRL_I128, nullptr);
1153 setLibcallName(RTLIB::SRA_I128, nullptr);
1154 }
1155
1156 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1157
1158 // We have target-specific dag combine patterns for the following nodes:
1159 setTargetDAGCombine(ISD::ADD);
1160 setTargetDAGCombine(ISD::SHL);
1161 setTargetDAGCombine(ISD::SRA);
1162 setTargetDAGCombine(ISD::SRL);
1163 setTargetDAGCombine(ISD::MUL);
1164 setTargetDAGCombine(ISD::SINT_TO_FP);
1165 setTargetDAGCombine(ISD::BUILD_VECTOR);
1166 if (Subtarget.hasFPCVT())
1167 setTargetDAGCombine(ISD::UINT_TO_FP);
1168 setTargetDAGCombine(ISD::LOAD);
1169 setTargetDAGCombine(ISD::STORE);
1170 setTargetDAGCombine(ISD::BR_CC);
1171 if (Subtarget.useCRBits())
1172 setTargetDAGCombine(ISD::BRCOND);
1173 setTargetDAGCombine(ISD::BSWAP);
1174 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1175 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1176 setTargetDAGCombine(ISD::INTRINSIC_VOID);
1177
1178 setTargetDAGCombine(ISD::SIGN_EXTEND);
1179 setTargetDAGCombine(ISD::ZERO_EXTEND);
1180 setTargetDAGCombine(ISD::ANY_EXTEND);
1181
1182 setTargetDAGCombine(ISD::TRUNCATE);
1183 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1184
1185
1186 if (Subtarget.useCRBits()) {
1187 setTargetDAGCombine(ISD::TRUNCATE);
1188 setTargetDAGCombine(ISD::SETCC);
1189 setTargetDAGCombine(ISD::SELECT_CC);
1190 }
1191
1192 // Use reciprocal estimates.
1193 if (TM.Options.UnsafeFPMath) {
1194 setTargetDAGCombine(ISD::FDIV);
1195 setTargetDAGCombine(ISD::FSQRT);
1196 }
1197
1198 if (Subtarget.hasP9Altivec()) {
1199 setTargetDAGCombine(ISD::ABS);
1200 setTargetDAGCombine(ISD::VSELECT);
1201 }
1202
1203 if (EnableQuadPrecision) {
1204 setLibcallName(RTLIB::LOG_F128, "logf128");
1205 setLibcallName(RTLIB::LOG2_F128, "log2f128");
1206 setLibcallName(RTLIB::LOG10_F128, "log10f128");
1207 setLibcallName(RTLIB::EXP_F128, "expf128");
1208 setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1209 setLibcallName(RTLIB::SIN_F128, "sinf128");
1210 setLibcallName(RTLIB::COS_F128, "cosf128");
1211 setLibcallName(RTLIB::POW_F128, "powf128");
1212 setLibcallName(RTLIB::FMIN_F128, "fminf128");
1213 setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1214 setLibcallName(RTLIB::POWI_F128, "__powikf2");
1215 setLibcallName(RTLIB::REM_F128, "fmodf128");
1216 }
1217
1218 // With 32 condition bits, we don't need to sink (and duplicate) compares
1219 // aggressively in CodeGenPrep.
1220 if (Subtarget.useCRBits()) {
1221 setHasMultipleConditionRegisters();
1222 setJumpIsExpensive();
1223 }
1224
1225 setMinFunctionAlignment(Align(4));
1226
1227 switch (Subtarget.getCPUDirective()) {
1228 default: break;
1229 case PPC::DIR_970:
1230 case PPC::DIR_A2:
1231 case PPC::DIR_E500:
1232 case PPC::DIR_E500mc:
1233 case PPC::DIR_E5500:
1234 case PPC::DIR_PWR4:
1235 case PPC::DIR_PWR5:
1236 case PPC::DIR_PWR5X:
1237 case PPC::DIR_PWR6:
1238 case PPC::DIR_PWR6X:
1239 case PPC::DIR_PWR7:
1240 case PPC::DIR_PWR8:
1241 case PPC::DIR_PWR9:
1242 case PPC::DIR_PWR_FUTURE:
1243 setPrefLoopAlignment(Align(16));
1244 setPrefFunctionAlignment(Align(16));
1245 break;
1246 }
1247
1248 if (Subtarget.enableMachineScheduler())
1249 setSchedulingPreference(Sched::Source);
1250 else
1251 setSchedulingPreference(Sched::Hybrid);
1252
1253 computeRegisterProperties(STI.getRegisterInfo());
1254
1255 // The Freescale cores do better with aggressive inlining of memcpy and
1256 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1257 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1258 Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1259 MaxStoresPerMemset = 32;
1260 MaxStoresPerMemsetOptSize = 16;
1261 MaxStoresPerMemcpy = 32;
1262 MaxStoresPerMemcpyOptSize = 8;
1263 MaxStoresPerMemmove = 32;
1264 MaxStoresPerMemmoveOptSize = 8;
1265 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1266 // The A2 also benefits from (very) aggressive inlining of memcpy and
1267 // friends. The overhead of a the function call, even when warm, can be
1268 // over one hundred cycles.
1269 MaxStoresPerMemset = 128;
1270 MaxStoresPerMemcpy = 128;
1271 MaxStoresPerMemmove = 128;
1272 MaxLoadsPerMemcmp = 128;
1273 } else {
1274 MaxLoadsPerMemcmp = 8;
1275 MaxLoadsPerMemcmpOptSize = 4;
1276 }
1277}
1278
1279/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1280/// the desired ByVal argument alignment.
1281static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1282 unsigned MaxMaxAlign) {
1283 if (MaxAlign == MaxMaxAlign)
1284 return;
1285 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1286 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1287 MaxAlign = 32;
1288 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1289 MaxAlign = 16;
1290 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1291 unsigned EltAlign = 0;
1292 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1293 if (EltAlign > MaxAlign)
1294 MaxAlign = EltAlign;
1295 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1296 for (auto *EltTy : STy->elements()) {
1297 unsigned EltAlign = 0;
1298 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1299 if (EltAlign > MaxAlign)
1300 MaxAlign = EltAlign;
1301 if (MaxAlign == MaxMaxAlign)
1302 break;
1303 }
1304 }
1305}
1306
1307/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1308/// function arguments in the caller parameter area.
1309unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1310 const DataLayout &DL) const {
1311 // 16byte and wider vectors are passed on 16byte boundary.
1312 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1313 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1314 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1315 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1316 return Align;
1317}
1318
1319bool PPCTargetLowering::useSoftFloat() const {
1320 return Subtarget.useSoftFloat();
1321}
1322
1323bool PPCTargetLowering::hasSPE() const {
1324 return Subtarget.hasSPE();
1325}
1326
1327bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1328 return VT.isScalarInteger();
1329}
1330
1331const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1332 switch ((PPCISD::NodeType)Opcode) {
1333 case PPCISD::FIRST_NUMBER: break;
1334 case PPCISD::FSEL: return "PPCISD::FSEL";
1335 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP";
1336 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP";
1337 case PPCISD::FCFID: return "PPCISD::FCFID";
1338 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1339 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1340 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1341 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1342 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1343 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1344 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1345 case PPCISD::FP_TO_UINT_IN_VSR:
1346 return "PPCISD::FP_TO_UINT_IN_VSR,";
1347 case PPCISD::FP_TO_SINT_IN_VSR:
1348 return "PPCISD::FP_TO_SINT_IN_VSR";
1349 case PPCISD::FRE: return "PPCISD::FRE";
1350 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1351 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1352 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
1353 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
1354 case PPCISD::VPERM: return "PPCISD::VPERM";
1355 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1356 case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1357 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1358 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1359 case PPCISD::CMPB: return "PPCISD::CMPB";
1360 case PPCISD::Hi: return "PPCISD::Hi";
1361 case PPCISD::Lo: return "PPCISD::Lo";
1362 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1363 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1364 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1365 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1366 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1367 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1368 case PPCISD::SRL: return "PPCISD::SRL";
1369 case PPCISD::SRA: return "PPCISD::SRA";
1370 case PPCISD::SHL: return "PPCISD::SHL";
1371 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1372 case PPCISD::CALL: return "PPCISD::CALL";
1373 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1374 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1375 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1376 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1377 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1378 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1379 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1380 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1381 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1382 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1383 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1384 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1385 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1386 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1387 case PPCISD::ANDI_rec_1_EQ_BIT:
1388 return "PPCISD::ANDI_rec_1_EQ_BIT";
1389 case PPCISD::ANDI_rec_1_GT_BIT:
1390 return "PPCISD::ANDI_rec_1_GT_BIT";
1391 case PPCISD::VCMP: return "PPCISD::VCMP";
1392 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1393 case PPCISD::LBRX: return "PPCISD::LBRX";
1394 case PPCISD::STBRX: return "PPCISD::STBRX";
1395 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1396 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1397 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1398 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1399 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1400 case PPCISD::SExtVElems: return "PPCISD::SExtVElems";
1401 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1402 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1403 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE";
1404 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE";
1405 case PPCISD::ST_VSR_SCAL_INT:
1406 return "PPCISD::ST_VSR_SCAL_INT";
1407 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1408 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1409 case PPCISD::BDZ: return "PPCISD::BDZ";
1410 case PPCISD::MFFS: return "PPCISD::MFFS";
1411 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1412 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1413 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1414 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1415 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1416 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1417 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1418 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1419 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1420 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1421 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1422 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1423 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1424 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1425 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1426 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1427 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1428 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1429 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1430 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1431 case PPCISD::SC: return "PPCISD::SC";
1432 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1433 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1434 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1435 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1436 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1437 case PPCISD::VABSD: return "PPCISD::VABSD";
1438 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1439 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1440 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1441 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1442 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1443 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1444 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1445 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64";
1446 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE";
1447 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
1448 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
1449 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF";
1450 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT";
1451 }
1452 return nullptr;
1453}
1454
1455EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1456 EVT VT) const {
1457 if (!VT.isVector())
1458 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1459
1460 if (Subtarget.hasQPX())
1461 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1462
1463 return VT.changeVectorElementTypeToInteger();
1464}
1465
1466bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1467 assert(VT.isFloatingPoint() && "Non-floating-point FMA?")((VT.isFloatingPoint() && "Non-floating-point FMA?") ?
static_cast<void> (0) : __assert_fail ("VT.isFloatingPoint() && \"Non-floating-point FMA?\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1467, __PRETTY_FUNCTION__))
;
1468 return true;
1469}
1470
1471//===----------------------------------------------------------------------===//
1472// Node matching predicates, for use by the tblgen matching code.
1473//===----------------------------------------------------------------------===//
1474
1475/// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1476static bool isFloatingPointZero(SDValue Op) {
1477 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
12
Calling 'dyn_cast<llvm::ConstantFPSDNode, llvm::SDValue>'
27
Returning from 'dyn_cast<llvm::ConstantFPSDNode, llvm::SDValue>'
28
Assuming 'CFP' is null
29
Taking false branch
1478 return CFP->getValueAPF().isZero();
1479 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1480 // Maybe this has already been legalized into the constant pool?
1481 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
30
Calling 'SDValue::getOperand'
1482 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1483 return CFP->getValueAPF().isZero();
1484 }
1485 return false;
1486}
1487
1488/// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1489/// true if Op is undef or if it matches the specified value.
1490static bool isConstantOrUndef(int Op, int Val) {
1491 return Op < 0 || Op == Val;
1492}
1493
1494/// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1495/// VPKUHUM instruction.
1496/// The ShuffleKind distinguishes between big-endian operations with
1497/// two different inputs (0), either-endian operations with two identical
1498/// inputs (1), and little-endian operations with two different inputs (2).
1499/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1500bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1501 SelectionDAG &DAG) {
1502 bool IsLE = DAG.getDataLayout().isLittleEndian();
1503 if (ShuffleKind == 0) {
1504 if (IsLE)
1505 return false;
1506 for (unsigned i = 0; i != 16; ++i)
1507 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1508 return false;
1509 } else if (ShuffleKind == 2) {
1510 if (!IsLE)
1511 return false;
1512 for (unsigned i = 0; i != 16; ++i)
1513 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1514 return false;
1515 } else if (ShuffleKind == 1) {
1516 unsigned j = IsLE ? 0 : 1;
1517 for (unsigned i = 0; i != 8; ++i)
1518 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1519 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1520 return false;
1521 }
1522 return true;
1523}
1524
1525/// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1526/// VPKUWUM instruction.
1527/// The ShuffleKind distinguishes between big-endian operations with
1528/// two different inputs (0), either-endian operations with two identical
1529/// inputs (1), and little-endian operations with two different inputs (2).
1530/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1531bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1532 SelectionDAG &DAG) {
1533 bool IsLE = DAG.getDataLayout().isLittleEndian();
1534 if (ShuffleKind == 0) {
1535 if (IsLE)
1536 return false;
1537 for (unsigned i = 0; i != 16; i += 2)
1538 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1539 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1540 return false;
1541 } else if (ShuffleKind == 2) {
1542 if (!IsLE)
1543 return false;
1544 for (unsigned i = 0; i != 16; i += 2)
1545 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1546 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1547 return false;
1548 } else if (ShuffleKind == 1) {
1549 unsigned j = IsLE ? 0 : 2;
1550 for (unsigned i = 0; i != 8; i += 2)
1551 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1552 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1553 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1554 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1555 return false;
1556 }
1557 return true;
1558}
1559
1560/// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1561/// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1562/// current subtarget.
1563///
1564/// The ShuffleKind distinguishes between big-endian operations with
1565/// two different inputs (0), either-endian operations with two identical
1566/// inputs (1), and little-endian operations with two different inputs (2).
1567/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1568bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1569 SelectionDAG &DAG) {
1570 const PPCSubtarget& Subtarget =
1571 static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1572 if (!Subtarget.hasP8Vector())
1573 return false;
1574
1575 bool IsLE = DAG.getDataLayout().isLittleEndian();
1576 if (ShuffleKind == 0) {
1577 if (IsLE)
1578 return false;
1579 for (unsigned i = 0; i != 16; i += 4)
1580 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1581 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1582 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1583 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1584 return false;
1585 } else if (ShuffleKind == 2) {
1586 if (!IsLE)
1587 return false;
1588 for (unsigned i = 0; i != 16; i += 4)
1589 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1590 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1591 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1592 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1593 return false;
1594 } else if (ShuffleKind == 1) {
1595 unsigned j = IsLE ? 0 : 4;
1596 for (unsigned i = 0; i != 8; i += 4)
1597 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1598 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1599 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1600 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1601 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1602 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1603 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1604 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1605 return false;
1606 }
1607 return true;
1608}
1609
1610/// isVMerge - Common function, used to match vmrg* shuffles.
1611///
1612static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1613 unsigned LHSStart, unsigned RHSStart) {
1614 if (N->getValueType(0) != MVT::v16i8)
1615 return false;
1616 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&(((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
"Unsupported merge size!") ? static_cast<void> (0) : __assert_fail
("(UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && \"Unsupported merge size!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1617, __PRETTY_FUNCTION__))
1617 "Unsupported merge size!")(((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
"Unsupported merge size!") ? static_cast<void> (0) : __assert_fail
("(UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && \"Unsupported merge size!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1617, __PRETTY_FUNCTION__))
;
1618
1619 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1620 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1621 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1622 LHSStart+j+i*UnitSize) ||
1623 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1624 RHSStart+j+i*UnitSize))
1625 return false;
1626 }
1627 return true;
1628}
1629
1630/// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1631/// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1632/// The ShuffleKind distinguishes between big-endian merges with two
1633/// different inputs (0), either-endian merges with two identical inputs (1),
1634/// and little-endian merges with two different inputs (2). For the latter,
1635/// the input operands are swapped (see PPCInstrAltivec.td).
1636bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1637 unsigned ShuffleKind, SelectionDAG &DAG) {
1638 if (DAG.getDataLayout().isLittleEndian()) {
1639 if (ShuffleKind == 1) // unary
1640 return isVMerge(N, UnitSize, 0, 0);
1641 else if (ShuffleKind == 2) // swapped
1642 return isVMerge(N, UnitSize, 0, 16);
1643 else
1644 return false;
1645 } else {
1646 if (ShuffleKind == 1) // unary
1647 return isVMerge(N, UnitSize, 8, 8);
1648 else if (ShuffleKind == 0) // normal
1649 return isVMerge(N, UnitSize, 8, 24);
1650 else
1651 return false;
1652 }
1653}
1654
1655/// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1656/// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1657/// The ShuffleKind distinguishes between big-endian merges with two
1658/// different inputs (0), either-endian merges with two identical inputs (1),
1659/// and little-endian merges with two different inputs (2). For the latter,
1660/// the input operands are swapped (see PPCInstrAltivec.td).
1661bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1662 unsigned ShuffleKind, SelectionDAG &DAG) {
1663 if (DAG.getDataLayout().isLittleEndian()) {
1664 if (ShuffleKind == 1) // unary
1665 return isVMerge(N, UnitSize, 8, 8);
1666 else if (ShuffleKind == 2) // swapped
1667 return isVMerge(N, UnitSize, 8, 24);
1668 else
1669 return false;
1670 } else {
1671 if (ShuffleKind == 1) // unary
1672 return isVMerge(N, UnitSize, 0, 0);
1673 else if (ShuffleKind == 0) // normal
1674 return isVMerge(N, UnitSize, 0, 16);
1675 else
1676 return false;
1677 }
1678}
1679
1680/**
1681 * Common function used to match vmrgew and vmrgow shuffles
1682 *
1683 * The indexOffset determines whether to look for even or odd words in
1684 * the shuffle mask. This is based on the of the endianness of the target
1685 * machine.
1686 * - Little Endian:
1687 * - Use offset of 0 to check for odd elements
1688 * - Use offset of 4 to check for even elements
1689 * - Big Endian:
1690 * - Use offset of 0 to check for even elements
1691 * - Use offset of 4 to check for odd elements
1692 * A detailed description of the vector element ordering for little endian and
1693 * big endian can be found at
1694 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1695 * Targeting your applications - what little endian and big endian IBM XL C/C++
1696 * compiler differences mean to you
1697 *
1698 * The mask to the shuffle vector instruction specifies the indices of the
1699 * elements from the two input vectors to place in the result. The elements are
1700 * numbered in array-access order, starting with the first vector. These vectors
1701 * are always of type v16i8, thus each vector will contain 16 elements of size
1702 * 8. More info on the shuffle vector can be found in the
1703 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1704 * Language Reference.
1705 *
1706 * The RHSStartValue indicates whether the same input vectors are used (unary)
1707 * or two different input vectors are used, based on the following:
1708 * - If the instruction uses the same vector for both inputs, the range of the
1709 * indices will be 0 to 15. In this case, the RHSStart value passed should
1710 * be 0.
1711 * - If the instruction has two different vectors then the range of the
1712 * indices will be 0 to 31. In this case, the RHSStart value passed should
1713 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1714 * to 31 specify elements in the second vector).
1715 *
1716 * \param[in] N The shuffle vector SD Node to analyze
1717 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1718 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1719 * vector to the shuffle_vector instruction
1720 * \return true iff this shuffle vector represents an even or odd word merge
1721 */
1722static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1723 unsigned RHSStartValue) {
1724 if (N->getValueType(0) != MVT::v16i8)
1725 return false;
1726
1727 for (unsigned i = 0; i < 2; ++i)
1728 for (unsigned j = 0; j < 4; ++j)
1729 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1730 i*RHSStartValue+j+IndexOffset) ||
1731 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1732 i*RHSStartValue+j+IndexOffset+8))
1733 return false;
1734 return true;
1735}
1736
1737/**
1738 * Determine if the specified shuffle mask is suitable for the vmrgew or
1739 * vmrgow instructions.
1740 *
1741 * \param[in] N The shuffle vector SD Node to analyze
1742 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1743 * \param[in] ShuffleKind Identify the type of merge:
1744 * - 0 = big-endian merge with two different inputs;
1745 * - 1 = either-endian merge with two identical inputs;
1746 * - 2 = little-endian merge with two different inputs (inputs are swapped for
1747 * little-endian merges).
1748 * \param[in] DAG The current SelectionDAG
1749 * \return true iff this shuffle mask
1750 */
1751bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1752 unsigned ShuffleKind, SelectionDAG &DAG) {
1753 if (DAG.getDataLayout().isLittleEndian()) {
1754 unsigned indexOffset = CheckEven ? 4 : 0;
1755 if (ShuffleKind == 1) // Unary
1756 return isVMerge(N, indexOffset, 0);
1757 else if (ShuffleKind == 2) // swapped
1758 return isVMerge(N, indexOffset, 16);
1759 else
1760 return false;
1761 }
1762 else {
1763 unsigned indexOffset = CheckEven ? 0 : 4;
1764 if (ShuffleKind == 1) // Unary
1765 return isVMerge(N, indexOffset, 0);
1766 else if (ShuffleKind == 0) // Normal
1767 return isVMerge(N, indexOffset, 16);
1768 else
1769 return false;
1770 }
1771 return false;
1772}
1773
1774/// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1775/// amount, otherwise return -1.
1776/// The ShuffleKind distinguishes between big-endian operations with two
1777/// different inputs (0), either-endian operations with two identical inputs
1778/// (1), and little-endian operations with two different inputs (2). For the
1779/// latter, the input operands are swapped (see PPCInstrAltivec.td).
1780int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1781 SelectionDAG &DAG) {
1782 if (N->getValueType(0) != MVT::v16i8)
1783 return -1;
1784
1785 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1786
1787 // Find the first non-undef value in the shuffle mask.
1788 unsigned i;
1789 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1790 /*search*/;
1791
1792 if (i == 16) return -1; // all undef.
1793
1794 // Otherwise, check to see if the rest of the elements are consecutively
1795 // numbered from this value.
1796 unsigned ShiftAmt = SVOp->getMaskElt(i);
1797 if (ShiftAmt < i) return -1;
1798
1799 ShiftAmt -= i;
1800 bool isLE = DAG.getDataLayout().isLittleEndian();
1801
1802 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1803 // Check the rest of the elements to see if they are consecutive.
1804 for (++i; i != 16; ++i)
1805 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1806 return -1;
1807 } else if (ShuffleKind == 1) {
1808 // Check the rest of the elements to see if they are consecutive.
1809 for (++i; i != 16; ++i)
1810 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1811 return -1;
1812 } else
1813 return -1;
1814
1815 if (isLE)
1816 ShiftAmt = 16 - ShiftAmt;
1817
1818 return ShiftAmt;
1819}
1820
1821/// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1822/// specifies a splat of a single element that is suitable for input to
1823/// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1824bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1825 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&((N->getValueType(0) == MVT::v16i8 && isPowerOf2_32
(EltSize) && EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && EltSize <= 8 && \"Can only handle 1,2,4,8 byte element sizes\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1826, __PRETTY_FUNCTION__))
1826 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes")((N->getValueType(0) == MVT::v16i8 && isPowerOf2_32
(EltSize) && EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && EltSize <= 8 && \"Can only handle 1,2,4,8 byte element sizes\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1826, __PRETTY_FUNCTION__))
;
1827
1828 // The consecutive indices need to specify an element, not part of two
1829 // different elements. So abandon ship early if this isn't the case.
1830 if (N->getMaskElt(0) % EltSize != 0)
1831 return false;
1832
1833 // This is a splat operation if each element of the permute is the same, and
1834 // if the value doesn't reference the second vector.
1835 unsigned ElementBase = N->getMaskElt(0);
1836
1837 // FIXME: Handle UNDEF elements too!
1838 if (ElementBase >= 16)
1839 return false;
1840
1841 // Check that the indices are consecutive, in the case of a multi-byte element
1842 // splatted with a v16i8 mask.
1843 for (unsigned i = 1; i != EltSize; ++i)
1844 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1845 return false;
1846
1847 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1848 if (N->getMaskElt(i) < 0) continue;
1849 for (unsigned j = 0; j != EltSize; ++j)
1850 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1851 return false;
1852 }
1853 return true;
1854}
1855
1856/// Check that the mask is shuffling N byte elements. Within each N byte
1857/// element of the mask, the indices could be either in increasing or
1858/// decreasing order as long as they are consecutive.
1859/// \param[in] N the shuffle vector SD Node to analyze
1860/// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1861/// Word/DoubleWord/QuadWord).
1862/// \param[in] StepLen the delta indices number among the N byte element, if
1863/// the mask is in increasing/decreasing order then it is 1/-1.
1864/// \return true iff the mask is shuffling N byte elements.
1865static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1866 int StepLen) {
1867 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&(((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
"Unexpected element width.") ? static_cast<void> (0) :
__assert_fail ("(Width == 2 || Width == 4 || Width == 8 || Width == 16) && \"Unexpected element width.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1868, __PRETTY_FUNCTION__))
1868 "Unexpected element width.")(((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
"Unexpected element width.") ? static_cast<void> (0) :
__assert_fail ("(Width == 2 || Width == 4 || Width == 8 || Width == 16) && \"Unexpected element width.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1868, __PRETTY_FUNCTION__))
;
1869 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.")(((StepLen == 1 || StepLen == -1) && "Unexpected element width."
) ? static_cast<void> (0) : __assert_fail ("(StepLen == 1 || StepLen == -1) && \"Unexpected element width.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1869, __PRETTY_FUNCTION__))
;
1870
1871 unsigned NumOfElem = 16 / Width;
1872 unsigned MaskVal[16]; // Width is never greater than 16
1873 for (unsigned i = 0; i < NumOfElem; ++i) {
1874 MaskVal[0] = N->getMaskElt(i * Width);
1875 if ((StepLen == 1) && (MaskVal[0] % Width)) {
1876 return false;
1877 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1878 return false;
1879 }
1880
1881 for (unsigned int j = 1; j < Width; ++j) {
1882 MaskVal[j] = N->getMaskElt(i * Width + j);
1883 if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1884 return false;
1885 }
1886 }
1887 }
1888
1889 return true;
1890}
1891
1892bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1893 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1894 if (!isNByteElemShuffleMask(N, 4, 1))
1895 return false;
1896
1897 // Now we look at mask elements 0,4,8,12
1898 unsigned M0 = N->getMaskElt(0) / 4;
1899 unsigned M1 = N->getMaskElt(4) / 4;
1900 unsigned M2 = N->getMaskElt(8) / 4;
1901 unsigned M3 = N->getMaskElt(12) / 4;
1902 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1903 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1904
1905 // Below, let H and L be arbitrary elements of the shuffle mask
1906 // where H is in the range [4,7] and L is in the range [0,3].
1907 // H, 1, 2, 3 or L, 5, 6, 7
1908 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1909 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1910 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1911 InsertAtByte = IsLE ? 12 : 0;
1912 Swap = M0 < 4;
1913 return true;
1914 }
1915 // 0, H, 2, 3 or 4, L, 6, 7
1916 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1917 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1918 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1919 InsertAtByte = IsLE ? 8 : 4;
1920 Swap = M1 < 4;
1921 return true;
1922 }
1923 // 0, 1, H, 3 or 4, 5, L, 7
1924 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1925 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1926 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1927 InsertAtByte = IsLE ? 4 : 8;
1928 Swap = M2 < 4;
1929 return true;
1930 }
1931 // 0, 1, 2, H or 4, 5, 6, L
1932 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1933 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1934 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1935 InsertAtByte = IsLE ? 0 : 12;
1936 Swap = M3 < 4;
1937 return true;
1938 }
1939
1940 // If both vector operands for the shuffle are the same vector, the mask will
1941 // contain only elements from the first one and the second one will be undef.
1942 if (N->getOperand(1).isUndef()) {
1943 ShiftElts = 0;
1944 Swap = true;
1945 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1946 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1947 InsertAtByte = IsLE ? 12 : 0;
1948 return true;
1949 }
1950 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1951 InsertAtByte = IsLE ? 8 : 4;
1952 return true;
1953 }
1954 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1955 InsertAtByte = IsLE ? 4 : 8;
1956 return true;
1957 }
1958 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1959 InsertAtByte = IsLE ? 0 : 12;
1960 return true;
1961 }
1962 }
1963
1964 return false;
1965}
1966
1967bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1968 bool &Swap, bool IsLE) {
1969 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8")((N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::v16i8 && \"Shuffle vector expects v16i8\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1969, __PRETTY_FUNCTION__))
;
1970 // Ensure each byte index of the word is consecutive.
1971 if (!isNByteElemShuffleMask(N, 4, 1))
1972 return false;
1973
1974 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1975 unsigned M0 = N->getMaskElt(0) / 4;
1976 unsigned M1 = N->getMaskElt(4) / 4;
1977 unsigned M2 = N->getMaskElt(8) / 4;
1978 unsigned M3 = N->getMaskElt(12) / 4;
1979
1980 // If both vector operands for the shuffle are the same vector, the mask will
1981 // contain only elements from the first one and the second one will be undef.
1982 if (N->getOperand(1).isUndef()) {
1983 assert(M0 < 4 && "Indexing into an undef vector?")((M0 < 4 && "Indexing into an undef vector?") ? static_cast
<void> (0) : __assert_fail ("M0 < 4 && \"Indexing into an undef vector?\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1983, __PRETTY_FUNCTION__))
;
1984 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1985 return false;
1986
1987 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1988 Swap = false;
1989 return true;
1990 }
1991
1992 // Ensure each word index of the ShuffleVector Mask is consecutive.
1993 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1994 return false;
1995
1996 if (IsLE) {
1997 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1998 // Input vectors don't need to be swapped if the leading element
1999 // of the result is one of the 3 left elements of the second vector
2000 // (or if there is no shift to be done at all).
2001 Swap = false;
2002 ShiftElts = (8 - M0) % 8;
2003 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2004 // Input vectors need to be swapped if the leading element
2005 // of the result is one of the 3 left elements of the first vector
2006 // (or if we're shifting by 4 - thereby simply swapping the vectors).
2007 Swap = true;
2008 ShiftElts = (4 - M0) % 4;
2009 }
2010
2011 return true;
2012 } else { // BE
2013 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2014 // Input vectors don't need to be swapped if the leading element
2015 // of the result is one of the 4 elements of the first vector.
2016 Swap = false;
2017 ShiftElts = M0;
2018 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2019 // Input vectors need to be swapped if the leading element
2020 // of the result is one of the 4 elements of the right vector.
2021 Swap = true;
2022 ShiftElts = M0 - 4;
2023 }
2024
2025 return true;
2026 }
2027}
2028
2029bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2030 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8")((N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::v16i8 && \"Shuffle vector expects v16i8\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2030, __PRETTY_FUNCTION__))
;
2031
2032 if (!isNByteElemShuffleMask(N, Width, -1))
2033 return false;
2034
2035 for (int i = 0; i < 16; i += Width)
2036 if (N->getMaskElt(i) != i + Width - 1)
2037 return false;
2038
2039 return true;
2040}
2041
2042bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2043 return isXXBRShuffleMaskHelper(N, 2);
2044}
2045
2046bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2047 return isXXBRShuffleMaskHelper(N, 4);
2048}
2049
2050bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2051 return isXXBRShuffleMaskHelper(N, 8);
2052}
2053
2054bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2055 return isXXBRShuffleMaskHelper(N, 16);
2056}
2057
2058/// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2059/// if the inputs to the instruction should be swapped and set \p DM to the
2060/// value for the immediate.
2061/// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2062/// AND element 0 of the result comes from the first input (LE) or second input
2063/// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2064/// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2065/// mask.
2066bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2067 bool &Swap, bool IsLE) {
2068 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8")((N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::v16i8 && \"Shuffle vector expects v16i8\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2068, __PRETTY_FUNCTION__))
;
2069
2070 // Ensure each byte index of the double word is consecutive.
2071 if (!isNByteElemShuffleMask(N, 8, 1))
2072 return false;
2073
2074 unsigned M0 = N->getMaskElt(0) / 8;
2075 unsigned M1 = N->getMaskElt(8) / 8;
2076 assert(((M0 | M1) < 4) && "A mask element out of bounds?")((((M0 | M1) < 4) && "A mask element out of bounds?"
) ? static_cast<void> (0) : __assert_fail ("((M0 | M1) < 4) && \"A mask element out of bounds?\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2076, __PRETTY_FUNCTION__))
;
2077
2078 // If both vector operands for the shuffle are the same vector, the mask will
2079 // contain only elements from the first one and the second one will be undef.
2080 if (N->getOperand(1).isUndef()) {
2081 if ((M0 | M1) < 2) {
2082 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2083 Swap = false;
2084 return true;
2085 } else
2086 return false;
2087 }
2088
2089 if (IsLE) {
2090 if (M0 > 1 && M1 < 2) {
2091 Swap = false;
2092 } else if (M0 < 2 && M1 > 1) {
2093 M0 = (M0 + 2) % 4;
2094 M1 = (M1 + 2) % 4;
2095 Swap = true;
2096 } else
2097 return false;
2098
2099 // Note: if control flow comes here that means Swap is already set above
2100 DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2101 return true;
2102 } else { // BE
2103 if (M0 < 2 && M1 > 1) {
2104 Swap = false;
2105 } else if (M0 > 1 && M1 < 2) {
2106 M0 = (M0 + 2) % 4;
2107 M1 = (M1 + 2) % 4;
2108 Swap = true;
2109 } else
2110 return false;
2111
2112 // Note: if control flow comes here that means Swap is already set above
2113 DM = (M0 << 1) + (M1 & 1);
2114 return true;
2115 }
2116}
2117
2118
2119/// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2120/// appropriate for PPC mnemonics (which have a big endian bias - namely
2121/// elements are counted from the left of the vector register).
2122unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2123 SelectionDAG &DAG) {
2124 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2125 assert(isSplatShuffleMask(SVOp, EltSize))((isSplatShuffleMask(SVOp, EltSize)) ? static_cast<void>
(0) : __assert_fail ("isSplatShuffleMask(SVOp, EltSize)", "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2125, __PRETTY_FUNCTION__))
;
2126 if (DAG.getDataLayout().isLittleEndian())
2127 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2128 else
2129 return SVOp->getMaskElt(0) / EltSize;
2130}
2131
2132/// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2133/// by using a vspltis[bhw] instruction of the specified element size, return
2134/// the constant being splatted. The ByteSize field indicates the number of
2135/// bytes of each element [124] -> [bhw].
2136SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2137 SDValue OpVal(nullptr, 0);
2138
2139 // If ByteSize of the splat is bigger than the element size of the
2140 // build_vector, then we have a case where we are checking for a splat where
2141 // multiple elements of the buildvector are folded together into a single
2142 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2143 unsigned EltSize = 16/N->getNumOperands();
2144 if (EltSize < ByteSize) {
2145 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2146 SDValue UniquedVals[4];
2147 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?")((Multiple > 1 && Multiple <= 4 && "How can this happen?"
) ? static_cast<void> (0) : __assert_fail ("Multiple > 1 && Multiple <= 4 && \"How can this happen?\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2147, __PRETTY_FUNCTION__))
;
2148
2149 // See if all of the elements in the buildvector agree across.
2150 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2151 if (N->getOperand(i).isUndef()) continue;
2152 // If the element isn't a constant, bail fully out.
2153 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2154
2155 if (!UniquedVals[i&(Multiple-1)].getNode())
2156 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2157 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2158 return SDValue(); // no match.
2159 }
2160
2161 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2162 // either constant or undef values that are identical for each chunk. See
2163 // if these chunks can form into a larger vspltis*.
2164
2165 // Check to see if all of the leading entries are either 0 or -1. If
2166 // neither, then this won't fit into the immediate field.
2167 bool LeadingZero = true;
2168 bool LeadingOnes = true;
2169 for (unsigned i = 0; i != Multiple-1; ++i) {
2170 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2171
2172 LeadingZero &= isNullConstant(UniquedVals[i]);
2173 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2174 }
2175 // Finally, check the least significant entry.
2176 if (LeadingZero) {
2177 if (!UniquedVals[Multiple-1].getNode())
2178 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2179 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2180 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2181 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2182 }
2183 if (LeadingOnes) {
2184 if (!UniquedVals[Multiple-1].getNode())
2185 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2186 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2187 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2188 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2189 }
2190
2191 return SDValue();
2192 }
2193
2194 // Check to see if this buildvec has a single non-undef value in its elements.
2195 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2196 if (N->getOperand(i).isUndef()) continue;
2197 if (!OpVal.getNode())
2198 OpVal = N->getOperand(i);
2199 else if (OpVal != N->getOperand(i))
2200 return SDValue();
2201 }
2202
2203 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2204
2205 unsigned ValSizeInBytes = EltSize;
2206 uint64_t Value = 0;
2207 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2208 Value = CN->getZExtValue();
2209 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2210 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!")((CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"
) ? static_cast<void> (0) : __assert_fail ("CN->getValueType(0) == MVT::f32 && \"Only one legal FP vector type!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2210, __PRETTY_FUNCTION__))
;
2211 Value = FloatToBits(CN->getValueAPF().convertToFloat());
2212 }
2213
2214 // If the splat value is larger than the element value, then we can never do
2215 // this splat. The only case that we could fit the replicated bits into our
2216 // immediate field for would be zero, and we prefer to use vxor for it.
2217 if (ValSizeInBytes < ByteSize) return SDValue();
2218
2219 // If the element value is larger than the splat value, check if it consists
2220 // of a repeated bit pattern of size ByteSize.
2221 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2222 return SDValue();
2223
2224 // Properly sign extend the value.
2225 int MaskVal = SignExtend32(Value, ByteSize * 8);
2226
2227 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2228 if (MaskVal == 0) return SDValue();
2229
2230 // Finally, if this value fits in a 5 bit sext field, return it
2231 if (SignExtend32<5>(MaskVal) == MaskVal)
2232 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2233 return SDValue();
2234}
2235
2236/// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2237/// amount, otherwise return -1.
2238int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2239 EVT VT = N->getValueType(0);
2240 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2241 return -1;
2242
2243 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2244
2245 // Find the first non-undef value in the shuffle mask.
2246 unsigned i;
2247 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2248 /*search*/;
2249
2250 if (i == 4) return -1; // all undef.
2251
2252 // Otherwise, check to see if the rest of the elements are consecutively
2253 // numbered from this value.
2254 unsigned ShiftAmt = SVOp->getMaskElt(i);
2255 if (ShiftAmt < i) return -1;
2256 ShiftAmt -= i;
2257
2258 // Check the rest of the elements to see if they are consecutive.
2259 for (++i; i != 4; ++i)
2260 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2261 return -1;
2262
2263 return ShiftAmt;
2264}
2265
2266//===----------------------------------------------------------------------===//
2267// Addressing Mode Selection
2268//===----------------------------------------------------------------------===//
2269
2270/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2271/// or 64-bit immediate, and if the value can be accurately represented as a
2272/// sign extension from a 16-bit value. If so, this returns true and the
2273/// immediate.
2274bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2275 if (!isa<ConstantSDNode>(N))
2276 return false;
2277
2278 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2279 if (N->getValueType(0) == MVT::i32)
2280 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2281 else
2282 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2283}
2284bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2285 return isIntS16Immediate(Op.getNode(), Imm);
2286}
2287
2288
2289/// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2290/// be represented as an indexed [r+r] operation.
2291bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2292 SDValue &Index,
2293 SelectionDAG &DAG) const {
2294 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2295 UI != E; ++UI) {
2296 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2297 if (Memop->getMemoryVT() == MVT::f64) {
2298 Base = N.getOperand(0);
2299 Index = N.getOperand(1);
2300 return true;
2301 }
2302 }
2303 }
2304 return false;
2305}
2306
2307/// SelectAddressRegReg - Given the specified addressed, check to see if it
2308/// can be represented as an indexed [r+r] operation. Returns false if it
2309/// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2310/// non-zero and N can be represented by a base register plus a signed 16-bit
2311/// displacement, make a more precise judgement by checking (displacement % \p
2312/// EncodingAlignment).
2313bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2314 SDValue &Index, SelectionDAG &DAG,
2315 unsigned EncodingAlignment) const {
2316 int16_t imm = 0;
2317 if (N.getOpcode() == ISD::ADD) {
2318 // Is there any SPE load/store (f64), which can't handle 16bit offset?
2319 // SPE load/store can only handle 8-bit offsets.
2320 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2321 return true;
2322 if (isIntS16Immediate(N.getOperand(1), imm) &&
2323 (!EncodingAlignment || !(imm % EncodingAlignment)))
2324 return false; // r+i
2325 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2326 return false; // r+i
2327
2328 Base = N.getOperand(0);
2329 Index = N.getOperand(1);
2330 return true;
2331 } else if (N.getOpcode() == ISD::OR) {
2332 if (isIntS16Immediate(N.getOperand(1), imm) &&
2333 (!EncodingAlignment || !(imm % EncodingAlignment)))
2334 return false; // r+i can fold it if we can.
2335
2336 // If this is an or of disjoint bitfields, we can codegen this as an add
2337 // (for better address arithmetic) if the LHS and RHS of the OR are provably
2338 // disjoint.
2339 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2340
2341 if (LHSKnown.Zero.getBoolValue()) {
2342 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2343 // If all of the bits are known zero on the LHS or RHS, the add won't
2344 // carry.
2345 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2346 Base = N.getOperand(0);
2347 Index = N.getOperand(1);
2348 return true;
2349 }
2350 }
2351 }
2352
2353 return false;
2354}
2355
2356// If we happen to be doing an i64 load or store into a stack slot that has
2357// less than a 4-byte alignment, then the frame-index elimination may need to
2358// use an indexed load or store instruction (because the offset may not be a
2359// multiple of 4). The extra register needed to hold the offset comes from the
2360// register scavenger, and it is possible that the scavenger will need to use
2361// an emergency spill slot. As a result, we need to make sure that a spill slot
2362// is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2363// stack slot.
2364static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2365 // FIXME: This does not handle the LWA case.
2366 if (VT != MVT::i64)
2367 return;
2368
2369 // NOTE: We'll exclude negative FIs here, which come from argument
2370 // lowering, because there are no known test cases triggering this problem
2371 // using packed structures (or similar). We can remove this exclusion if
2372 // we find such a test case. The reason why this is so test-case driven is
2373 // because this entire 'fixup' is only to prevent crashes (from the
2374 // register scavenger) on not-really-valid inputs. For example, if we have:
2375 // %a = alloca i1
2376 // %b = bitcast i1* %a to i64*
2377 // store i64* a, i64 b
2378 // then the store should really be marked as 'align 1', but is not. If it
2379 // were marked as 'align 1' then the indexed form would have been
2380 // instruction-selected initially, and the problem this 'fixup' is preventing
2381 // won't happen regardless.
2382 if (FrameIdx < 0)
2383 return;
2384
2385 MachineFunction &MF = DAG.getMachineFunction();
2386 MachineFrameInfo &MFI = MF.getFrameInfo();
2387
2388 unsigned Align = MFI.getObjectAlignment(FrameIdx);
2389 if (Align >= 4)
2390 return;
2391
2392 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2393 FuncInfo->setHasNonRISpills();
2394}
2395
2396/// Returns true if the address N can be represented by a base register plus
2397/// a signed 16-bit displacement [r+imm], and if it is not better
2398/// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2399/// displacements that are multiples of that value.
2400bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2401 SDValue &Base,
2402 SelectionDAG &DAG,
2403 unsigned EncodingAlignment) const {
2404 // FIXME dl should come from parent load or store, not from address
2405 SDLoc dl(N);
2406 // If this can be more profitably realized as r+r, fail.
2407 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2408 return false;
2409
2410 if (N.getOpcode() == ISD::ADD) {
2411 int16_t imm = 0;
2412 if (isIntS16Immediate(N.getOperand(1), imm) &&
2413 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2414 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2415 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2416 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2417 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2418 } else {
2419 Base = N.getOperand(0);
2420 }
2421 return true; // [r+i]
2422 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2423 // Match LOAD (ADD (X, Lo(G))).
2424 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()((!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->
getZExtValue() && "Cannot handle constant offsets yet!"
) ? static_cast<void> (0) : __assert_fail ("!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() && \"Cannot handle constant offsets yet!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2425, __PRETTY_FUNCTION__))
2425 && "Cannot handle constant offsets yet!")((!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->
getZExtValue() && "Cannot handle constant offsets yet!"
) ? static_cast<void> (0) : __assert_fail ("!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() && \"Cannot handle constant offsets yet!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2425, __PRETTY_FUNCTION__))
;
2426 Disp = N.getOperand(1).getOperand(0); // The global address.
2427 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||((Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode
() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::
TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable
) ? static_cast<void> (0) : __assert_fail ("Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable"
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2430, __PRETTY_FUNCTION__))
2428 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||((Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode
() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::
TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable
) ? static_cast<void> (0) : __assert_fail ("Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable"
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2430, __PRETTY_FUNCTION__))
2429 Disp.getOpcode() == ISD::TargetConstantPool ||((Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode
() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::
TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable
) ? static_cast<void> (0) : __assert_fail ("Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable"
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2430, __PRETTY_FUNCTION__))
2430 Disp.getOpcode() == ISD::TargetJumpTable)((Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode
() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::
TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable
) ? static_cast<void> (0) : __assert_fail ("Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable"
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2430, __PRETTY_FUNCTION__))
;
2431 Base = N.getOperand(0);
2432 return true; // [&g+r]
2433 }
2434 } else if (N.getOpcode() == ISD::OR) {
2435 int16_t imm = 0;
2436 if (isIntS16Immediate(N.getOperand(1), imm) &&
2437 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2438 // If this is an or of disjoint bitfields, we can codegen this as an add
2439 // (for better address arithmetic) if the LHS and RHS of the OR are
2440 // provably disjoint.
2441 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2442
2443 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2444 // If all of the bits are known zero on the LHS or RHS, the add won't
2445 // carry.
2446 if (FrameIndexSDNode *FI =
2447 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2448 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2449 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2450 } else {
2451 Base = N.getOperand(0);
2452 }
2453 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2454 return true;
2455 }
2456 }
2457 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2458 // Loading from a constant address.
2459
2460 // If this address fits entirely in a 16-bit sext immediate field, codegen
2461 // this as "d, 0"
2462 int16_t Imm;
2463 if (isIntS16Immediate(CN, Imm) &&
2464 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2465 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2466 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2467 CN->getValueType(0));
2468 return true;
2469 }
2470
2471 // Handle 32-bit sext immediates with LIS + addr mode.
2472 if ((CN->getValueType(0) == MVT::i32 ||
2473 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2474 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2475 int Addr = (int)CN->getZExtValue();
2476
2477 // Otherwise, break this down into an LIS + disp.
2478 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2479
2480 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2481 MVT::i32);
2482 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2483 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2484 return true;
2485 }
2486 }
2487
2488 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2489 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2490 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2491 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2492 } else
2493 Base = N;
2494 return true; // [r+0]
2495}
2496
2497/// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2498/// represented as an indexed [r+r] operation.
2499bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2500 SDValue &Index,
2501 SelectionDAG &DAG) const {
2502 // Check to see if we can easily represent this as an [r+r] address. This
2503 // will fail if it thinks that the address is more profitably represented as
2504 // reg+imm, e.g. where imm = 0.
2505 if (SelectAddressRegReg(N, Base, Index, DAG))
2506 return true;
2507
2508 // If the address is the result of an add, we will utilize the fact that the
2509 // address calculation includes an implicit add. However, we can reduce
2510 // register pressure if we do not materialize a constant just for use as the
2511 // index register. We only get rid of the add if it is not an add of a
2512 // value and a 16-bit signed constant and both have a single use.
2513 int16_t imm = 0;
2514 if (N.getOpcode() == ISD::ADD &&
2515 (!isIntS16Immediate(N.getOperand(1), imm) ||
2516 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2517 Base = N.getOperand(0);
2518 Index = N.getOperand(1);
2519 return true;
2520 }
2521
2522 // Otherwise, do it the hard way, using R0 as the base register.
2523 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2524 N.getValueType());
2525 Index = N;
2526 return true;
2527}
2528
2529/// Returns true if we should use a direct load into vector instruction
2530/// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2531static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2532
2533 // If there are any other uses other than scalar to vector, then we should
2534 // keep it as a scalar load -> direct move pattern to prevent multiple
2535 // loads.
2536 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2537 if (!LD)
2538 return false;
2539
2540 EVT MemVT = LD->getMemoryVT();
2541 if (!MemVT.isSimple())
2542 return false;
2543 switch(MemVT.getSimpleVT().SimpleTy) {
2544 case MVT::i64:
2545 break;
2546 case MVT::i32:
2547 if (!ST.hasP8Vector())
2548 return false;
2549 break;
2550 case MVT::i16:
2551 case MVT::i8:
2552 if (!ST.hasP9Vector())
2553 return false;
2554 break;
2555 default:
2556 return false;
2557 }
2558
2559 SDValue LoadedVal(N, 0);
2560 if (!LoadedVal.hasOneUse())
2561 return false;
2562
2563 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2564 UI != UE; ++UI)
2565 if (UI.getUse().get().getResNo() == 0 &&
2566 UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2567 return false;
2568
2569 return true;
2570}
2571
2572/// getPreIndexedAddressParts - returns true by value, base pointer and
2573/// offset pointer and addressing mode by reference if the node's address
2574/// can be legally represented as pre-indexed load / store address.
2575bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2576 SDValue &Offset,
2577 ISD::MemIndexedMode &AM,
2578 SelectionDAG &DAG) const {
2579 if (DisablePPCPreinc) return false;
2580
2581 bool isLoad = true;
2582 SDValue Ptr;
2583 EVT VT;
2584 unsigned Alignment;
2585 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2586 Ptr = LD->getBasePtr();
2587 VT = LD->getMemoryVT();
2588 Alignment = LD->getAlignment();
2589 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2590 Ptr = ST->getBasePtr();
2591 VT = ST->getMemoryVT();
2592 Alignment = ST->getAlignment();
2593 isLoad = false;
2594 } else
2595 return false;
2596
2597 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2598 // instructions because we can fold these into a more efficient instruction
2599 // instead, (such as LXSD).
2600 if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2601 return false;
2602 }
2603
2604 // PowerPC doesn't have preinc load/store instructions for vectors (except
2605 // for QPX, which does have preinc r+r forms).
2606 if (VT.isVector()) {
2607 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2608 return false;
2609 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2610 AM = ISD::PRE_INC;
2611 return true;
2612 }
2613 }
2614
2615 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2616 // Common code will reject creating a pre-inc form if the base pointer
2617 // is a frame index, or if N is a store and the base pointer is either
2618 // the same as or a predecessor of the value being stored. Check for
2619 // those situations here, and try with swapped Base/Offset instead.
2620 bool Swap = false;
2621
2622 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2623 Swap = true;
2624 else if (!isLoad) {
2625 SDValue Val = cast<StoreSDNode>(N)->getValue();
2626 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2627 Swap = true;
2628 }
2629
2630 if (Swap)
2631 std::swap(Base, Offset);
2632
2633 AM = ISD::PRE_INC;
2634 return true;
2635 }
2636
2637 // LDU/STU can only handle immediates that are a multiple of 4.
2638 if (VT != MVT::i64) {
2639 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2640 return false;
2641 } else {
2642 // LDU/STU need an address with at least 4-byte alignment.
2643 if (Alignment < 4)
2644 return false;
2645
2646 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2647 return false;
2648 }
2649
2650 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2651 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2652 // sext i32 to i64 when addr mode is r+i.
2653 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2654 LD->getExtensionType() == ISD::SEXTLOAD &&
2655 isa<ConstantSDNode>(Offset))
2656 return false;
2657 }
2658
2659 AM = ISD::PRE_INC;
2660 return true;
2661}
2662
2663//===----------------------------------------------------------------------===//
2664// LowerOperation implementation
2665//===----------------------------------------------------------------------===//
2666
2667/// Return true if we should reference labels using a PICBase, set the HiOpFlags
2668/// and LoOpFlags to the target MO flags.
2669static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2670 unsigned &HiOpFlags, unsigned &LoOpFlags,
2671 const GlobalValue *GV = nullptr) {
2672 HiOpFlags = PPCII::MO_HA;
2673 LoOpFlags = PPCII::MO_LO;
2674
2675 // Don't use the pic base if not in PIC relocation model.
2676 if (IsPIC) {
2677 HiOpFlags |= PPCII::MO_PIC_FLAG;
2678 LoOpFlags |= PPCII::MO_PIC_FLAG;
2679 }
2680}
2681
2682static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2683 SelectionDAG &DAG) {
2684 SDLoc DL(HiPart);
2685 EVT PtrVT = HiPart.getValueType();
2686 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2687
2688 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2689 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2690
2691 // With PIC, the first instruction is actually "GR+hi(&G)".
2692 if (isPIC)
2693 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2694 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2695
2696 // Generate non-pic code that has direct accesses to the constant pool.
2697 // The address of the global is just (hi(&g)+lo(&g)).
2698 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2699}
2700
2701static void setUsesTOCBasePtr(MachineFunction &MF) {
2702 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2703 FuncInfo->setUsesTOCBasePtr();
2704}
2705
2706static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2707 setUsesTOCBasePtr(DAG.getMachineFunction());
2708}
2709
2710SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2711 SDValue GA) const {
2712 const bool Is64Bit = Subtarget.isPPC64();
2713 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2714 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2715 : Subtarget.isAIXABI()
2716 ? DAG.getRegister(PPC::R2, VT)
2717 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2718 SDValue Ops[] = { GA, Reg };
2719 return DAG.getMemIntrinsicNode(
2720 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2721 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2722 MachineMemOperand::MOLoad);
2723}
2724
2725SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2726 SelectionDAG &DAG) const {
2727 EVT PtrVT = Op.getValueType();
2728 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2729 const Constant *C = CP->getConstVal();
2730
2731 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2732 // The actual address of the GlobalValue is stored in the TOC.
2733 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2734 setUsesTOCBasePtr(DAG);
2735 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2736 return getTOCEntry(DAG, SDLoc(CP), GA);
2737 }
2738
2739 unsigned MOHiFlag, MOLoFlag;
2740 bool IsPIC = isPositionIndependent();
2741 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2742
2743 if (IsPIC && Subtarget.isSVR4ABI()) {
2744 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2745 PPCII::MO_PIC_FLAG);
2746 return getTOCEntry(DAG, SDLoc(CP), GA);
2747 }
2748
2749 SDValue CPIHi =
2750 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2751 SDValue CPILo =
2752 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2753 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2754}
2755
2756// For 64-bit PowerPC, prefer the more compact relative encodings.
2757// This trades 32 bits per jump table entry for one or two instructions
2758// on the jump site.
2759unsigned PPCTargetLowering::getJumpTableEncoding() const {
2760 if (isJumpTableRelative())
2761 return MachineJumpTableInfo::EK_LabelDifference32;
2762
2763 return TargetLowering::getJumpTableEncoding();
2764}
2765
2766bool PPCTargetLowering::isJumpTableRelative() const {
2767 if (UseAbsoluteJumpTables)
2768 return false;
2769 if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2770 return true;
2771 return TargetLowering::isJumpTableRelative();
2772}
2773
2774SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2775 SelectionDAG &DAG) const {
2776 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2777 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2778
2779 switch (getTargetMachine().getCodeModel()) {
2780 case CodeModel::Small:
2781 case CodeModel::Medium:
2782 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2783 default:
2784 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2785 getPointerTy(DAG.getDataLayout()));
2786 }
2787}
2788
2789const MCExpr *
2790PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2791 unsigned JTI,
2792 MCContext &Ctx) const {
2793 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2794 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2795
2796 switch (getTargetMachine().getCodeModel()) {
2797 case CodeModel::Small:
2798 case CodeModel::Medium:
2799 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2800 default:
2801 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2802 }
2803}
2804
2805SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2806 EVT PtrVT = Op.getValueType();
2807 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2808
2809 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2810 // The actual address of the GlobalValue is stored in the TOC.
2811 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2812 setUsesTOCBasePtr(DAG);
2813 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2814 return getTOCEntry(DAG, SDLoc(JT), GA);
2815 }
2816
2817 unsigned MOHiFlag, MOLoFlag;
2818 bool IsPIC = isPositionIndependent();
2819 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2820
2821 if (IsPIC && Subtarget.isSVR4ABI()) {
2822 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2823 PPCII::MO_PIC_FLAG);
2824 return getTOCEntry(DAG, SDLoc(GA), GA);
2825 }
2826
2827 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2828 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2829 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2830}
2831
2832SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2833 SelectionDAG &DAG) const {
2834 EVT PtrVT = Op.getValueType();
2835 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2836 const BlockAddress *BA = BASDN->getBlockAddress();
2837
2838 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2839 // The actual BlockAddress is stored in the TOC.
2840 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2841 setUsesTOCBasePtr(DAG);
2842 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2843 return getTOCEntry(DAG, SDLoc(BASDN), GA);
2844 }
2845
2846 // 32-bit position-independent ELF stores the BlockAddress in the .got.
2847 if (Subtarget.is32BitELFABI() && isPositionIndependent())
2848 return getTOCEntry(
2849 DAG, SDLoc(BASDN),
2850 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2851
2852 unsigned MOHiFlag, MOLoFlag;
2853 bool IsPIC = isPositionIndependent();
2854 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2855 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2856 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2857 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2858}
2859
2860SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2861 SelectionDAG &DAG) const {
2862 // FIXME: TLS addresses currently use medium model code sequences,
2863 // which is the most useful form. Eventually support for small and
2864 // large models could be added if users need it, at the cost of
2865 // additional complexity.
2866 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2867 if (DAG.getTarget().useEmulatedTLS())
2868 return LowerToTLSEmulatedModel(GA, DAG);
2869
2870 SDLoc dl(GA);
2871 const GlobalValue *GV = GA->getGlobal();
2872 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2873 bool is64bit = Subtarget.isPPC64();
2874 const Module *M = DAG.getMachineFunction().getFunction().getParent();
2875 PICLevel::Level picLevel = M->getPICLevel();
2876
2877 const TargetMachine &TM = getTargetMachine();
2878 TLSModel::Model Model = TM.getTLSModel(GV);
2879
2880 if (Model == TLSModel::LocalExec) {
2881 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2882 PPCII::MO_TPREL_HA);
2883 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2884 PPCII::MO_TPREL_LO);
2885 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2886 : DAG.getRegister(PPC::R2, MVT::i32);
2887
2888 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2889 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2890 }
2891
2892 if (Model == TLSModel::InitialExec) {
2893 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2894 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2895 PPCII::MO_TLS);
2896 SDValue GOTPtr;
2897 if (is64bit) {
2898 setUsesTOCBasePtr(DAG);
2899 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2900 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2901 PtrVT, GOTReg, TGA);
2902 } else {
2903 if (!TM.isPositionIndependent())
2904 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2905 else if (picLevel == PICLevel::SmallPIC)
2906 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2907 else
2908 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2909 }
2910 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2911 PtrVT, TGA, GOTPtr);
2912 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2913 }
2914
2915 if (Model == TLSModel::GeneralDynamic) {
2916 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2917 SDValue GOTPtr;
2918 if (is64bit) {
2919 setUsesTOCBasePtr(DAG);
2920 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2921 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2922 GOTReg, TGA);
2923 } else {
2924 if (picLevel == PICLevel::SmallPIC)
2925 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2926 else
2927 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2928 }
2929 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2930 GOTPtr, TGA, TGA);
2931 }
2932
2933 if (Model == TLSModel::LocalDynamic) {
2934 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2935 SDValue GOTPtr;
2936 if (is64bit) {
2937 setUsesTOCBasePtr(DAG);
2938 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2939 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2940 GOTReg, TGA);
2941 } else {
2942 if (picLevel == PICLevel::SmallPIC)
2943 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2944 else
2945 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2946 }
2947 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2948 PtrVT, GOTPtr, TGA, TGA);
2949 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2950 PtrVT, TLSAddr, TGA);
2951 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2952 }
2953
2954 llvm_unreachable("Unknown TLS model!")::llvm::llvm_unreachable_internal("Unknown TLS model!", "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2954)
;
2955}
2956
2957SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2958 SelectionDAG &DAG) const {
2959 EVT PtrVT = Op.getValueType();
2960 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2961 SDLoc DL(GSDN);
2962 const GlobalValue *GV = GSDN->getGlobal();
2963
2964 // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
2965 // The actual address of the GlobalValue is stored in the TOC.
2966 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2967 setUsesTOCBasePtr(DAG);
2968 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2969 return getTOCEntry(DAG, DL, GA);
2970 }
2971
2972 unsigned MOHiFlag, MOLoFlag;
2973 bool IsPIC = isPositionIndependent();
2974 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2975
2976 if (IsPIC && Subtarget.isSVR4ABI()) {
2977 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2978 GSDN->getOffset(),
2979 PPCII::MO_PIC_FLAG);
2980 return getTOCEntry(DAG, DL, GA);
2981 }
2982
2983 SDValue GAHi =
2984 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2985 SDValue GALo =
2986 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2987
2988 return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2989}
2990
2991SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2992 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2993 SDLoc dl(Op);
2994
2995 if (Op.getValueType() == MVT::v2i64) {
2996 // When the operands themselves are v2i64 values, we need to do something
2997 // special because VSX has no underlying comparison operations for these.
2998 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2999 // Equality can be handled by casting to the legal type for Altivec
3000 // comparisons, everything else needs to be expanded.
3001 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3002 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3003 DAG.getSetCC(dl, MVT::v4i32,
3004 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3005 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3006 CC));
3007 }
3008
3009 return SDValue();
3010 }
3011
3012 // We handle most of these in the usual way.
3013 return Op;
3014 }
3015
3016 // If we're comparing for equality to zero, expose the fact that this is
3017 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3018 // fold the new nodes.
3019 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3020 return V;
3021
3022 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3023 // Leave comparisons against 0 and -1 alone for now, since they're usually
3024 // optimized. FIXME: revisit this when we can custom lower all setcc
3025 // optimizations.
3026 if (C->isAllOnesValue() || C->isNullValue())
3027 return SDValue();
3028 }
3029
3030 // If we have an integer seteq/setne, turn it into a compare against zero
3031 // by xor'ing the rhs with the lhs, which is faster than setting a
3032 // condition register, reading it back out, and masking the correct bit. The
3033 // normal approach here uses sub to do this instead of xor. Using xor exposes
3034 // the result to other bit-twiddling opportunities.
3035 EVT LHSVT = Op.getOperand(0).getValueType();
3036 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3037 EVT VT = Op.getValueType();
3038 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3039 Op.getOperand(1));
3040 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3041 }
3042 return SDValue();
3043}
3044
3045SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3046 SDNode *Node = Op.getNode();
3047 EVT VT = Node->getValueType(0);
3048 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3049 SDValue InChain = Node->getOperand(0);
3050 SDValue VAListPtr = Node->getOperand(1);
3051 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3052 SDLoc dl(Node);
3053
3054 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only")((!Subtarget.isPPC64() && "LowerVAARG is PPC32 only")
? static_cast<void> (0) : __assert_fail ("!Subtarget.isPPC64() && \"LowerVAARG is PPC32 only\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3054, __PRETTY_FUNCTION__))
;
3055
3056 // gpr_index
3057 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3058 VAListPtr, MachinePointerInfo(SV), MVT::i8);
3059 InChain = GprIndex.getValue(1);
3060
3061 if (VT == MVT::i64) {
3062 // Check if GprIndex is even
3063 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3064 DAG.getConstant(1, dl, MVT::i32));
3065 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3066 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3067 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3068 DAG.getConstant(1, dl, MVT::i32));
3069 // Align GprIndex to be even if it isn't
3070 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3071 GprIndex);
3072 }
3073
3074 // fpr index is 1 byte after gpr
3075 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3076 DAG.getConstant(1, dl, MVT::i32));
3077
3078 // fpr
3079 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3080 FprPtr, MachinePointerInfo(SV), MVT::i8);
3081 InChain = FprIndex.getValue(1);
3082
3083 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3084 DAG.getConstant(8, dl, MVT::i32));
3085
3086 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3087 DAG.getConstant(4, dl, MVT::i32));
3088
3089 // areas
3090 SDValue OverflowArea =
3091 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3092 InChain = OverflowArea.getValue(1);
3093
3094 SDValue RegSaveArea =
3095 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3096 InChain = RegSaveArea.getValue(1);
3097
3098 // select overflow_area if index > 8
3099 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3100 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3101
3102 // adjustment constant gpr_index * 4/8
3103 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3104 VT.isInteger() ? GprIndex : FprIndex,
3105 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3106 MVT::i32));
3107
3108 // OurReg = RegSaveArea + RegConstant
3109 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3110 RegConstant);
3111
3112 // Floating types are 32 bytes into RegSaveArea
3113 if (VT.isFloatingPoint())
3114 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3115 DAG.getConstant(32, dl, MVT::i32));
3116
3117 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3118 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3119 VT.isInteger() ? GprIndex : FprIndex,
3120 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3121 MVT::i32));
3122
3123 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3124 VT.isInteger() ? VAListPtr : FprPtr,
3125 MachinePointerInfo(SV), MVT::i8);
3126
3127 // determine if we should load from reg_save_area or overflow_area
3128 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3129
3130 // increase overflow_area by 4/8 if gpr/fpr > 8
3131 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3132 DAG.getConstant(VT.isInteger() ? 4 : 8,
3133 dl, MVT::i32));
3134
3135 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3136 OverflowAreaPlusN);
3137
3138 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3139 MachinePointerInfo(), MVT::i32);
3140
3141 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3142}
3143
3144SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3145 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only")((!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget.isPPC64() && \"LowerVACOPY is PPC32 only\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3145, __PRETTY_FUNCTION__))
;
3146
3147 // We have to copy the entire va_list struct:
3148 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3149 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3150 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3151 false, true, false, MachinePointerInfo(),
3152 MachinePointerInfo());
3153}
3154
3155SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3156 SelectionDAG &DAG) const {
3157 if (Subtarget.isAIXABI())
3158 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3159
3160 return Op.getOperand(0);
3161}
3162
3163SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3164 SelectionDAG &DAG) const {
3165 if (Subtarget.isAIXABI())
3166 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3167
3168 SDValue Chain = Op.getOperand(0);
3169 SDValue Trmp = Op.getOperand(1); // trampoline
3170 SDValue FPtr = Op.getOperand(2); // nested function
3171 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3172 SDLoc dl(Op);
3173
3174 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3175 bool isPPC64 = (PtrVT == MVT::i64);
3176 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3177
3178 TargetLowering::ArgListTy Args;
3179 TargetLowering::ArgListEntry Entry;
3180
3181 Entry.Ty = IntPtrTy;
3182 Entry.Node = Trmp; Args.push_back(Entry);
3183
3184 // TrampSize == (isPPC64 ? 48 : 40);
3185 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3186 isPPC64 ? MVT::i64 : MVT::i32);
3187 Args.push_back(Entry);
3188
3189 Entry.Node = FPtr; Args.push_back(Entry);
3190 Entry.Node = Nest; Args.push_back(Entry);
3191
3192 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3193 TargetLowering::CallLoweringInfo CLI(DAG);
3194 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3195 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3196 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3197
3198 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3199 return CallResult.second;
3200}
3201
3202SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3203 MachineFunction &MF = DAG.getMachineFunction();
3204 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3205 EVT PtrVT = getPointerTy(MF.getDataLayout());
3206
3207 SDLoc dl(Op);
3208
3209 if (Subtarget.isPPC64()) {
3210 // vastart just stores the address of the VarArgsFrameIndex slot into the
3211 // memory location argument.
3212 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3213 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3214 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3215 MachinePointerInfo(SV));
3216 }
3217
3218 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3219 // We suppose the given va_list is already allocated.
3220 //
3221 // typedef struct {
3222 // char gpr; /* index into the array of 8 GPRs
3223 // * stored in the register save area
3224 // * gpr=0 corresponds to r3,
3225 // * gpr=1 to r4, etc.
3226 // */
3227 // char fpr; /* index into the array of 8 FPRs
3228 // * stored in the register save area
3229 // * fpr=0 corresponds to f1,
3230 // * fpr=1 to f2, etc.
3231 // */
3232 // char *overflow_arg_area;
3233 // /* location on stack that holds
3234 // * the next overflow argument
3235 // */
3236 // char *reg_save_area;
3237 // /* where r3:r10 and f1:f8 (if saved)
3238 // * are stored
3239 // */
3240 // } va_list[1];
3241
3242 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3243 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3244 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3245 PtrVT);
3246 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3247 PtrVT);
3248
3249 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3250 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3251
3252 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3253 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3254
3255 uint64_t FPROffset = 1;
3256 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3257
3258 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3259
3260 // Store first byte : number of int regs
3261 SDValue firstStore =
3262 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3263 MachinePointerInfo(SV), MVT::i8);
3264 uint64_t nextOffset = FPROffset;
3265 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3266 ConstFPROffset);
3267
3268 // Store second byte : number of float regs
3269 SDValue secondStore =
3270 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3271 MachinePointerInfo(SV, nextOffset), MVT::i8);
3272 nextOffset += StackOffset;
3273 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3274
3275 // Store second word : arguments given on stack
3276 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3277 MachinePointerInfo(SV, nextOffset));
3278 nextOffset += FrameOffset;
3279 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3280
3281 // Store third word : arguments given in registers
3282 return DAG.getStore(thirdStore, dl, FR, nextPtr,
3283 MachinePointerInfo(SV, nextOffset));
3284}
3285
3286/// FPR - The set of FP registers that should be allocated for arguments
3287/// on Darwin and AIX.
3288static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
3289 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
3290 PPC::F11, PPC::F12, PPC::F13};
3291
3292/// QFPR - The set of QPX registers that should be allocated for arguments.
3293static const MCPhysReg QFPR[] = {
3294 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
3295 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3296
3297/// CalculateStackSlotSize - Calculates the size reserved for this argument on
3298/// the stack.
3299static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3300 unsigned PtrByteSize) {
3301 unsigned ArgSize = ArgVT.getStoreSize();
3302 if (Flags.isByVal())
3303 ArgSize = Flags.getByValSize();
3304
3305 // Round up to multiples of the pointer size, except for array members,
3306 // which are always packed.
3307 if (!Flags.isInConsecutiveRegs())
3308 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3309
3310 return ArgSize;
3311}
3312
3313/// CalculateStackSlotAlignment - Calculates the alignment of this argument
3314/// on the stack.
3315static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3316 ISD::ArgFlagsTy Flags,
3317 unsigned PtrByteSize) {
3318 Align Alignment(PtrByteSize);
3319
3320 // Altivec parameters are padded to a 16 byte boundary.
3321 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3322 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3323 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3324 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3325 Alignment = Align(16);
3326 // QPX vector types stored in double-precision are padded to a 32 byte
3327 // boundary.
3328 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3329 Alignment = Align(32);
3330
3331 // ByVal parameters are aligned as requested.
3332 if (Flags.isByVal()) {
3333 auto BVAlign = Flags.getNonZeroByValAlign();
3334 if (BVAlign > PtrByteSize) {
3335 if (BVAlign.value() % PtrByteSize != 0)
3336 llvm_unreachable(::llvm::llvm_unreachable_internal("ByVal alignment is not a multiple of the pointer size"
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3337)
3337 "ByVal alignment is not a multiple of the pointer size")::llvm::llvm_unreachable_internal("ByVal alignment is not a multiple of the pointer size"
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3337)
;
3338
3339 Alignment = BVAlign;
3340 }
3341 }
3342
3343 // Array members are always packed to their original alignment.
3344 if (Flags.isInConsecutiveRegs()) {
3345 // If the array member was split into multiple registers, the first
3346 // needs to be aligned to the size of the full type. (Except for
3347 // ppcf128, which is only aligned as its f64 components.)
3348 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3349 Alignment = Align(OrigVT.getStoreSize());
3350 else
3351 Alignment = Align(ArgVT.getStoreSize());
3352 }
3353
3354 return Alignment;
3355}
3356
3357/// CalculateStackSlotUsed - Return whether this argument will use its
3358/// stack slot (instead of being passed in registers). ArgOffset,
3359/// AvailableFPRs, and AvailableVRs must hold the current argument
3360/// position, and will be updated to account for this argument.
3361static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3362 ISD::ArgFlagsTy Flags,
3363 unsigned PtrByteSize,
3364 unsigned LinkageSize,
3365 unsigned ParamAreaSize,
3366 unsigned &ArgOffset,
3367 unsigned &AvailableFPRs,
3368 unsigned &AvailableVRs, bool HasQPX) {
3369 bool UseMemory = false;
3370
3371 // Respect alignment of argument on the stack.
3372 Align Alignment =
3373 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3374 ArgOffset = alignTo(ArgOffset, Alignment);
3375 // If there's no space left in the argument save area, we must
3376 // use memory (this check also catches zero-sized arguments).
3377 if (ArgOffset >= LinkageSize + ParamAreaSize)
3378 UseMemory = true;
3379
3380 // Allocate argument on the stack.
3381 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3382 if (Flags.isInConsecutiveRegsLast())
3383 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3384 // If we overran the argument save area, we must use memory
3385 // (this check catches arguments passed partially in memory)
3386 if (ArgOffset > LinkageSize + ParamAreaSize)
3387 UseMemory = true;
3388
3389 // However, if the argument is actually passed in an FPR or a VR,
3390 // we don't use memory after all.
3391 if (!Flags.isByVal()) {
3392 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3393 // QPX registers overlap with the scalar FP registers.
3394 (HasQPX && (ArgVT == MVT::v4f32 ||
3395 ArgVT == MVT::v4f64 ||
3396 ArgVT == MVT::v4i1)))
3397 if (AvailableFPRs > 0) {
3398 --AvailableFPRs;
3399 return false;
3400 }
3401 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3402 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3403 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3404 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3405 if (AvailableVRs > 0) {
3406 --AvailableVRs;
3407 return false;
3408 }
3409 }
3410
3411 return UseMemory;
3412}
3413
3414/// EnsureStackAlignment - Round stack frame size up from NumBytes to
3415/// ensure minimum alignment required for target.
3416static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3417 unsigned NumBytes) {
3418 unsigned TargetAlign = Lowering->getStackAlignment();
3419 unsigned AlignMask = TargetAlign - 1;
3420 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3421 return NumBytes;
3422}
3423
3424SDValue PPCTargetLowering::LowerFormalArguments(
3425 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3426 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3427 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3428 if (Subtarget.isAIXABI())
3429 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3430 InVals);
3431 if (Subtarget.is64BitELFABI())
3432 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3433 InVals);
3434 if (Subtarget.is32BitELFABI())
3435 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3436 InVals);
3437
3438 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3439 InVals);
3440}
3441
3442SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3443 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3444 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3445 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3446
3447 // 32-bit SVR4 ABI Stack Frame Layout:
3448 // +-----------------------------------+
3449 // +--> | Back chain |
3450 // | +-----------------------------------+
3451 // | | Floating-point register save area |
3452 // | +-----------------------------------+
3453 // | | General register save area |
3454 // | +-----------------------------------+
3455 // | | CR save word |
3456 // | +-----------------------------------+
3457 // | | VRSAVE save word |
3458 // | +-----------------------------------+
3459 // | | Alignment padding |
3460 // | +-----------------------------------+
3461 // | | Vector register save area |
3462 // | +-----------------------------------+
3463 // | | Local variable space |
3464 // | +-----------------------------------+
3465 // | | Parameter list area |
3466 // | +-----------------------------------+
3467 // | | LR save word |
3468 // | +-----------------------------------+
3469 // SP--> +--- | Back chain |
3470 // +-----------------------------------+
3471 //
3472 // Specifications:
3473 // System V Application Binary Interface PowerPC Processor Supplement
3474 // AltiVec Technology Programming Interface Manual
3475
3476 MachineFunction &MF = DAG.getMachineFunction();
3477 MachineFrameInfo &MFI = MF.getFrameInfo();
3478 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3479
3480 EVT PtrVT = getPointerTy(MF.getDataLayout());
3481 // Potential tail calls could cause overwriting of argument stack slots.
3482 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3483 (CallConv == CallingConv::Fast));
3484 unsigned PtrByteSize = 4;
3485
3486 // Assign locations to all of the incoming arguments.
3487 SmallVector<CCValAssign, 16> ArgLocs;
3488 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3489 *DAG.getContext());
3490
3491 // Reserve space for the linkage area on the stack.
3492 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3493 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3494 if (useSoftFloat())
3495 CCInfo.PreAnalyzeFormalArguments(Ins);
3496
3497 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3498 CCInfo.clearWasPPCF128();
3499
3500 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3501 CCValAssign &VA = ArgLocs[i];
3502
3503 // Arguments stored in registers.
3504 if (VA.isRegLoc()) {
3505 const TargetRegisterClass *RC;
3506 EVT ValVT = VA.getValVT();
3507
3508 switch (ValVT.getSimpleVT().SimpleTy) {
3509 default:
3510 llvm_unreachable("ValVT not supported by formal arguments Lowering")::llvm::llvm_unreachable_internal("ValVT not supported by formal arguments Lowering"
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3510)
;
3511 case MVT::i1:
3512 case MVT::i32:
3513 RC = &PPC::GPRCRegClass;
3514 break;
3515 case MVT::f32:
3516 if (Subtarget.hasP8Vector())
3517 RC = &PPC::VSSRCRegClass;
3518 else if (Subtarget.hasSPE())
3519 RC = &PPC::GPRCRegClass;
3520 else
3521 RC = &PPC::F4RCRegClass;
3522 break;
3523 case MVT::f64:
3524 if (Subtarget.hasVSX())
3525 RC = &PPC::VSFRCRegClass;
3526 else if (Subtarget.hasSPE())
3527 // SPE passes doubles in GPR pairs.
3528 RC = &PPC::GPRCRegClass;
3529 else
3530 RC = &PPC::F8RCRegClass;
3531 break;
3532 case MVT::v16i8:
3533 case MVT::v8i16:
3534 case MVT::v4i32:
3535 RC = &PPC::VRRCRegClass;
3536 break;
3537 case MVT::v4f32:
3538 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3539 break;
3540 case MVT::v2f64:
3541 case MVT::v2i64:
3542 RC = &PPC::VRRCRegClass;
3543 break;
3544 case MVT::v4f64:
3545 RC = &PPC::QFRCRegClass;
3546 break;
3547 case MVT::v4i1:
3548 RC = &PPC::QBRCRegClass;
3549 break;
3550 }
3551
3552 SDValue ArgValue;
3553 // Transform the arguments stored in physical registers into
3554 // virtual ones.
3555 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3556 assert(i + 1 < e && "No second half of double precision argument")((i + 1 < e && "No second half of double precision argument"
) ? static_cast<void> (0) : __assert_fail ("i + 1 < e && \"No second half of double precision argument\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3556, __PRETTY_FUNCTION__))
;
3557 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3558 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3559 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3560 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3561 if (!Subtarget.isLittleEndian())
3562 std::swap (ArgValueLo, ArgValueHi);
3563 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3564 ArgValueHi);
3565 } else {
3566 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3567 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3568 ValVT == MVT::i1 ? MVT::i32 : ValVT);
3569 if (ValVT == MVT::i1)
3570 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3571 }
3572
3573 InVals.push_back(ArgValue);
3574 } else {
3575 // Argument stored in memory.
3576 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3576, __PRETTY_FUNCTION__))
;
3577
3578 // Get the extended size of the argument type in stack
3579 unsigned ArgSize = VA.getLocVT().getStoreSize();
3580 // Get the actual size of the argument type
3581 unsigned ObjSize = VA.getValVT().getStoreSize();
3582 unsigned ArgOffset = VA.getLocMemOffset();
3583 // Stack objects in PPC32 are right justified.
3584 ArgOffset += ArgSize - ObjSize;
3585 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3586
3587 // Create load nodes to retrieve arguments from the stack.
3588 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3589 InVals.push_back(
3590 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3591 }
3592 }
3593
3594 // Assign locations to all of the incoming aggregate by value arguments.
3595 // Aggregates passed by value are stored in the local variable space of the
3596 // caller's stack frame, right above the parameter list area.
3597 SmallVector<CCValAssign, 16> ByValArgLocs;
3598 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3599 ByValArgLocs, *DAG.getContext());
3600
3601 // Reserve stack space for the allocations in CCInfo.
3602 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3603
3604 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3605
3606 // Area that is at least reserved in the caller of this function.
3607 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3608 MinReservedArea = std::max(MinReservedArea, LinkageSize);
3609
3610 // Set the size that is at least reserved in caller of this function. Tail
3611 // call optimized function's reserved stack space needs to be aligned so that
3612 // taking the difference between two stack areas will result in an aligned
3613 // stack.
3614 MinReservedArea =
3615 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3616 FuncInfo->setMinReservedArea(MinReservedArea);
3617
3618 SmallVector<SDValue, 8> MemOps;
3619
3620 // If the function takes variable number of arguments, make a frame index for
3621 // the start of the first vararg value... for expansion of llvm.va_start.
3622 if (isVarArg) {
3623 static const MCPhysReg GPArgRegs[] = {
3624 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3625 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3626 };
3627 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3628
3629 static const MCPhysReg FPArgRegs[] = {
3630 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3631 PPC::F8
3632 };
3633 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3634
3635 if (useSoftFloat() || hasSPE())
3636 NumFPArgRegs = 0;
3637
3638 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3639 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3640
3641 // Make room for NumGPArgRegs and NumFPArgRegs.
3642 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3643 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3644
3645 FuncInfo->setVarArgsStackOffset(
3646 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3647 CCInfo.getNextStackOffset(), true));
3648
3649 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3650 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3651
3652 // The fixed integer arguments of a variadic function are stored to the
3653 // VarArgsFrameIndex on the stack so that they may be loaded by
3654 // dereferencing the result of va_next.
3655 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3656 // Get an existing live-in vreg, or add a new one.
3657 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3658 if (!VReg)
3659 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3660
3661 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3662 SDValue Store =
3663 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3664 MemOps.push_back(Store);
3665 // Increment the address by four for the next argument to store
3666 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3667 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3668 }
3669
3670 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3671 // is set.
3672 // The double arguments are stored to the VarArgsFrameIndex
3673 // on the stack.
3674 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3675 // Get an existing live-in vreg, or add a new one.
3676 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3677 if (!VReg)
3678 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3679
3680 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3681 SDValue Store =
3682 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3683 MemOps.push_back(Store);
3684 // Increment the address by eight for the next argument to store
3685 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3686 PtrVT);
3687 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3688 }
3689 }
3690
3691 if (!MemOps.empty())
3692 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3693
3694 return Chain;
3695}
3696
3697// PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3698// value to MVT::i64 and then truncate to the correct register size.
3699SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3700 EVT ObjectVT, SelectionDAG &DAG,
3701 SDValue ArgVal,
3702 const SDLoc &dl) const {
3703 if (Flags.isSExt())
3704 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3705 DAG.getValueType(ObjectVT));
3706 else if (Flags.isZExt())
3707 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3708 DAG.getValueType(ObjectVT));
3709
3710 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3711}
3712
3713SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3714 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3715 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3716 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3717 // TODO: add description of PPC stack frame format, or at least some docs.
3718 //
3719 bool isELFv2ABI = Subtarget.isELFv2ABI();
3720 bool isLittleEndian = Subtarget.isLittleEndian();
3721 MachineFunction &MF = DAG.getMachineFunction();
3722 MachineFrameInfo &MFI = MF.getFrameInfo();
3723 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3724
3725 assert(!(CallConv == CallingConv::Fast && isVarArg) &&((!(CallConv == CallingConv::Fast && isVarArg) &&
"fastcc not supported on varargs functions") ? static_cast<
void> (0) : __assert_fail ("!(CallConv == CallingConv::Fast && isVarArg) && \"fastcc not supported on varargs functions\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3726, __PRETTY_FUNCTION__))
3726 "fastcc not supported on varargs functions")((!(CallConv == CallingConv::Fast && isVarArg) &&
"fastcc not supported on varargs functions") ? static_cast<
void> (0) : __assert_fail ("!(CallConv == CallingConv::Fast && isVarArg) && \"fastcc not supported on varargs functions\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3726, __PRETTY_FUNCTION__))
;
3727
3728 EVT PtrVT = getPointerTy(MF.getDataLayout());
3729 // Potential tail calls could cause overwriting of argument stack slots.
3730 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3731 (CallConv == CallingConv::Fast));
3732 unsigned PtrByteSize = 8;
3733 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3734
3735 static const MCPhysReg GPR[] = {
3736 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3737 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3738 };
3739 static const MCPhysReg VR[] = {
3740 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3741 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3742 };
3743
3744 const unsigned Num_GPR_Regs = array_lengthof(GPR);
3745 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3746 const unsigned Num_VR_Regs = array_lengthof(VR);
3747 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3748
3749 // Do a first pass over the arguments to determine whether the ABI
3750 // guarantees that our caller has allocated the parameter save area
3751 // on its stack frame. In the ELFv1 ABI, this is always the case;
3752 // in the ELFv2 ABI, it is true if this is a vararg function or if
3753 // any parameter is located in a stack slot.
3754
3755 bool HasParameterArea = !isELFv2ABI || isVarArg;
3756 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3757 unsigned NumBytes = LinkageSize;
3758 unsigned AvailableFPRs = Num_FPR_Regs;
3759 unsigned AvailableVRs = Num_VR_Regs;
3760 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3761 if (Ins[i].Flags.isNest())
3762 continue;
3763
3764 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3765 PtrByteSize, LinkageSize, ParamAreaSize,
3766 NumBytes, AvailableFPRs, AvailableVRs,
3767 Subtarget.hasQPX()))
3768 HasParameterArea = true;
3769 }
3770
3771 // Add DAG nodes to load the arguments or copy them out of registers. On
3772 // entry to a function on PPC, the arguments start after the linkage area,
3773 // although the first ones are often in registers.
3774
3775 unsigned ArgOffset = LinkageSize;
3776 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3777 unsigned &QFPR_idx = FPR_idx;
3778 SmallVector<SDValue, 8> MemOps;
3779 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3780 unsigned CurArgIdx = 0;
3781 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3782 SDValue ArgVal;
3783 bool needsLoad = false;
3784 EVT ObjectVT = Ins[ArgNo].VT;
3785 EVT OrigVT = Ins[ArgNo].ArgVT;
3786 unsigned ObjSize = ObjectVT.getStoreSize();
3787 unsigned ArgSize = ObjSize;
3788 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3789 if (Ins[ArgNo].isOrigArg()) {
3790 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3791 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3792 }
3793 // We re-align the argument offset for each argument, except when using the
3794 // fast calling convention, when we need to make sure we do that only when
3795 // we'll actually use a stack slot.
3796 unsigned CurArgOffset;
3797 Align Alignment;
3798 auto ComputeArgOffset = [&]() {
3799 /* Respect alignment of argument on the stack. */
3800 Alignment =
3801 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3802 ArgOffset = alignTo(ArgOffset, Alignment);
3803 CurArgOffset = ArgOffset;
3804 };
3805
3806 if (CallConv != CallingConv::Fast) {
3807 ComputeArgOffset();
3808
3809 /* Compute GPR index associated with argument offset. */
3810 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3811 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3812 }
3813
3814 // FIXME the codegen can be much improved in some cases.
3815 // We do not have to keep everything in memory.
3816 if (Flags.isByVal()) {
3817 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit")((Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"
) ? static_cast<void> (0) : __assert_fail ("Ins[ArgNo].isOrigArg() && \"Byval arguments cannot be implicit\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3817, __PRETTY_FUNCTION__))
;
3818
3819 if (CallConv == CallingConv::Fast)
3820 ComputeArgOffset();
3821
3822 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3823 ObjSize = Flags.getByValSize();
3824 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3825 // Empty aggregate parameters do not take up registers. Examples:
3826 // struct { } a;
3827 // union { } b;
3828 // int c[0];
3829 // etc. However, we have to provide a place-holder in InVals, so
3830 // pretend we have an 8-byte item at the current address for that
3831 // purpose.
3832 if (!ObjSize) {
3833 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3834 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3835 InVals.push_back(FIN);
3836 continue;
3837 }
3838
3839 // Create a stack object covering all stack doublewords occupied
3840 // by the argument. If the argument is (fully or partially) on
3841 // the stack, or if the argument is fully in registers but the
3842 // caller has allocated the parameter save anyway, we can refer
3843 // directly to the caller's stack frame. Otherwise, create a
3844 // local copy in our own frame.
3845 int FI;
3846 if (HasParameterArea ||
3847 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3848 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3849 else
3850 FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3851 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3852
3853 // Handle aggregates smaller than 8 bytes.
3854 if (ObjSize < PtrByteSize) {
3855 // The value of the object is its address, which differs from the
3856 // address of the enclosing doubleword on big-endian systems.
3857 SDValue Arg = FIN;
3858 if (!isLittleEndian) {
3859 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3860 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3861 }
3862 InVals.push_back(Arg);
3863
3864 if (GPR_idx != Num_GPR_Regs) {
3865 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3866 FuncInfo->addLiveInAttr(VReg, Flags);
3867 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3868 SDValue Store;
3869
3870 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3871 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3872 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3873 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3874 MachinePointerInfo(&*FuncArg), ObjType);
3875 } else {
3876 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3877 // store the whole register as-is to the parameter save area
3878 // slot.
3879 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3880 MachinePointerInfo(&*FuncArg));
3881 }
3882
3883 MemOps.push_back(Store);
3884 }
3885 // Whether we copied from a register or not, advance the offset
3886 // into the parameter save area by a full doubleword.
3887 ArgOffset += PtrByteSize;
3888 continue;
3889 }
3890
3891 // The value of the object is its address, which is the address of
3892 // its first stack doubleword.
3893 InVals.push_back(FIN);
3894
3895 // Store whatever pieces of the object are in registers to memory.
3896 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3897 if (GPR_idx == Num_GPR_Regs)
3898 break;
3899
3900 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3901 FuncInfo->addLiveInAttr(VReg, Flags);
3902 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3903 SDValue Addr = FIN;
3904 if (j) {
3905 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3906 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3907 }
3908 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3909 MachinePointerInfo(&*FuncArg, j));
3910 MemOps.push_back(Store);
3911 ++GPR_idx;
3912 }
3913 ArgOffset += ArgSize;
3914 continue;
3915 }
3916
3917 switch (ObjectVT.getSimpleVT().SimpleTy) {
3918 default: llvm_unreachable("Unhandled argument type!")::llvm::llvm_unreachable_internal("Unhandled argument type!",
"/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3918)
;
3919 case MVT::i1:
3920 case MVT::i32:
3921 case MVT::i64:
3922 if (Flags.isNest()) {
3923 // The 'nest' parameter, if any, is passed in R11.
3924 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3925 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3926
3927 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3928 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3929
3930 break;
3931 }
3932
3933 // These can be scalar arguments or elements of an integer array type
3934 // passed directly. Clang may use those instead of "byval" aggregate
3935 // types to avoid forcing arguments to memory unnecessarily.
3936 if (GPR_idx != Num_GPR_Regs) {
3937 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3938 FuncInfo->addLiveInAttr(VReg, Flags);
3939 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3940
3941 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3942 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3943 // value to MVT::i64 and then truncate to the correct register size.
3944 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3945 } else {
3946 if (CallConv == CallingConv::Fast)
3947 ComputeArgOffset();
3948
3949 needsLoad = true;
3950 ArgSize = PtrByteSize;
3951 }
3952 if (CallConv != CallingConv::Fast || needsLoad)
3953 ArgOffset += 8;
3954 break;
3955
3956 case MVT::f32:
3957 case MVT::f64:
3958 // These can be scalar arguments or elements of a float array type
3959 // passed directly. The latter are used to implement ELFv2 homogenous
3960 // float aggregates.
3961 if (FPR_idx != Num_FPR_Regs) {
3962 unsigned VReg;
3963
3964 if (ObjectVT == MVT::f32)
3965 VReg = MF.addLiveIn(FPR[FPR_idx],
3966 Subtarget.hasP8Vector()
3967 ? &PPC::VSSRCRegClass
3968 : &PPC::F4RCRegClass);
3969 else
3970 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3971 ? &PPC::VSFRCRegClass
3972 : &PPC::F8RCRegClass);
3973
3974 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3975 ++FPR_idx;
3976 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3977 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3978 // once we support fp <-> gpr moves.
3979
3980 // This can only ever happen in the presence of f32 array types,
3981 // since otherwise we never run out of FPRs before running out
3982 // of GPRs.
3983 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3984 FuncInfo->addLiveInAttr(VReg, Flags);
3985 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3986
3987 if (ObjectVT == MVT::f32) {
3988 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3989 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3990 DAG.getConstant(32, dl, MVT::i32));
3991 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3992 }
3993
3994 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3995 } else {
3996 if (CallConv == CallingConv::Fast)
3997 ComputeArgOffset();
3998
3999 needsLoad = true;
4000 }
4001
4002 // When passing an array of floats, the array occupies consecutive
4003 // space in the argument area; only round up to the next doubleword
4004 // at the end of the array. Otherwise, each float takes 8 bytes.
4005 if (CallConv != CallingConv::Fast || needsLoad) {
4006 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4007 ArgOffset += ArgSize;
4008 if (Flags.isInConsecutiveRegsLast())
4009 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4010 }
4011 break;
4012 case MVT::v4f32:
4013 case MVT::v4i32:
4014 case MVT::v8i16:
4015 case MVT::v16i8:
4016 case MVT::v2f64:
4017 case MVT::v2i64:
4018 case MVT::v1i128:
4019 case MVT::f128:
4020 if (!Subtarget.hasQPX()) {
4021 // These can be scalar arguments or elements of a vector array type
4022 // passed directly. The latter are used to implement ELFv2 homogenous
4023 // vector aggregates.
4024 if (VR_idx != Num_VR_Regs) {
4025 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4026 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4027 ++VR_idx;
4028 } else {
4029 if (CallConv == CallingConv::Fast)
4030 ComputeArgOffset();
4031 needsLoad = true;
4032 }
4033 if (CallConv != CallingConv::Fast || needsLoad)
4034 ArgOffset += 16;
4035 break;
4036 } // not QPX
4037
4038 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&((ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && "Invalid QPX parameter type"
) ? static_cast<void> (0) : __assert_fail ("ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && \"Invalid QPX parameter type\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4039, __PRETTY_FUNCTION__))
4039 "Invalid QPX parameter type")((ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && "Invalid QPX parameter type"
) ? static_cast<void> (0) : __assert_fail ("ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && \"Invalid QPX parameter type\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4039, __PRETTY_FUNCTION__))
;
4040 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4041
4042 case MVT::v4f64:
4043 case MVT::v4i1:
4044 // QPX vectors are treated like their scalar floating-point subregisters
4045 // (except that they're larger).
4046 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4047 if (QFPR_idx != Num_QFPR_Regs) {
4048 const TargetRegisterClass *RC;
4049 switch (ObjectVT.getSimpleVT().SimpleTy) {
4050 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4051 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4052 default: RC = &PPC::QBRCRegClass; break;
4053 }
4054
4055 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4056 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4057 ++QFPR_idx;
4058 } else {
4059 if (CallConv == CallingConv::Fast)
4060 ComputeArgOffset();
4061 needsLoad = true;
4062 }
4063 if (CallConv != CallingConv::Fast || needsLoad)
4064 ArgOffset += Sz;
4065 break;
4066 }
4067
4068 // We need to load the argument to a virtual register if we determined
4069 // above that we ran out of physical registers of the appropriate type.
4070 if (needsLoad) {
4071 if (ObjSize < ArgSize && !isLittleEndian)
4072 CurArgOffset += ArgSize - ObjSize;
4073 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4074 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4075 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4076 }
4077
4078 InVals.push_back(ArgVal);
4079 }
4080
4081 // Area that is at least reserved in the caller of this function.
4082 unsigned MinReservedArea;
4083 if (HasParameterArea)
4084 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4085 else
4086 MinReservedArea = LinkageSize;
4087
4088 // Set the size that is at least reserved in caller of this function. Tail
4089 // call optimized functions' reserved stack space needs to be aligned so that
4090 // taking the difference between two stack areas will result in an aligned
4091 // stack.
4092 MinReservedArea =
4093 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4094 FuncInfo->setMinReservedArea(MinReservedArea);
4095
4096 // If the function takes variable number of arguments, make a frame index for
4097 // the start of the first vararg value... for expansion of llvm.va_start.
4098 if (isVarArg) {
4099 int Depth = ArgOffset;
4100
4101 FuncInfo->setVarArgsFrameIndex(
4102 MFI.CreateFixedObject(PtrByteSize, Depth, true));
4103 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4104
4105 // If this function is vararg, store any remaining integer argument regs
4106 // to their spots on the stack so that they may be loaded by dereferencing
4107 // the result of va_next.
4108 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4109 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4110 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4111 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4112 SDValue Store =
4113 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4114 MemOps.push_back(Store);
4115 // Increment the address by four for the next argument to store
4116 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4117 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4118 }
4119 }
4120
4121 if (!MemOps.empty())
4122 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4123
4124 return Chain;
4125}
4126
4127SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4128 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4129 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4130 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4131 // TODO: add description of PPC stack frame format, or at least some docs.
4132 //
4133 MachineFunction &MF = DAG.getMachineFunction();
4134 MachineFrameInfo &MFI = MF.getFrameInfo();
4135 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4136
4137 EVT PtrVT = getPointerTy(MF.getDataLayout());
4138 bool isPPC64 = PtrVT == MVT::i64;
4139 // Potential tail calls could cause overwriting of argument stack slots.
4140 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4141 (CallConv == CallingConv::Fast));
4142 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4143 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4144 unsigned ArgOffset = LinkageSize;
4145 // Area that is at least reserved in caller of this function.
4146 unsigned MinReservedArea = ArgOffset;
4147
4148 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4149 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4150 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4151 };
4152 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4153 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4154 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4155 };
4156 static const MCPhysReg VR[] = {
4157 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4158 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4159 };
4160
4161 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4162 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4163 const unsigned Num_VR_Regs = array_lengthof( VR);
4164
4165 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4166
4167 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4168
4169 // In 32-bit non-varargs functions, the stack space for vectors is after the
4170 // stack space for non-vectors. We do not use this space unless we have
4171 // too many vectors to fit in registers, something that only occurs in
4172 // constructed examples:), but we have to walk the arglist to figure
4173 // that out...for the pathological case, compute VecArgOffset as the
4174 // start of the vector parameter area. Computing VecArgOffset is the
4175 // entire point of the following loop.
4176 unsigned VecArgOffset = ArgOffset;
4177 if (!isVarArg && !isPPC64) {
4178 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4179 ++ArgNo) {
4180 EVT ObjectVT = Ins[ArgNo].VT;
4181 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4182
4183 if (Flags.isByVal()) {
4184 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4185 unsigned ObjSize = Flags.getByValSize();
4186 unsigned ArgSize =
4187 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4188 VecArgOffset += ArgSize;
4189 continue;
4190 }
4191
4192 switch(ObjectVT.getSimpleVT().SimpleTy) {
4193 default: llvm_unreachable("Unhandled argument type!")::llvm::llvm_unreachable_internal("Unhandled argument type!",
"/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4193)
;
4194 case MVT::i1:
4195 case MVT::i32:
4196 case MVT::f32:
4197 VecArgOffset += 4;
4198 break;
4199 case MVT::i64: // PPC64
4200 case MVT::f64:
4201 // FIXME: We are guaranteed to be !isPPC64 at this point.
4202 // Does MVT::i64 apply?
4203 VecArgOffset += 8;
4204 break;
4205 case MVT::v4f32:
4206 case MVT::v4i32:
4207 case MVT::v8i16:
4208 case MVT::v16i8:
4209 // Nothing to do, we're only looking at Nonvector args here.
4210 break;
4211 }
4212 }
4213 }
4214 // We've found where the vector parameter area in memory is. Skip the
4215 // first 12 parameters; these don't use that memory.
4216 VecArgOffset = ((VecArgOffset+15)/16)*16;
4217 VecArgOffset += 12*16;
4218
4219 // Add DAG nodes to load the arguments or copy them out of registers. On
4220 // entry to a function on PPC, the arguments start after the linkage area,
4221 // although the first ones are often in registers.
4222
4223 SmallVector<SDValue, 8> MemOps;
4224 unsigned nAltivecParamsAtEnd = 0;
4225 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4226 unsigned CurArgIdx = 0;
4227 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4228 SDValue ArgVal;
4229 bool needsLoad = false;
4230 EVT ObjectVT = Ins[ArgNo].VT;
4231 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4232 unsigned ArgSize = ObjSize;
4233 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4234 if (Ins[ArgNo].isOrigArg()) {
4235 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4236 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4237 }
4238 unsigned CurArgOffset = ArgOffset;
4239
4240 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4241 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4242 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4243 if (isVarArg || isPPC64) {
4244 MinReservedArea = ((MinReservedArea+15)/16)*16;
4245 MinReservedArea += CalculateStackSlotSize(ObjectVT,
4246 Flags,
4247 PtrByteSize);
4248 } else nAltivecParamsAtEnd++;
4249 } else
4250 // Calculate min reserved area.
4251 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4252 Flags,
4253 PtrByteSize);
4254
4255 // FIXME the codegen can be much improved in some cases.
4256 // We do not have to keep everything in memory.
4257 if (Flags.isByVal()) {
4258 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit")((Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"
) ? static_cast<void> (0) : __assert_fail ("Ins[ArgNo].isOrigArg() && \"Byval arguments cannot be implicit\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4258, __PRETTY_FUNCTION__))
;
4259
4260 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4261 ObjSize = Flags.getByValSize();
4262 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4263 // Objects of size 1 and 2 are right justified, everything else is
4264 // left justified. This means the memory address is adjusted forwards.
4265 if (ObjSize==1 || ObjSize==2) {
4266 CurArgOffset = CurArgOffset + (4 - ObjSize);
4267 }
4268 // The value of the object is its address.
4269 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4270 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4271 InVals.push_back(FIN);
4272 if (ObjSize==1 || ObjSize==2) {
4273 if (GPR_idx != Num_GPR_Regs) {
4274 unsigned VReg;
4275 if (isPPC64)
4276 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4277 else
4278 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4279 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4280 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4281 SDValue Store =
4282 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4283 MachinePointerInfo(&*FuncArg), ObjType);
4284 MemOps.push_back(Store);
4285 ++GPR_idx;
4286 }
4287
4288 ArgOffset += PtrByteSize;
4289
4290 continue;
4291 }
4292 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4293 // Store whatever pieces of the object are in registers
4294 // to memory. ArgOffset will be the address of the beginning
4295 // of the object.
4296 if (GPR_idx != Num_GPR_Regs) {
4297 unsigned VReg;
4298 if (isPPC64)
4299 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4300 else
4301 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4302 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4303 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4304 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4305 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4306 MachinePointerInfo(&*FuncArg, j));
4307 MemOps.push_back(Store);
4308 ++GPR_idx;
4309 ArgOffset += PtrByteSize;
4310 } else {
4311 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4312 break;
4313 }
4314 }
4315 continue;
4316 }
4317
4318 switch (ObjectVT.getSimpleVT().SimpleTy) {
4319 default: llvm_unreachable("Unhandled argument type!")::llvm::llvm_unreachable_internal("Unhandled argument type!",
"/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4319)
;
4320 case MVT::i1:
4321 case MVT::i32:
4322 if (!isPPC64) {
4323 if (GPR_idx != Num_GPR_Regs) {
4324 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4325 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4326
4327 if (ObjectVT == MVT::i1)
4328 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4329
4330 ++GPR_idx;
4331 } else {
4332 needsLoad = true;
4333 ArgSize = PtrByteSize;
4334 }
4335 // All int arguments reserve stack space in the Darwin ABI.
4336 ArgOffset += PtrByteSize;
4337 break;
4338 }
4339 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4340 case MVT::i64: // PPC64
4341 if (GPR_idx != Num_GPR_Regs) {
4342 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4343 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4344
4345 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4346 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4347 // value to MVT::i64 and then truncate to the correct register size.
4348 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4349
4350 ++GPR_idx;
4351 } else {
4352 needsLoad = true;
4353 ArgSize = PtrByteSize;
4354 }
4355 // All int arguments reserve stack space in the Darwin ABI.
4356 ArgOffset += 8;
4357 break;
4358
4359 case MVT::f32:
4360 case MVT::f64:
4361 // Every 4 bytes of argument space consumes one of the GPRs available for
4362 // argument passing.
4363 if (GPR_idx != Num_GPR_Regs) {
4364 ++GPR_idx;
4365 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4366 ++GPR_idx;
4367 }
4368 if (FPR_idx != Num_FPR_Regs) {
4369 unsigned VReg;
4370
4371 if (ObjectVT == MVT::f32)
4372 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4373 else
4374 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4375
4376 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4377 ++FPR_idx;
4378 } else {
4379 needsLoad = true;
4380 }
4381
4382 // All FP arguments reserve stack space in the Darwin ABI.
4383 ArgOffset += isPPC64 ? 8 : ObjSize;
4384 break;
4385 case MVT::v4f32:
4386 case MVT::v4i32:
4387 case MVT::v8i16:
4388 case MVT::v16i8:
4389 // Note that vector arguments in registers don't reserve stack space,
4390 // except in varargs functions.
4391 if (VR_idx != Num_VR_Regs) {
4392 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4393 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4394 if (isVarArg) {
4395 while ((ArgOffset % 16) != 0) {
4396 ArgOffset += PtrByteSize;
4397 if (GPR_idx != Num_GPR_Regs)
4398 GPR_idx++;
4399 }
4400 ArgOffset += 16;
4401 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4402 }
4403 ++VR_idx;
4404 } else {
4405 if (!isVarArg && !isPPC64) {
4406 // Vectors go after all the nonvectors.
4407 CurArgOffset = VecArgOffset;
4408 VecArgOffset += 16;
4409 } else {
4410 // Vectors are aligned.
4411 ArgOffset = ((ArgOffset+15)/16)*16;
4412 CurArgOffset = ArgOffset;
4413 ArgOffset += 16;
4414 }
4415 needsLoad = true;
4416 }
4417 break;
4418 }
4419
4420 // We need to load the argument to a virtual register if we determined above
4421 // that we ran out of physical registers of the appropriate type.
4422 if (needsLoad) {
4423 int FI = MFI.CreateFixedObject(ObjSize,
4424 CurArgOffset + (ArgSize - ObjSize),
4425 isImmutable);
4426 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4427 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4428 }
4429
4430 InVals.push_back(ArgVal);
4431 }
4432
4433 // Allow for Altivec parameters at the end, if needed.
4434 if (nAltivecParamsAtEnd) {
4435 MinReservedArea = ((MinReservedArea+15)/16)*16;
4436 MinReservedArea += 16*nAltivecParamsAtEnd;
4437 }
4438
4439 // Area that is at least reserved in the caller of this function.
4440 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4441
4442 // Set the size that is at least reserved in caller of this function. Tail
4443 // call optimized functions' reserved stack space needs to be aligned so that
4444 // taking the difference between two stack areas will result in an aligned
4445 // stack.
4446 MinReservedArea =
4447 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4448 FuncInfo->setMinReservedArea(MinReservedArea);
4449
4450 // If the function takes variable number of arguments, make a frame index for
4451 // the start of the first vararg value... for expansion of llvm.va_start.
4452 if (isVarArg) {
4453 int Depth = ArgOffset;
4454
4455 FuncInfo->setVarArgsFrameIndex(
4456 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4457 Depth, true));
4458 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4459
4460 // If this function is vararg, store any remaining integer argument regs
4461 // to their spots on the stack so that they may be loaded by dereferencing
4462 // the result of va_next.
4463 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4464 unsigned VReg;
4465
4466 if (isPPC64)
4467 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4468 else
4469 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4470
4471 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4472 SDValue Store =
4473 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4474 MemOps.push_back(Store);
4475 // Increment the address by four for the next argument to store
4476 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4477 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4478 }
4479 }
4480
4481 if (!MemOps.empty())
4482 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4483
4484 return Chain;
4485}
4486
4487/// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4488/// adjusted to accommodate the arguments for the tailcall.
4489static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4490 unsigned ParamSize) {
4491
4492 if (!isTailCall) return 0;
4493
4494 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4495 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4496 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4497 // Remember only if the new adjustment is bigger.
4498 if (SPDiff < FI->getTailCallSPDelta())
4499 FI->setTailCallSPDelta(SPDiff);
4500
4501 return SPDiff;
4502}
4503
4504static bool isFunctionGlobalAddress(SDValue Callee);
4505
4506static bool
4507callsShareTOCBase(const Function *Caller, SDValue Callee,
4508 const TargetMachine &TM) {
4509 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4510 // don't have enough information to determine if the caller and calle share
4511 // the same TOC base, so we have to pessimistically assume they don't for
4512 // correctness.
4513 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4514 if (!G)
4515 return false;
4516
4517 const GlobalValue *GV = G->getGlobal();
4518 // The medium and large code models are expected to provide a sufficiently
4519 // large TOC to provide all data addressing needs of a module with a
4520 // single TOC. Since each module will be addressed with a single TOC then we
4521 // only need to check that caller and callee don't cross dso boundaries.
4522 if (CodeModel::Medium == TM.getCodeModel() ||
4523 CodeModel::Large == TM.getCodeModel())
4524 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4525
4526 // Otherwise we need to ensure callee and caller are in the same section,
4527 // since the linker may allocate multiple TOCs, and we don't know which
4528 // sections will belong to the same TOC base.
4529
4530 if (!GV->isStrongDefinitionForLinker())
4531 return false;
4532
4533 // Any explicitly-specified sections and section prefixes must also match.
4534 // Also, if we're using -ffunction-sections, then each function is always in
4535 // a different section (the same is true for COMDAT functions).
4536 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4537 GV->getSection() != Caller->getSection())
4538 return false;
4539 if (const auto *F = dyn_cast<Function>(GV)) {
4540 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4541 return false;
4542 }
4543
4544 // If the callee might be interposed, then we can't assume the ultimate call
4545 // target will be in the same section. Even in cases where we can assume that
4546 // interposition won't happen, in any case where the linker might insert a
4547 // stub to allow for interposition, we must generate code as though
4548 // interposition might occur. To understand why this matters, consider a
4549 // situation where: a -> b -> c where the arrows indicate calls. b and c are
4550 // in the same section, but a is in a different module (i.e. has a different
4551 // TOC base pointer). If the linker allows for interposition between b and c,
4552 // then it will generate a stub for the call edge between b and c which will
4553 // save the TOC pointer into the designated stack slot allocated by b. If we
4554 // return true here, and therefore allow a tail call between b and c, that
4555 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4556 // pointer into the stack slot allocated by a (where the a -> b stub saved
4557 // a's TOC base pointer). If we're not considering a tail call, but rather,
4558 // whether a nop is needed after the call instruction in b, because the linker
4559 // will insert a stub, it might complain about a missing nop if we omit it
4560 // (although many don't complain in this case).
4561 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4562 return false;
4563
4564 return true;
4565}
4566
4567static bool
4568needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4569 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4570 assert(Subtarget.is64BitELFABI())((Subtarget.is64BitELFABI()) ? static_cast<void> (0) : __assert_fail
("Subtarget.is64BitELFABI()", "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4570, __PRETTY_FUNCTION__))
;
4571
4572 const unsigned PtrByteSize = 8;
4573 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4574
4575 static const MCPhysReg GPR[] = {
4576 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4577 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4578 };
4579 static const MCPhysReg VR[] = {
4580 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4581 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4582 };
4583
4584 const unsigned NumGPRs = array_lengthof(GPR);
4585 const unsigned NumFPRs = 13;
4586 const unsigned NumVRs = array_lengthof(VR);
4587 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4588
4589 unsigned NumBytes = LinkageSize;
4590 unsigned AvailableFPRs = NumFPRs;
4591 unsigned AvailableVRs = NumVRs;
4592
4593 for (const ISD::OutputArg& Param : Outs) {
4594 if (Param.Flags.isNest()) continue;
4595
4596 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4597 PtrByteSize, LinkageSize, ParamAreaSize,
4598 NumBytes, AvailableFPRs, AvailableVRs,
4599 Subtarget.hasQPX()))
4600 return true;
4601 }
4602 return false;
4603}
4604
4605static bool
4606hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4607 if (CS.arg_size() != CallerFn->arg_size())
4608 return false;
4609
4610 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4611 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4612 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4613
4614 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4615 const Value* CalleeArg = *CalleeArgIter;
4616 const Value* CallerArg = &(*CallerArgIter);
4617 if (CalleeArg == CallerArg)
4618 continue;
4619
4620 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4621 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4622 // }
4623 // 1st argument of callee is undef and has the same type as caller.
4624 if (CalleeArg->getType() == CallerArg->getType() &&
4625 isa<UndefValue>(CalleeArg))
4626 continue;
4627
4628 return false;
4629 }
4630
4631 return true;
4632}
4633
4634// Returns true if TCO is possible between the callers and callees
4635// calling conventions.
4636static bool
4637areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4638 CallingConv::ID CalleeCC) {
4639 // Tail calls are possible with fastcc and ccc.
4640 auto isTailCallableCC = [] (CallingConv::ID CC){
4641 return CC == CallingConv::C || CC == CallingConv::Fast;
4642 };
4643 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4644 return false;
4645
4646 // We can safely tail call both fastcc and ccc callees from a c calling
4647 // convention caller. If the caller is fastcc, we may have less stack space
4648 // than a non-fastcc caller with the same signature so disable tail-calls in
4649 // that case.
4650 return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4651}
4652
4653bool
4654PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4655 SDValue Callee,
4656 CallingConv::ID CalleeCC,
4657 ImmutableCallSite CS,
4658 bool isVarArg,
4659 const SmallVectorImpl<ISD::OutputArg> &Outs,
4660 const SmallVectorImpl<ISD::InputArg> &Ins,
4661 SelectionDAG& DAG) const {
4662 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4663
4664 if (DisableSCO && !TailCallOpt) return false;
4665
4666 // Variadic argument functions are not supported.
4667 if (isVarArg) return false;
4668
4669 auto &Caller = DAG.getMachineFunction().getFunction();
4670 // Check that the calling conventions are compatible for tco.
4671 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4672 return false;
4673
4674 // Caller contains any byval parameter is not supported.
4675 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4676 return false;
4677
4678 // Callee contains any byval parameter is not supported, too.
4679 // Note: This is a quick work around, because in some cases, e.g.
4680 // caller's stack size > callee's stack size, we are still able to apply
4681 // sibling call optimization. For example, gcc is able to do SCO for caller1
4682 // in the following example, but not for caller2.
4683 // struct test {
4684 // long int a;
4685 // char ary[56];
4686 // } gTest;
4687 // __attribute__((noinline)) int callee(struct test v, struct test *b) {
4688 // b->a = v.a;
4689 // return 0;
4690 // }
4691 // void caller1(struct test a, struct test c, struct test *b) {
4692 // callee(gTest, b); }
4693 // void caller2(struct test *b) { callee(gTest, b); }
4694 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4695 return false;
4696
4697 // If callee and caller use different calling conventions, we cannot pass
4698 // parameters on stack since offsets for the parameter area may be different.
4699 if (Caller.getCallingConv() != CalleeCC &&
4700 needStackSlotPassParameters(Subtarget, Outs))
4701 return false;
4702
4703 // No TCO/SCO on indirect call because Caller have to restore its TOC
4704 if (!isFunctionGlobalAddress(Callee) &&
4705 !isa<ExternalSymbolSDNode>(Callee))
4706 return false;
4707
4708 // If the caller and callee potentially have different TOC bases then we
4709 // cannot tail call since we need to restore the TOC pointer after the call.
4710 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4711 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4712 return false;
4713
4714 // TCO allows altering callee ABI, so we don't have to check further.
4715 if (CalleeCC == CallingConv::Fast && TailCallOpt)
4716 return true;
4717
4718 if (DisableSCO) return false;
4719
4720 // If callee use the same argument list that caller is using, then we can
4721 // apply SCO on this case. If it is not, then we need to check if callee needs
4722 // stack for passing arguments.
4723 if (!hasSameArgumentList(&Caller, CS) &&
4724 needStackSlotPassParameters(Subtarget, Outs)) {
4725 return false;
4726 }
4727
4728 return true;
4729}
4730
4731/// IsEligibleForTailCallOptimization - Check whether the call is eligible
4732/// for tail call optimization. Targets which want to do tail call
4733/// optimization should implement this function.
4734bool
4735PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4736 CallingConv::ID CalleeCC,
4737 bool isVarArg,
4738 const SmallVectorImpl<ISD::InputArg> &Ins,
4739 SelectionDAG& DAG) const {
4740 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4741 return false;
4742
4743 // Variable argument functions are not supported.
4744 if (isVarArg)
4745 return false;
4746
4747 MachineFunction &MF = DAG.getMachineFunction();
4748 CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4749 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4750 // Functions containing by val parameters are not supported.
4751 for (unsigned i = 0; i != Ins.size(); i++) {
4752 ISD::ArgFlagsTy Flags = Ins[i].Flags;
4753 if (Flags.isByVal()) return false;
4754 }
4755
4756 // Non-PIC/GOT tail calls are supported.
4757 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4758 return true;
4759
4760 // At the moment we can only do local tail calls (in same module, hidden
4761 // or protected) if we are generating PIC.
4762 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4763 return G->getGlobal()->hasHiddenVisibility()
4764 || G->getGlobal()->hasProtectedVisibility();
4765 }
4766
4767 return false;
4768}
4769
4770/// isCallCompatibleAddress - Return the immediate to use if the specified
4771/// 32-bit value is representable in the immediate field of a BxA instruction.
4772static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4773 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4774 if (!C) return nullptr;
4775
4776 int Addr = C->getZExtValue();
4777 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
4778 SignExtend32<26>(Addr) != Addr)
4779 return nullptr; // Top 6 bits have to be sext of immediate.
4780
4781 return DAG
4782 .getConstant(
4783 (int)C->getZExtValue() >> 2, SDLoc(Op),
4784 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4785 .getNode();
4786}
4787
4788namespace {
4789
4790struct TailCallArgumentInfo {
4791 SDValue Arg;
4792 SDValue FrameIdxOp;
4793 int FrameIdx = 0;
4794
4795 TailCallArgumentInfo() = default;
4796};
4797
4798} // end anonymous namespace
4799
4800/// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4801static void StoreTailCallArgumentsToStackSlot(
4802 SelectionDAG &DAG, SDValue Chain,
4803 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4804 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4805 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4806 SDValue Arg = TailCallArgs[i].Arg;
4807 SDValue FIN = TailCallArgs[i].FrameIdxOp;
4808 int FI = TailCallArgs[i].FrameIdx;
4809 // Store relative to framepointer.
4810 MemOpChains.push_back(DAG.getStore(
4811 Chain, dl, Arg, FIN,
4812 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4813 }
4814}
4815
4816/// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4817/// the appropriate stack slot for the tail call optimized function call.
4818static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4819 SDValue OldRetAddr, SDValue OldFP,
4820 int SPDiff, const SDLoc &dl) {
4821 if (SPDiff) {
4822 // Calculate the new stack slot for the return address.
4823 MachineFunction &MF = DAG.getMachineFunction();
4824 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4825 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4826 bool isPPC64 = Subtarget.isPPC64();
4827 int SlotSize = isPPC64 ? 8 : 4;
4828 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4829 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4830 NewRetAddrLoc, true);
4831 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4832 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4833 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4834 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4835 }
4836 return Chain;
4837}
4838
4839/// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4840/// the position of the argument.
4841static void
4842CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4843 SDValue Arg, int SPDiff, unsigned ArgOffset,
4844 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4845 int Offset = ArgOffset + SPDiff;
4846 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4847 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4848 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4849 SDValue FIN = DAG.getFrameIndex(FI, VT);
4850 TailCallArgumentInfo Info;
4851 Info.Arg = Arg;
4852 Info.FrameIdxOp = FIN;
4853 Info.FrameIdx = FI;
4854 TailCallArguments.push_back(Info);
4855}
4856
4857/// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4858/// stack slot. Returns the chain as result and the loaded frame pointers in
4859/// LROpOut/FPOpout. Used when tail calling.
4860SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4861 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4862 SDValue &FPOpOut, const SDLoc &dl) const {
4863 if (SPDiff) {
4864 // Load the LR and FP stack slot for later adjusting.
4865 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4866 LROpOut = getReturnAddrFrameIndex(DAG);
4867 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4868 Chain = SDValue(LROpOut.getNode(), 1);
4869 }
4870 return Chain;
4871}
4872
4873/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4874/// by "Src" to address "Dst" of size "Size". Alignment information is
4875/// specified by the specific parameter attribute. The copy will be passed as
4876/// a byval function parameter.
4877/// Sometimes what we are copying is the end of a larger object, the part that
4878/// does not fit in registers.
4879static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4880 SDValue Chain, ISD::ArgFlagsTy Flags,
4881 SelectionDAG &DAG, const SDLoc &dl) {
4882 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4883 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4884 Flags.getNonZeroByValAlign(), false, false, false,
4885 MachinePointerInfo(), MachinePointerInfo());
4886}
4887
4888/// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4889/// tail calls.
4890static void LowerMemOpCallTo(
4891 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4892 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4893 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4894 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4895 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4896 if (!isTailCall) {
4897 if (isVector) {
4898 SDValue StackPtr;
4899 if (isPPC64)
4900 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4901 else
4902 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4903 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4904 DAG.getConstant(ArgOffset, dl, PtrVT));
4905 }
4906 MemOpChains.push_back(
4907 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4908 // Calculate and remember argument location.
4909 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4910 TailCallArguments);
4911}
4912
4913static void
4914PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4915 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4916 SDValue FPOp,
4917 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4918 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4919 // might overwrite each other in case of tail call optimization.
4920 SmallVector<SDValue, 8> MemOpChains2;
4921 // Do not flag preceding copytoreg stuff together with the following stuff.
4922 InFlag = SDValue();
4923 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4924 MemOpChains2, dl);
4925 if (!MemOpChains2.empty())
4926 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4927
4928 // Store the return address to the appropriate stack slot.
4929 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4930
4931 // Emit callseq_end just before tailcall node.
4932 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4933 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4934 InFlag = Chain.getValue(1);
4935}
4936
4937// Is this global address that of a function that can be called by name? (as
4938// opposed to something that must hold a descriptor for an indirect call).
4939static bool isFunctionGlobalAddress(SDValue Callee) {
4940 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4941 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4942 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4943 return false;
4944
4945 return G->getGlobal()->getValueType()->isFunctionTy();
4946 }
4947
4948 return false;
4949}
4950
4951SDValue PPCTargetLowering::LowerCallResult(
4952 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4953 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4954 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4955 SmallVector<CCValAssign, 16> RVLocs;
4956 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4957 *DAG.getContext());
4958
4959 CCRetInfo.AnalyzeCallResult(
4960 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4961 ? RetCC_PPC_Cold
4962 : RetCC_PPC);
4963
4964 // Copy all of the result registers out of their specified physreg.
4965 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4966 CCValAssign &VA = RVLocs[i];
4967 assert(VA.isRegLoc() && "Can only return in registers!")((VA.isRegLoc() && "Can only return in registers!") ?
static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4967, __PRETTY_FUNCTION__))
;
4968
4969 SDValue Val;
4970
4971 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
4972 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4973 InFlag);
4974 Chain = Lo.getValue(1);
4975 InFlag = Lo.getValue(2);
4976 VA = RVLocs[++i]; // skip ahead to next loc
4977 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4978 InFlag);
4979 Chain = Hi.getValue(1);
4980 InFlag = Hi.getValue(2);
4981 if (!Subtarget.isLittleEndian())
4982 std::swap (Lo, Hi);
4983 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
4984 } else {
4985 Val = DAG.getCopyFromReg(Chain, dl,
4986 VA.getLocReg(), VA.getLocVT(), InFlag);
4987 Chain = Val.getValue(1);
4988 InFlag = Val.getValue(2);
4989 }
4990
4991 switch (VA.getLocInfo()) {
4992 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4992)
;
4993 case CCValAssign::Full: break;
4994 case CCValAssign::AExt:
4995 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4996 break;
4997 case CCValAssign::ZExt:
4998 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4999 DAG.getValueType(VA.getValVT()));
5000 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5001 break;
5002 case CCValAssign::SExt:
5003 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5004 DAG.getValueType(VA.getValVT()));
5005 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5006 break;
5007 }
5008
5009 InVals.push_back(Val);
5010 }
5011
5012 return Chain;
5013}
5014
5015static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5016 const PPCSubtarget &Subtarget, bool isPatchPoint) {
5017 // PatchPoint calls are not indirect.
5018 if (isPatchPoint)
5019 return false;
5020
5021 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5022 return false;
5023
5024 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5025 // becuase the immediate function pointer points to a descriptor instead of
5026 // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5027 // pointer immediate points to the global entry point, while the BLA would
5028 // need to jump to the local entry point (see rL211174).
5029 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5030 isBLACompatibleAddress(Callee, DAG))
5031 return false;
5032
5033 return true;
5034}
5035
5036static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5037 const Function &Caller,
5038 const SDValue &Callee,
5039 const PPCSubtarget &Subtarget,
5040 const TargetMachine &TM) {
5041 if (CFlags.IsTailCall)
5042 return PPCISD::TC_RETURN;
5043
5044 // This is a call through a function pointer.
5045 if (CFlags.IsIndirect) {
5046 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5047 // indirect calls. The save of the caller's TOC pointer to the stack will be
5048 // inserted into the DAG as part of call lowering. The restore of the TOC
5049 // pointer is modeled by using a pseudo instruction for the call opcode that
5050 // represents the 2 instruction sequence of an indirect branch and link,
5051 // immediately followed by a load of the TOC pointer from the the stack save
5052 // slot into gpr2.
5053 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5054 return PPCISD::BCTRL_LOAD_TOC;
5055
5056 // An indirect call that does not need a TOC restore.
5057 return PPCISD::BCTRL;
5058 }
5059
5060 // The ABIs that maintain a TOC pointer accross calls need to have a nop
5061 // immediately following the call instruction if the caller and callee may
5062 // have different TOC bases. At link time if the linker determines the calls
5063 // may not share a TOC base, the call is redirected to a trampoline inserted
5064 // by the linker. The trampoline will (among other things) save the callers
5065 // TOC pointer at an ABI designated offset in the linkage area and the linker
5066 // will rewrite the nop to be a load of the TOC pointer from the linkage area
5067 // into gpr2.
5068 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5069 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5070 : PPCISD::CALL_NOP;
5071
5072 return PPCISD::CALL;
5073}
5074
5075static bool isValidAIXExternalSymSDNode(StringRef SymName) {
5076 return StringSwitch<bool>(SymName)
5077 .Cases("__divdi3", "__fixunsdfdi", "__floatundidf", "__floatundisf",
5078 "__moddi3", "__udivdi3", "__umoddi3", true)
5079 .Cases("ceil", "floor", "memcpy", "memmove", "memset", "round", true)
5080 .Default(false);
5081}
5082
5083static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5084 const SDLoc &dl, const PPCSubtarget &Subtarget) {
5085 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5086 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5087 return SDValue(Dest, 0);
5088
5089 // Returns true if the callee is local, and false otherwise.
5090 auto isLocalCallee = [&]() {
5091 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5092 const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5093 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5094
5095 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5096 !dyn_cast_or_null<GlobalIFunc>(GV);
5097 };
5098
5099 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in
5100 // a static relocation model causes some versions of GNU LD (2.17.50, at
5101 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5102 // built with secure-PLT.
5103 bool UsePlt =
5104 Subtarget.is32BitELFABI() && !isLocalCallee() &&
5105 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5106
5107 // On AIX, direct function calls reference the symbol for the function's
5108 // entry point, which is named by prepending a "." before the function's
5109 // C-linkage name.
5110 const auto getAIXFuncEntryPointSymbolSDNode =
5111 [&](StringRef FuncName, bool IsDeclaration,
5112 const XCOFF::StorageClass &SC) {
5113 auto &Context = DAG.getMachineFunction().getMMI().getContext();
5114
5115 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5116 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5117
5118 if (IsDeclaration && !S->hasContainingCsect()) {
5119 // On AIX, an undefined symbol needs to be associated with a
5120 // MCSectionXCOFF to get the correct storage mapping class.
5121 // In this case, XCOFF::XMC_PR.
5122 MCSectionXCOFF *Sec = Context.getXCOFFSection(
5123 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5124 SectionKind::getMetadata());
5125 S->setContainingCsect(Sec);
5126 }
5127
5128 MVT PtrVT =
5129 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5130 return DAG.getMCSymbol(S, PtrVT);
5131 };
5132
5133 if (isFunctionGlobalAddress(Callee)) {
5134 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5135 const GlobalValue *GV = G->getGlobal();
5136
5137 if (!Subtarget.isAIXABI())
5138 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5139 UsePlt ? PPCII::MO_PLT : 0);
5140
5141 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.")((!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."
) ? static_cast<void> (0) : __assert_fail ("!isa<GlobalIFunc>(GV) && \"IFunc is not supported on AIX.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5141, __PRETTY_FUNCTION__))
;
5142 const GlobalObject *GO = cast<GlobalObject>(GV);
5143 const XCOFF::StorageClass SC =
5144 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5145 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5146 SC);
5147 }
5148
5149 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5150 const char *SymName = S->getSymbol();
5151 if (!Subtarget.isAIXABI())
5152 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5153 UsePlt ? PPCII::MO_PLT : 0);
5154
5155 // If there exists a user-declared function whose name is the same as the
5156 // ExternalSymbol's, then we pick up the user-declared version.
5157 const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5158 if (const Function *F =
5159 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5160 const XCOFF::StorageClass SC =
5161 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5162 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5163 SC);
5164 }
5165
5166 // TODO: Remove this when the support for ExternalSymbolSDNode is complete.
5167 if (isValidAIXExternalSymSDNode(SymName)) {
5168 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5169 }
5170
5171 report_fatal_error("Unexpected ExternalSymbolSDNode: " + Twine(SymName));
5172 }
5173
5174 // No transformation needed.
5175 assert(Callee.getNode() && "What no callee?")((Callee.getNode() && "What no callee?") ? static_cast
<void> (0) : __assert_fail ("Callee.getNode() && \"What no callee?\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5175, __PRETTY_FUNCTION__))
;
5176 return Callee;
5177}
5178
5179static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5180 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&((CallSeqStart.getOpcode() == ISD::CALLSEQ_START && "Expected a CALLSEQ_STARTSDNode."
) ? static_cast<void> (0) : __assert_fail ("CallSeqStart.getOpcode() == ISD::CALLSEQ_START && \"Expected a CALLSEQ_STARTSDNode.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5181, __PRETTY_FUNCTION__))
5181 "Expected a CALLSEQ_STARTSDNode.")((CallSeqStart.getOpcode() == ISD::CALLSEQ_START && "Expected a CALLSEQ_STARTSDNode."
) ? static_cast<void> (0) : __assert_fail ("CallSeqStart.getOpcode() == ISD::CALLSEQ_START && \"Expected a CALLSEQ_STARTSDNode.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5181, __PRETTY_FUNCTION__))
;
5182
5183 // The last operand is the chain, except when the node has glue. If the node
5184 // has glue, then the last operand is the glue, and the chain is the second
5185 // last operand.
5186 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5187 if (LastValue.getValueType() != MVT::Glue)
5188 return LastValue;
5189
5190 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5191}
5192
5193// Creates the node that moves a functions address into the count register
5194// to prepare for an indirect call instruction.
5195static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5196 SDValue &Glue, SDValue &Chain,
5197 const SDLoc &dl) {
5198 SDValue MTCTROps[] = {Chain, Callee, Glue};
5199 EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5200 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5201 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5202 // The glue is the second value produced.
5203 Glue = Chain.getValue(1);
5204}
5205
5206static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5207 SDValue &Glue, SDValue &Chain,
5208 SDValue CallSeqStart,
5209 ImmutableCallSite CS, const SDLoc &dl,
5210 bool hasNest,
5211 const PPCSubtarget &Subtarget) {
5212 // Function pointers in the 64-bit SVR4 ABI do not point to the function
5213 // entry point, but to the function descriptor (the function entry point
5214 // address is part of the function descriptor though).
5215 // The function descriptor is a three doubleword structure with the
5216 // following fields: function entry point, TOC base address and
5217 // environment pointer.
5218 // Thus for a call through a function pointer, the following actions need
5219 // to be performed:
5220 // 1. Save the TOC of the caller in the TOC save area of its stack
5221 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5222 // 2. Load the address of the function entry point from the function
5223 // descriptor.
5224 // 3. Load the TOC of the callee from the function descriptor into r2.
5225 // 4. Load the environment pointer from the function descriptor into
5226 // r11.
5227 // 5. Branch to the function entry point address.
5228 // 6. On return of the callee, the TOC of the caller needs to be
5229 // restored (this is done in FinishCall()).
5230 //
5231 // The loads are scheduled at the beginning of the call sequence, and the
5232 // register copies are flagged together to ensure that no other
5233 // operations can be scheduled in between. E.g. without flagging the
5234 // copies together, a TOC access in the caller could be scheduled between
5235 // the assignment of the callee TOC and the branch to the callee, which leads
5236 // to incorrect code.
5237
5238 // Start by loading the function address from the descriptor.
5239 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5240 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5241 ? (MachineMemOperand::MODereferenceable |
5242 MachineMemOperand::MOInvariant)
5243 : MachineMemOperand::MONone;
5244
5245 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5246
5247 // Registers used in building the DAG.
5248 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5249 const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5250
5251 // Offsets of descriptor members.
5252 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5253 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5254
5255 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5256 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5257
5258 // One load for the functions entry point address.
5259 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5260 Alignment, MMOFlags);
5261
5262 // One for loading the TOC anchor for the module that contains the called
5263 // function.
5264 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5265 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5266 SDValue TOCPtr =
5267 DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5268 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5269
5270 // One for loading the environment pointer.
5271 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5272 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5273 SDValue LoadEnvPtr =
5274 DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5275 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5276
5277
5278 // Then copy the newly loaded TOC anchor to the TOC pointer.
5279 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5280 Chain = TOCVal.getValue(0);
5281 Glue = TOCVal.getValue(1);
5282
5283 // If the function call has an explicit 'nest' parameter, it takes the
5284 // place of the environment pointer.
5285 assert((!hasNest || !Subtarget.isAIXABI()) &&(((!hasNest || !Subtarget.isAIXABI()) && "Nest parameter is not supported on AIX."
) ? static_cast<void> (0) : __assert_fail ("(!hasNest || !Subtarget.isAIXABI()) && \"Nest parameter is not supported on AIX.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5286, __PRETTY_FUNCTION__))
5286 "Nest parameter is not supported on AIX.")(((!hasNest || !Subtarget.isAIXABI()) && "Nest parameter is not supported on AIX."
) ? static_cast<void> (0) : __assert_fail ("(!hasNest || !Subtarget.isAIXABI()) && \"Nest parameter is not supported on AIX.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5286, __PRETTY_FUNCTION__))
;
5287 if (!hasNest) {
5288 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5289 Chain = EnvVal.getValue(0);
5290 Glue = EnvVal.getValue(1);
5291 }
5292
5293 // The rest of the indirect call sequence is the same as the non-descriptor
5294 // DAG.
5295 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5296}
5297
5298static void
5299buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5300 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5301 SelectionDAG &DAG,
5302 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5303 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5304 const PPCSubtarget &Subtarget) {
5305 const bool IsPPC64 = Subtarget.isPPC64();
5306 // MVT for a general purpose register.
5307 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5308
5309 // First operand is always the chain.
5310 Ops.push_back(Chain);
5311
5312 // If it's a direct call pass the callee as the second operand.
5313 if (!CFlags.IsIndirect)
5314 Ops.push_back(Callee);
5315 else {
5316 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.")((!CFlags.IsPatchPoint && "Patch point calls are not indirect."
) ? static_cast<void> (0) : __assert_fail ("!CFlags.IsPatchPoint && \"Patch point calls are not indirect.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5316, __PRETTY_FUNCTION__))
;
5317
5318 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5319 // on the stack (this would have been done in `LowerCall_64SVR4` or
5320 // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5321 // represents both the indirect branch and a load that restores the TOC
5322 // pointer from the linkage area. The operand for the TOC restore is an add
5323 // of the TOC save offset to the stack pointer. This must be the second
5324 // operand: after the chain input but before any other variadic arguments.
5325 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5326 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5327
5328 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5329 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5330 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5331 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5332 Ops.push_back(AddTOC);
5333 }
5334
5335 // Add the register used for the environment pointer.
5336 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5337 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5338 RegVT));
5339
5340
5341 // Add CTR register as callee so a bctr can be emitted later.
5342 if (CFlags.IsTailCall)
5343 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5344 }
5345
5346 // If this is a tail call add stack pointer delta.
5347 if (CFlags.IsTailCall)
5348 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5349
5350 // Add argument registers to the end of the list so that they are known live
5351 // into the call.
5352 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5353 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5354 RegsToPass[i].second.getValueType()));
5355
5356 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5357 // no way to mark dependencies as implicit here.
5358 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5359 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5360 !CFlags.IsPatchPoint)
5361 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5362
5363 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5364 if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5365 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5366
5367 // Add a register mask operand representing the call-preserved registers.
5368 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5369 const uint32_t *Mask =
5370 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5371 assert(Mask && "Missing call preserved mask for calling convention")((Mask && "Missing call preserved mask for calling convention"
) ? static_cast<void> (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5371, __PRETTY_FUNCTION__))
;
5372 Ops.push_back(DAG.getRegisterMask(Mask));
5373
5374 // If the glue is valid, it is the last operand.
5375 if (Glue.getNode())
5376 Ops.push_back(Glue);
5377}
5378
5379SDValue PPCTargetLowering::FinishCall(
5380 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5381 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5382 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5383 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5384 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5385
5386 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI())
5387 setUsesTOCBasePtr(DAG);
5388
5389 unsigned CallOpc =
5390 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5391 Subtarget, DAG.getTarget());
5392
5393 if (!CFlags.IsIndirect)
5394 Callee = transformCallee(Callee, DAG, dl, Subtarget);
5395 else if (Subtarget.usesFunctionDescriptors())
5396 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS,
5397 dl, CFlags.HasNest, Subtarget);
5398 else
5399 prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5400
5401 // Build the operand list for the call instruction.
5402 SmallVector<SDValue, 8> Ops;
5403 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5404 SPDiff, Subtarget);
5405
5406 // Emit tail call.
5407 if (CFlags.IsTailCall) {
5408 assert(((Callee.getOpcode() == ISD::Register &&((((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode
>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() ==
ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress
|| isa<ConstantSDNode>(Callee)) && "Expecting a global address, external symbol, absolute value or "
"register") ? static_cast<void> (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee)) && \"Expecting a global address, external symbol, absolute value or \" \"register\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5414, __PRETTY_FUNCTION__))
5409 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||((((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode
>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() ==
ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress
|| isa<ConstantSDNode>(Callee)) && "Expecting a global address, external symbol, absolute value or "
"register") ? static_cast<void> (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee)) && \"Expecting a global address, external symbol, absolute value or \" \"register\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5414, __PRETTY_FUNCTION__))
5410 Callee.getOpcode() == ISD::TargetExternalSymbol ||((((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode
>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() ==
ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress
|| isa<ConstantSDNode>(Callee)) && "Expecting a global address, external symbol, absolute value or "
"register") ? static_cast<void> (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee)) && \"Expecting a global address, external symbol, absolute value or \" \"register\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5414, __PRETTY_FUNCTION__))
5411 Callee.getOpcode() == ISD::TargetGlobalAddress ||((((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode
>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() ==
ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress
|| isa<ConstantSDNode>(Callee)) && "Expecting a global address, external symbol, absolute value or "
"register") ? static_cast<void> (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee)) && \"Expecting a global address, external symbol, absolute value or \" \"register\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5414, __PRETTY_FUNCTION__))
5412 isa<ConstantSDNode>(Callee)) &&((((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode
>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() ==
ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress
|| isa<ConstantSDNode>(Callee)) && "Expecting a global address, external symbol, absolute value or "
"register") ? static_cast<void> (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee)) && \"Expecting a global address, external symbol, absolute value or \" \"register\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5414, __PRETTY_FUNCTION__))
5413 "Expecting a global address, external symbol, absolute value or "((((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode
>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() ==
ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress
|| isa<ConstantSDNode>(Callee)) && "Expecting a global address, external symbol, absolute value or "
"register") ? static_cast<void> (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee)) && \"Expecting a global address, external symbol, absolute value or \" \"register\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5414, __PRETTY_FUNCTION__))
5414 "register")((((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode
>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() ==
ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress
|| isa<ConstantSDNode>(Callee)) && "Expecting a global address, external symbol, absolute value or "
"register") ? static_cast<void> (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee)) && \"Expecting a global address, external symbol, absolute value or \" \"register\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5414, __PRETTY_FUNCTION__))
;
5415 assert(CallOpc == PPCISD::TC_RETURN &&((CallOpc == PPCISD::TC_RETURN && "Unexpected call opcode for a tail call."
) ? static_cast<void> (0) : __assert_fail ("CallOpc == PPCISD::TC_RETURN && \"Unexpected call opcode for a tail call.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5416, __PRETTY_FUNCTION__))
5416 "Unexpected call opcode for a tail call.")((CallOpc == PPCISD::TC_RETURN && "Unexpected call opcode for a tail call."
) ? static_cast<void> (0) : __assert_fail ("CallOpc == PPCISD::TC_RETURN && \"Unexpected call opcode for a tail call.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5416, __PRETTY_FUNCTION__))
;
5417 DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5418 return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5419 }
5420
5421 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5422 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5423 Glue = Chain.getValue(1);
5424
5425 // When performing tail call optimization the callee pops its arguments off
5426 // the stack. Account for this here so these bytes can be pushed back on in
5427 // PPCFrameLowering::eliminateCallFramePseudoInstr.
5428 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5429 getTargetMachine().Options.GuaranteedTailCallOpt)
5430 ? NumBytes
5431 : 0;
5432
5433 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5434 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5435 Glue, dl);
5436 Glue = Chain.getValue(1);
5437
5438 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5439 DAG, InVals);
5440}
5441
5442SDValue
5443PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5444 SmallVectorImpl<SDValue> &InVals) const {
5445 SelectionDAG &DAG = CLI.DAG;
5446 SDLoc &dl = CLI.DL;
5447 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5448 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
5449 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
5450 SDValue Chain = CLI.Chain;
5451 SDValue Callee = CLI.Callee;
5452 bool &isTailCall = CLI.IsTailCall;
5453 CallingConv::ID CallConv = CLI.CallConv;
5454 bool isVarArg = CLI.IsVarArg;
5455 bool isPatchPoint = CLI.IsPatchPoint;
5456 ImmutableCallSite CS = CLI.CS;
5457
5458 if (isTailCall) {
5459 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5460 isTailCall = false;
5461 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5462 isTailCall =
5463 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5464 isVarArg, Outs, Ins, DAG);
5465 else
5466 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5467 Ins, DAG);
5468 if (isTailCall) {
5469 ++NumTailCalls;
5470 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5471 ++NumSiblingCalls;
5472
5473 assert(isa<GlobalAddressSDNode>(Callee) &&((isa<GlobalAddressSDNode>(Callee) && "Callee should be an llvm::Function object."
) ? static_cast<void> (0) : __assert_fail ("isa<GlobalAddressSDNode>(Callee) && \"Callee should be an llvm::Function object.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5474, __PRETTY_FUNCTION__))
5474 "Callee should be an llvm::Function object.")((isa<GlobalAddressSDNode>(Callee) && "Callee should be an llvm::Function object."
) ? static_cast<void> (0) : __assert_fail ("isa<GlobalAddressSDNode>(Callee) && \"Callee should be an llvm::Function object.\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5474, __PRETTY_FUNCTION__))
;
5475 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { const GlobalValue *GV = cast<GlobalAddressSDNode
>(Callee)->getGlobal(); const unsigned Width = 80 - strlen
("TCO caller: ") - strlen(", callee linkage: 0, 0"); dbgs() <<
"TCO caller: " << left_justify(DAG.getMachineFunction(
).getName(), Width) << ", callee linkage: " << GV
->getVisibility() << ", " << GV->getLinkage
() << "\n"; } } while (false)
5476 const GlobalValue *GV =do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { const GlobalValue *GV = cast<GlobalAddressSDNode
>(Callee)->getGlobal(); const unsigned Width = 80 - strlen
("TCO caller: ") - strlen(", callee linkage: 0, 0"); dbgs() <<
"TCO caller: " << left_justify(DAG.getMachineFunction(
).getName(), Width) << ", callee linkage: " << GV
->getVisibility() << ", " << GV->getLinkage
() << "\n"; } } while (false)
5477 cast<GlobalAddressSDNode>(Callee)->getGlobal();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { const GlobalValue *GV = cast<GlobalAddressSDNode
>(Callee)->getGlobal(); const unsigned Width = 80 - strlen
("TCO caller: ") - strlen(", callee linkage: 0, 0"); dbgs() <<
"TCO caller: " << left_justify(DAG.getMachineFunction(
).getName(), Width) << ", callee linkage: " << GV
->getVisibility() << ", " << GV->getLinkage
() << "\n"; } } while (false)
5478 const unsigned Width =do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { const GlobalValue *GV = cast<GlobalAddressSDNode
>(Callee)->getGlobal(); const unsigned Width = 80 - strlen
("TCO caller: ") - strlen(", callee linkage: 0, 0"); dbgs() <<
"TCO caller: " << left_justify(DAG.getMachineFunction(
).getName(), Width) << ", callee linkage: " << GV
->getVisibility() << ", " << GV->getLinkage
() << "\n"; } } while (false)
5479 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { const GlobalValue *GV = cast<GlobalAddressSDNode
>(Callee)->getGlobal(); const unsigned Width = 80 - strlen
("TCO caller: ") - strlen(", callee linkage: 0, 0"); dbgs() <<
"TCO caller: " << left_justify(DAG.getMachineFunction(
).getName(), Width) << ", callee linkage: " << GV
->getVisibility() << ", " << GV->getLinkage
() << "\n"; } } while (false)
5480 dbgs() << "TCO caller: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { const GlobalValue *GV = cast<GlobalAddressSDNode
>(Callee)->getGlobal(); const unsigned Width = 80 - strlen
("TCO caller: ") - strlen(", callee linkage: 0, 0"); dbgs() <<
"TCO caller: " << left_justify(DAG.getMachineFunction(
).getName(), Width) << ", callee linkage: " << GV
->getVisibility() << ", " << GV->getLinkage
() << "\n"; } } while (false)
5481 << left_justify(DAG.getMachineFunction().getName(), Width)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { const GlobalValue *GV = cast<GlobalAddressSDNode
>(Callee)->getGlobal(); const unsigned Width = 80 - strlen
("TCO caller: ") - strlen(", callee linkage: 0, 0"); dbgs() <<
"TCO caller: " << left_justify(DAG.getMachineFunction(
).getName(), Width) << ", callee linkage: " << GV
->getVisibility() << ", " << GV->getLinkage
() << "\n"; } } while (false)
5482 << ", callee linkage: " << GV->getVisibility() << ", "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { const GlobalValue *GV = cast<GlobalAddressSDNode
>(Callee)->getGlobal(); const unsigned Width = 80 - strlen
("TCO caller: ") - strlen(", callee linkage: 0, 0"); dbgs() <<
"TCO caller: " << left_justify(DAG.getMachineFunction(
).getName(), Width) << ", callee linkage: " << GV
->getVisibility() << ", " << GV->getLinkage
() << "\n"; } } while (false)
5483 << GV->getLinkage() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { const GlobalValue *GV = cast<GlobalAddressSDNode
>(Callee)->getGlobal(); const unsigned Width = 80 - strlen
("TCO caller: ") - strlen(", callee linkage: 0, 0"); dbgs() <<
"TCO caller: " << left_justify(DAG.getMachineFunction(
).getName(), Width) << ", callee linkage: " << GV
->getVisibility() << ", " << GV->getLinkage
() << "\n"; } } while (false)
;
5484 }
5485 }
5486
5487 if (!isTailCall && CS && CS.isMustTailCall())
5488 report_fatal_error("failed to perform tail call elimination on a call "
5489 "site marked musttail");
5490
5491 // When long calls (i.e. indirect calls) are always used, calls are always
5492 // made via function pointer. If we have a function name, first translate it
5493 // into a pointer.
5494 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5495 !isTailCall)
5496 Callee = LowerGlobalAddress(Callee, DAG);
5497
5498 CallFlags CFlags(
5499 CallConv, isTailCall, isVarArg, isPatchPoint,
5500 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5501 // hasNest
5502 Subtarget.is64BitELFABI() &&
5503 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }));
5504
5505 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5506 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5507 InVals, CS);
5508
5509 if (Subtarget.isSVR4ABI())
5510 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5511 InVals, CS);
5512
5513 if (Subtarget.isAIXABI())
5514 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5515 InVals, CS);
5516
5517 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5518 InVals, CS);
5519}
5520
5521SDValue PPCTargetLowering::LowerCall_32SVR4(
5522 SDValue Chain, SDValue Callee, CallFlags CFlags,
5523 const SmallVectorImpl<ISD::OutputArg> &Outs,
5524 const SmallVectorImpl<SDValue> &OutVals,
5525 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5526 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5527 ImmutableCallSite CS) const {
5528 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5529 // of the 32-bit SVR4 ABI stack frame layout.
5530
5531 const CallingConv::ID CallConv = CFlags.CallConv;
5532 const bool IsVarArg = CFlags.IsVarArg;
5533 const bool IsTailCall = CFlags.IsTailCall;
5534
5535 assert((CallConv == CallingConv::C ||(((CallConv == CallingConv::C || CallConv == CallingConv::Cold
|| CallConv == CallingConv::Fast) && "Unknown calling convention!"
) ? static_cast<void> (0) : __assert_fail ("(CallConv == CallingConv::C || CallConv == CallingConv::Cold || CallConv == CallingConv::Fast) && \"Unknown calling convention!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5537, __PRETTY_FUNCTION__))
5536 CallConv == CallingConv::Cold ||(((CallConv == CallingConv::C || CallConv == CallingConv::Cold
|| CallConv == CallingConv::Fast) && "Unknown calling convention!"
) ? static_cast<void> (0) : __assert_fail ("(CallConv == CallingConv::C || CallConv == CallingConv::Cold || CallConv == CallingConv::Fast) && \"Unknown calling convention!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5537, __PRETTY_FUNCTION__))
5537 CallConv == CallingConv::Fast) && "Unknown calling convention!")(((CallConv == CallingConv::C || CallConv == CallingConv::Cold
|| CallConv == CallingConv::Fast) && "Unknown calling convention!"
) ? static_cast<void> (0) : __assert_fail ("(CallConv == CallingConv::C || CallConv == CallingConv::Cold || CallConv == CallingConv::Fast) && \"Unknown calling convention!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5537, __PRETTY_FUNCTION__))
;
5538
5539 unsigned PtrByteSize = 4;
5540
5541 MachineFunction &MF = DAG.getMachineFunction();
5542
5543 // Mark this function as potentially containing a function that contains a
5544 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5545 // and restoring the callers stack pointer in this functions epilog. This is
5546 // done because by tail calling the called function might overwrite the value
5547 // in this function's (MF) stack pointer stack slot 0(SP).
5548 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5549 CallConv == CallingConv::Fast)
5550 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5551
5552 // Count how many bytes are to be pushed on the stack, including the linkage
5553 // area, parameter list area and the part of the local variable space which
5554 // contains copies of aggregates which are passed by value.
5555
5556 // Assign locations to all of the outgoing arguments.
5557 SmallVector<CCValAssign, 16> ArgLocs;
5558 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5559
5560 // Reserve space for the linkage area on the stack.
5561 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5562 PtrByteSize);
5563 if (useSoftFloat())
5564 CCInfo.PreAnalyzeCallOperands(Outs);
5565
5566 if (IsVarArg) {
5567 // Handle fixed and variable vector arguments differently.
5568 // Fixed vector arguments go into registers as long as registers are
5569 // available. Variable vector arguments always go into memory.
5570 unsigned NumArgs = Outs.size();
5571
5572 for (unsigned i = 0; i != NumArgs; ++i) {
5573 MVT ArgVT = Outs[i].VT;
5574 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5575 bool Result;
5576
5577 if (Outs[i].IsFixed) {
5578 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5579 CCInfo);
5580 } else {
5581 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5582 ArgFlags, CCInfo);
5583 }
5584
5585 if (Result) {
5586#ifndef NDEBUG
5587 errs() << "Call operand #" << i << " has unhandled type "
5588 << EVT(ArgVT).getEVTString() << "\n";
5589#endif
5590 llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5590)
;
5591 }
5592 }
5593 } else {
5594 // All arguments are treated the same.
5595 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5596 }
5597 CCInfo.clearWasPPCF128();
5598
5599 // Assign locations to all of the outgoing aggregate by value arguments.
5600 SmallVector<CCValAssign, 16> ByValArgLocs;
5601 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5602
5603 // Reserve stack space for the allocations in CCInfo.
5604 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5605
5606 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5607
5608 // Size of the linkage area, parameter list area and the part of the local
5609 // space variable where copies of aggregates which are passed by value are
5610 // stored.
5611 unsigned NumBytes = CCByValInfo.getNextStackOffset();
5612
5613 // Calculate by how many bytes the stack has to be adjusted in case of tail
5614 // call optimization.
5615 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5616
5617 // Adjust the stack pointer for the new arguments...
5618 // These operations are automatically eliminated by the prolog/epilog pass
5619 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5620 SDValue CallSeqStart = Chain;
5621
5622 // Load the return address and frame pointer so it can be moved somewhere else
5623 // later.
5624 SDValue LROp, FPOp;
5625 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5626
5627 // Set up a copy of the stack pointer for use loading and storing any
5628 // arguments that may not fit in the registers available for argument
5629 // passing.
5630 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5631
5632 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5633 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5634 SmallVector<SDValue, 8> MemOpChains;
5635
5636 bool seenFloatArg = false;
5637 // Walk the register/memloc assignments, inserting copies/loads.
5638 // i - Tracks the index into the list of registers allocated for the call
5639 // RealArgIdx - Tracks the index into the list of actual function arguments
5640 // j - Tracks the index into the list of byval arguments
5641 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5642 i != e;
5643 ++i, ++RealArgIdx) {
5644 CCValAssign &VA = ArgLocs[i];
5645 SDValue Arg = OutVals[RealArgIdx];
5646 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5647
5648 if (Flags.isByVal()) {
5649 // Argument is an aggregate which is passed by value, thus we need to
5650 // create a copy of it in the local variable space of the current stack
5651 // frame (which is the stack frame of the caller) and pass the address of
5652 // this copy to the callee.
5653 assert((j < ByValArgLocs.size()) && "Index out of bounds!")(((j < ByValArgLocs.size()) && "Index out of bounds!"
) ? static_cast<void> (0) : __assert_fail ("(j < ByValArgLocs.size()) && \"Index out of bounds!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5653, __PRETTY_FUNCTION__))
;
5654 CCValAssign &ByValVA = ByValArgLocs[j++];
5655 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!")(((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"
) ? static_cast<void> (0) : __assert_fail ("(VA.getValNo() == ByValVA.getValNo()) && \"ValNo mismatch!\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5655, __PRETTY_FUNCTION__))
;
5656
5657 // Memory reserved in the local variable space of the callers stack frame.
5658 unsigned LocMemOffset = ByValVA.getLocMemOffset();
5659
5660 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5661 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5662 StackPtr, PtrOff);
5663
5664 // Create a copy of the argument in the local area of the current
5665 // stack frame.
5666 SDValue MemcpyCall =
5667 CreateCopyOfByValArgument(Arg, PtrOff,
5668 CallSeqStart.getNode()->getOperand(0),
5669 Flags, DAG, dl);
5670
5671 // This must go outside the CALLSEQ_START..END.
5672 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5673 SDLoc(MemcpyCall));
5674 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5675 NewCallSeqStart.getNode());
5676 Chain = CallSeqStart = NewCallSeqStart;
5677
5678 // Pass the address of the aggregate copy on the stack either in a
5679 // physical register or in the parameter list area of the current stack
5680 // frame to the callee.
5681 Arg = PtrOff;
5682 }
5683
5684 // When useCRBits() is true, there can be i1 arguments.
5685 // It is because getRegisterType(MVT::i1) => MVT::i1,
5686 // and for other integer types getRegisterType() => MVT::i32.
5687 // Extend i1 and ensure callee will get i32.
5688 if (Arg.getValueType() == MVT::i1)
5689 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5690 dl, MVT::i32, Arg);
5691
5692 if (VA.isRegLoc()) {
5693 seenFloatArg |= VA.getLocVT().isFloatingPoint();
5694 // Put argument in a physical register.
5695 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5696 bool IsLE = Subtarget.isLittleEndian();
5697 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5698 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5699 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5700 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5701 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5702 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5703 SVal.getValue(0)));
5704 } else
5705 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5706 } else {
5707 // Put argument in the parameter list area of the current stack frame.
5708 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5708, __PRETTY_FUNCTION__))
;
5709 unsigned LocMemOffset = VA.getLocMemOffset();
5710
5711 if (!IsTailCall) {
5712 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5713 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5714 StackPtr, PtrOff);
5715
5716 MemOpChains.push_back(
5717 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5718 } else {
5719 // Calculate and remember argument location.
5720 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5721 TailCallArguments);
5722 }
5723 }
5724 }
5725
5726 if (!MemOpChains.empty())
5727 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5728
5729 // Build a sequence of copy-to-reg nodes chained together with token chain
5730 // and flag operands which copy the outgoing args into the appropriate regs.
5731 SDValue InFlag;
5732 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5733 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5734 RegsToPass[i].second, InFlag);
5735 InFlag = Chain.getValue(1);
5736 }
5737
5738 // Set CR bit 6 to true if this is a vararg call with floating args passed in
5739 // registers.
5740 if (IsVarArg) {
5741 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5742 SDValue Ops[] = { Chain, InFlag };
5743
5744 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5745 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5746
5747 InFlag = Chain.getValue(1);
5748 }
5749
5750 if (IsTailCall)
5751 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5752 TailCallArguments);
5753
5754 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5755 Callee, SPDiff, NumBytes, Ins, InVals, CS);
5756}
5757
5758// Copy an argument into memory, being careful to do this outside the
5759// call sequence for the call to which the argument belongs.
5760SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5761 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5762 SelectionDAG &DAG, const SDLoc &dl) const {
5763 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5764 CallSeqStart.getNode()->getOperand(0),
5765 Flags, DAG, dl);
5766 // The MEMCPY must go outside the CALLSEQ_START..END.
5767 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5768 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5769 SDLoc(MemcpyCall));
5770 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5771 NewCallSeqStart.getNode());
5772 return NewCallSeqStart;
5773}
5774
5775SDValue PPCTargetLowering::LowerCall_64SVR4(
5776 SDValue Chain, SDValue Callee, CallFlags CFlags,
5777 const SmallVectorImpl<ISD::OutputArg> &Outs,
5778 const SmallVectorImpl<SDValue> &OutVals,
5779 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5780 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5781 ImmutableCallSite CS) const {
5782 bool isELFv2ABI = Subtarget.isELFv2ABI();
5783 bool isLittleEndian = Subtarget.isLittleEndian();
5784 unsigned NumOps = Outs.size();
5785 bool IsSibCall = false;
5786 bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5787
5788 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5789 unsigned PtrByteSize = 8;
5790
5791 MachineFunction &MF = DAG.getMachineFunction();
5792
5793 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5794 IsSibCall = true;
5795
5796 // Mark this function as potentially containing a function that contains a
5797 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5798 // and restoring the callers stack pointer in this functions epilog. This is
5799 // done because by tail calling the called function might overwrite the value
5800 // in this function's (MF) stack pointer stack slot 0(SP).
5801 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5802 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5803
5804 assert(!(IsFastCall && CFlags.IsVarArg) &&((!(IsFastCall && CFlags.IsVarArg) && "fastcc not supported on varargs functions"
) ? static_cast<void> (0) : __assert_fail ("!(IsFastCall && CFlags.IsVarArg) && \"fastcc not supported on varargs functions\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5805, __PRETTY_FUNCTION__))
5805 "fastcc not supported on varargs functions")((!(IsFastCall && CFlags.IsVarArg) && "fastcc not supported on varargs functions"
) ? static_cast<void> (0) : __assert_fail ("!(IsFastCall && CFlags.IsVarArg) && \"fastcc not supported on varargs functions\""
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5805, __PRETTY_FUNCTION__))
;
5806
5807 // Count how many bytes are to be pushed on the stack, including the linkage
5808 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
5809 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5810 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5811 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5812 unsigned NumBytes = LinkageSize;
5813 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5814 unsigned &QFPR_idx = FPR_idx;
5815
5816 static const MCPhysReg GPR[] = {
5817 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5818 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5819 };
5820 static const MCPhysReg VR[] = {
5821 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5822 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5823 };
5824
5825 const unsigned NumGPRs = array_lengthof(GPR);
5826 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5827 const unsigned NumVRs = array_lengthof(VR);
5828 const unsigned NumQFPRs = NumFPRs;
5829
5830 // On ELFv2, we can avoid allocating the parameter area if all the arguments
5831 // can be passed to the callee in registers.
5832 // For the fast calling convention, there is another check below.
5833 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5834 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5835 if (!HasParameterArea) {
5836 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5837 unsigned AvailableFPRs = NumFPRs;
5838 unsigned AvailableVRs = NumVRs;
5839 unsigned NumBytesTmp = NumBytes;
5840 for (unsigned i = 0; i != NumOps; ++i) {
5841 if (Outs[i].Flags.isNest()) continue;
5842 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5843 PtrByteSize, LinkageSize, ParamAreaSize,
5844 NumBytesTmp, AvailableFPRs, AvailableVRs,
5845 Subtarget.hasQPX()))
5846 HasParameterArea = true;
5847 }
5848 }
5849
5850 // When using the fast calling convention, we don't provide backing for
5851 // arguments that will be in registers.
5852 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5853
5854 // Avoid allocating parameter area for fastcc functions if all the arguments
5855 // can be passed in the registers.
5856 if (IsFastCall)
5857 HasParameterArea = false;
5858
5859 // Add up all the space actually used.
5860 for (unsigned i = 0; i != NumOps; ++i) {
5861 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5862 EVT ArgVT = Outs[i].VT;
5863 EVT OrigVT = Outs[i].ArgVT;
5864
5865 if (Flags.isNest())
5866 continue;
5867
5868 if (IsFastCall) {
5869 if (Flags.isByVal()) {
5870 NumGPRsUsed += (Flags.getByValSize()+7)/8;
5871 if (NumGPRsUsed > NumGPRs)
5872 HasParameterArea = true;
5873 } else {
5874 switch (ArgVT.getSimpleVT().SimpleTy) {
5875 default: llvm_unreachable("Unexpected ValueType for argument!")::llvm::llvm_unreachable_internal("Unexpected ValueType for argument!"
, "/build/llvm-toolchain-snapshot-11~++20200226111113+80d7e473e0b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5875)
;
5876 case MVT::i1:
5877 case MVT::i32:
5878 case MVT::i64:
5879 if (++NumGPRsUsed <= NumGPRs)
5880 continue;
5881 break;
5882 case MVT::v4i32:
5883 case MVT::v8i16:
5884 case MVT::v16i8:
5885 case MVT::v2f64:
5886 case MVT::v2i64:
5887 case MVT::v1i128:
5888 case MVT::f128:
5889 if (++NumVRsUsed <= NumVRs)
5890 continue;
5891 break;
5892 case MVT::v4f32:
5893 // When using QPX, this is handled like a FP register, otherwise, it
5894 // is an Altivec register.
5895 if (Subtarget.hasQPX()) {
5896 if (++NumFPRsUsed <= NumFPRs)
5897 continue;
5898 } else {
5899 if (++NumVRsUsed <= NumVRs)
5900 continue;
5901 }
5902 break;
5903 case MVT::f32:
5904 case MVT::f64:
5905 case MVT::v4f64: // QPX
5906 case MVT::v4i1: // QPX
5907 if (++NumFPRsUsed <= NumFPRs)
5908 continue;
5909 break;
5910 }
5911 HasParameterArea = true;
5912 }
5913 }
5914
5915 /* Re