Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -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 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Target/PowerPC -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Target/PowerPC -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7=. -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-06-13-111025-38230-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Target/PowerPC/PPCISelLowering.cpp

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