Bug Summary

File:llvm/lib/Target/PowerPC/PPCISelLowering.cpp
Warning:line 16572, 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-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -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/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/lib/Target/PowerPC -I include -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/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-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -O3 -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -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-2022-01-16-232930-107970-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/lib/Target/PowerPC/PPCISelLowering.cpp

/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/lib/Target/PowerPC/PPCISelLowering.cpp

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