Bug Summary

File:build/source/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
Warning:line 16995, column 9
Assigned value is garbage or undefined

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name PPCISelLowering.cpp -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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Target/PowerPC -I /build/source/llvm/lib/Target/PowerPC -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -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-17/lib/clang/17/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 -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1679443490 -O2 -Wno-unused-command-line-argument -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 -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility=hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -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-2023-03-22-005342-16304-1 -x c++ /build/source/llvm/lib/Target/PowerPC/PPCISelLowering.cpp

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