Bug Summary

File:build/source/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
Warning:line 10052, column 31
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name PPCISelLowering.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Target/PowerPC -I /build/source/llvm/lib/Target/PowerPC -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1683717183 -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility=hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
1//===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the PPCISelLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "PPCISelLowering.h"
14#include "MCTargetDesc/PPCPredicates.h"
15#include "PPC.h"
16#include "PPCCCState.h"
17#include "PPCCallingConv.h"
18#include "PPCFrameLowering.h"
19#include "PPCInstrInfo.h"
20#include "PPCMachineFunctionInfo.h"
21#include "PPCPerfectShuffle.h"
22#include "PPCRegisterInfo.h"
23#include "PPCSubtarget.h"
24#include "PPCTargetMachine.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/ADT/StringSwitch.h"
36#include "llvm/CodeGen/CallingConvLower.h"
37#include "llvm/CodeGen/ISDOpcodes.h"
38#include "llvm/CodeGen/MachineBasicBlock.h"
39#include "llvm/CodeGen/MachineFrameInfo.h"
40#include "llvm/CodeGen/MachineFunction.h"
41#include "llvm/CodeGen/MachineInstr.h"
42#include "llvm/CodeGen/MachineInstrBuilder.h"
43#include "llvm/CodeGen/MachineJumpTableInfo.h"
44#include "llvm/CodeGen/MachineLoopInfo.h"
45#include "llvm/CodeGen/MachineMemOperand.h"
46#include "llvm/CodeGen/MachineModuleInfo.h"
47#include "llvm/CodeGen/MachineOperand.h"
48#include "llvm/CodeGen/MachineRegisterInfo.h"
49#include "llvm/CodeGen/MachineValueType.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/MathExtras.h"
90#include "llvm/Support/raw_ostream.h"
91#include "llvm/Target/TargetMachine.h"
92#include "llvm/Target/TargetOptions.h"
93#include <algorithm>
94#include <cassert>
95#include <cstdint>
96#include <iterator>
97#include <list>
98#include <optional>
99#include <utility>
100#include <vector>
101
102using namespace llvm;
103
104#define DEBUG_TYPE"ppc-lowering" "ppc-lowering"
105
106static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108
109static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111
112static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114
115static cl::opt<bool> DisableSCO("disable-ppc-sco",
116cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117
118static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120
121static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123
124static cl::opt<bool> EnableQuadwordAtomics(
125 "ppc-quadword-atomics",
126 cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
127 cl::Hidden);
128
129static cl::opt<bool>
130 DisablePerfectShuffle("ppc-disable-perfect-shuffle",
131 cl::desc("disable vector permute decomposition"),
132 cl::init(true), cl::Hidden);
133
134cl::opt<bool> DisableAutoPairedVecSt(
135 "disable-auto-paired-vec-st",
136 cl::desc("disable automatically generated 32byte paired vector stores"),
137 cl::init(true), cl::Hidden);
138
139STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"ppc-lowering", "NumTailCalls"
, "Number of tail calls"}
;
140STATISTIC(NumSiblingCalls, "Number of sibling calls")static llvm::Statistic NumSiblingCalls = {"ppc-lowering", "NumSiblingCalls"
, "Number of sibling calls"}
;
141STATISTIC(ShufflesHandledWithVPERM,static llvm::Statistic ShufflesHandledWithVPERM = {"ppc-lowering"
, "ShufflesHandledWithVPERM", "Number of shuffles lowered to a VPERM or XXPERM"
}
142 "Number of shuffles lowered to a VPERM or XXPERM")static llvm::Statistic ShufflesHandledWithVPERM = {"ppc-lowering"
, "ShufflesHandledWithVPERM", "Number of shuffles lowered to a VPERM or XXPERM"
}
;
143STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed")static llvm::Statistic NumDynamicAllocaProbed = {"ppc-lowering"
, "NumDynamicAllocaProbed", "Number of dynamic stack allocation probed"
}
;
144
145static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
146
147static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
148
149static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
150
151// FIXME: Remove this once the bug has been fixed!
152extern cl::opt<bool> ANDIGlueBug;
153
154PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
155 const PPCSubtarget &STI)
156 : TargetLowering(TM), Subtarget(STI) {
157 // Initialize map that relates the PPC addressing modes to the computed flags
158 // of a load/store instruction. The map is used to determine the optimal
159 // addressing mode when selecting load and stores.
160 initializeAddrModeMap();
161 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
162 // arguments are at least 4/8 bytes aligned.
163 bool isPPC64 = Subtarget.isPPC64();
164 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
165
166 // Set up the register classes.
167 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
168 if (!useSoftFloat()) {
169 if (hasSPE()) {
170 addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
171 // EFPU2 APU only supports f32
172 if (!Subtarget.hasEFPU2())
173 addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
174 } else {
175 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
176 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
177 }
178 }
179
180 // Match BITREVERSE to customized fast code sequence in the td file.
181 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
182 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
183
184 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
185 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
186
187 // Custom lower inline assembly to check for special registers.
188 setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
189 setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom);
190
191 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
192 for (MVT VT : MVT::integer_valuetypes()) {
193 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
194 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
195 }
196
197 if (Subtarget.isISA3_0()) {
198 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
199 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
200 setTruncStoreAction(MVT::f64, MVT::f16, Legal);
201 setTruncStoreAction(MVT::f32, MVT::f16, Legal);
202 } else {
203 // No extending loads from f16 or HW conversions back and forth.
204 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
205 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
206 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
207 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
208 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
209 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
210 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
211 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
212 }
213
214 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
215
216 // PowerPC has pre-inc load and store's.
217 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
218 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
219 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
220 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
221 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
222 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
223 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
224 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
225 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
226 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
227 if (!Subtarget.hasSPE()) {
228 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
229 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
230 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
231 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
232 }
233
234 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
235 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
236 for (MVT VT : ScalarIntVTs) {
237 setOperationAction(ISD::ADDC, VT, Legal);
238 setOperationAction(ISD::ADDE, VT, Legal);
239 setOperationAction(ISD::SUBC, VT, Legal);
240 setOperationAction(ISD::SUBE, VT, Legal);
241 }
242
243 if (Subtarget.useCRBits()) {
244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
245
246 if (isPPC64 || Subtarget.hasFPCVT()) {
247 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
248 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
249 isPPC64 ? MVT::i64 : MVT::i32);
250 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
251 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
252 isPPC64 ? MVT::i64 : MVT::i32);
253
254 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
255 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
256 isPPC64 ? MVT::i64 : MVT::i32);
257 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
258 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
259 isPPC64 ? MVT::i64 : MVT::i32);
260
261 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
262 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
263 isPPC64 ? MVT::i64 : MVT::i32);
264 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
265 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
266 isPPC64 ? MVT::i64 : MVT::i32);
267
268 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
269 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
270 isPPC64 ? MVT::i64 : MVT::i32);
271 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
272 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
273 isPPC64 ? MVT::i64 : MVT::i32);
274 } else {
275 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
276 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
277 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
278 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
279 }
280
281 // PowerPC does not support direct load/store of condition registers.
282 setOperationAction(ISD::LOAD, MVT::i1, Custom);
283 setOperationAction(ISD::STORE, MVT::i1, Custom);
284
285 // FIXME: Remove this once the ANDI glue bug is fixed:
286 if (ANDIGlueBug)
287 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
288
289 for (MVT VT : MVT::integer_valuetypes()) {
290 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
291 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
292 setTruncStoreAction(VT, MVT::i1, Expand);
293 }
294
295 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
296 }
297
298 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
299 // PPC (the libcall is not available).
300 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
301 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
302 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
303 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
304
305 // We do not currently implement these libm ops for PowerPC.
306 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
307 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
308 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
309 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
310 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
311 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
312
313 // PowerPC has no SREM/UREM instructions unless we are on P9
314 // On P9 we may use a hardware instruction to compute the remainder.
315 // When the result of both the remainder and the division is required it is
316 // more efficient to compute the remainder from the result of the division
317 // rather than use the remainder instruction. The instructions are legalized
318 // directly because the DivRemPairsPass performs the transformation at the IR
319 // level.
320 if (Subtarget.isISA3_0()) {
321 setOperationAction(ISD::SREM, MVT::i32, Legal);
322 setOperationAction(ISD::UREM, MVT::i32, Legal);
323 setOperationAction(ISD::SREM, MVT::i64, Legal);
324 setOperationAction(ISD::UREM, MVT::i64, Legal);
325 } else {
326 setOperationAction(ISD::SREM, MVT::i32, Expand);
327 setOperationAction(ISD::UREM, MVT::i32, Expand);
328 setOperationAction(ISD::SREM, MVT::i64, Expand);
329 setOperationAction(ISD::UREM, MVT::i64, Expand);
330 }
331
332 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
333 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
334 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
335 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
336 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
337 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
338 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
339 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
340 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
341
342 // Handle constrained floating-point operations of scalar.
343 // TODO: Handle SPE specific operation.
344 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
345 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
346 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
347 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
348 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
349
350 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
351 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
352 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
353 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
354
355 if (!Subtarget.hasSPE()) {
356 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
357 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
358 }
359
360 if (Subtarget.hasVSX()) {
361 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
362 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
363 }
364
365 if (Subtarget.hasFSQRT()) {
366 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
367 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
368 }
369
370 if (Subtarget.hasFPRND()) {
371 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
372 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal);
373 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
374 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
375
376 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
377 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal);
378 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
379 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
380 }
381
382 // We don't support sin/cos/sqrt/fmod/pow
383 setOperationAction(ISD::FSIN , MVT::f64, Expand);
384 setOperationAction(ISD::FCOS , MVT::f64, Expand);
385 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
386 setOperationAction(ISD::FREM , MVT::f64, Expand);
387 setOperationAction(ISD::FPOW , MVT::f64, Expand);
388 setOperationAction(ISD::FSIN , MVT::f32, Expand);
389 setOperationAction(ISD::FCOS , MVT::f32, Expand);
390 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
391 setOperationAction(ISD::FREM , MVT::f32, Expand);
392 setOperationAction(ISD::FPOW , MVT::f32, Expand);
393
394 // MASS transformation for LLVM intrinsics with replicating fast-math flag
395 // to be consistent to PPCGenScalarMASSEntries pass
396 if (TM.getOptLevel() == CodeGenOpt::Aggressive) {
397 setOperationAction(ISD::FSIN , MVT::f64, Custom);
398 setOperationAction(ISD::FCOS , MVT::f64, Custom);
399 setOperationAction(ISD::FPOW , MVT::f64, Custom);
400 setOperationAction(ISD::FLOG, MVT::f64, Custom);
401 setOperationAction(ISD::FLOG10, MVT::f64, Custom);
402 setOperationAction(ISD::FEXP, MVT::f64, Custom);
403 setOperationAction(ISD::FSIN , MVT::f32, Custom);
404 setOperationAction(ISD::FCOS , MVT::f32, Custom);
405 setOperationAction(ISD::FPOW , MVT::f32, Custom);
406 setOperationAction(ISD::FLOG, MVT::f32, Custom);
407 setOperationAction(ISD::FLOG10, MVT::f32, Custom);
408 setOperationAction(ISD::FEXP, MVT::f32, Custom);
409 }
410
411 if (Subtarget.hasSPE()) {
412 setOperationAction(ISD::FMA , MVT::f64, Expand);
413 setOperationAction(ISD::FMA , MVT::f32, Expand);
414 } else {
415 setOperationAction(ISD::FMA , MVT::f64, Legal);
416 setOperationAction(ISD::FMA , MVT::f32, Legal);
417 }
418
419 if (Subtarget.hasSPE())
420 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
421
422 setOperationAction(ISD::GET_ROUNDING, MVT::i32, Custom);
423
424 // If we're enabling GP optimizations, use hardware square root
425 if (!Subtarget.hasFSQRT() &&
426 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
427 Subtarget.hasFRE()))
428 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
429
430 if (!Subtarget.hasFSQRT() &&
431 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
432 Subtarget.hasFRES()))
433 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
434
435 if (Subtarget.hasFCPSGN()) {
436 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
437 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
438 } else {
439 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
440 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
441 }
442
443 if (Subtarget.hasFPRND()) {
444 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
445 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
446 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
447 setOperationAction(ISD::FROUND, MVT::f64, Legal);
448
449 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
450 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
451 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
452 setOperationAction(ISD::FROUND, MVT::f32, Legal);
453 }
454
455 // Prior to P10, PowerPC does not have BSWAP, but we can use vector BSWAP
456 // instruction xxbrd to speed up scalar BSWAP64.
457 if (Subtarget.isISA3_1()) {
458 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
459 setOperationAction(ISD::BSWAP, MVT::i64, Legal);
460 } else {
461 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
462 setOperationAction(
463 ISD::BSWAP, MVT::i64,
464 (Subtarget.hasP9Vector() && Subtarget.isPPC64()) ? Custom : Expand);
465 }
466
467 // CTPOP or CTTZ were introduced in P8/P9 respectively
468 if (Subtarget.isISA3_0()) {
469 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
470 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
471 } else {
472 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
473 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
474 }
475
476 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
477 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
478 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
479 } else {
480 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
481 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
482 }
483
484 // PowerPC does not have ROTR
485 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
486 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
487
488 if (!Subtarget.useCRBits()) {
489 // PowerPC does not have Select
490 setOperationAction(ISD::SELECT, MVT::i32, Expand);
491 setOperationAction(ISD::SELECT, MVT::i64, Expand);
492 setOperationAction(ISD::SELECT, MVT::f32, Expand);
493 setOperationAction(ISD::SELECT, MVT::f64, Expand);
494 }
495
496 // PowerPC wants to turn select_cc of FP into fsel when possible.
497 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
498 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
499
500 // PowerPC wants to optimize integer setcc a bit
501 if (!Subtarget.useCRBits())
502 setOperationAction(ISD::SETCC, MVT::i32, Custom);
503
504 if (Subtarget.hasFPU()) {
505 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
506 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
507 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
508
509 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
510 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
511 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
512 }
513
514 // PowerPC does not have BRCOND which requires SetCC
515 if (!Subtarget.useCRBits())
516 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
517
518 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
519
520 if (Subtarget.hasSPE()) {
521 // SPE has built-in conversions
522 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
523 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
524 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
525 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
526 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
527 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
528
529 // SPE supports signaling compare of f32/f64.
530 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
531 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
532 } else {
533 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
534 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
535 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
536
537 // PowerPC does not have [U|S]INT_TO_FP
538 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
539 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
540 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
541 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
542 }
543
544 if (Subtarget.hasDirectMove() && isPPC64) {
545 setOperationAction(ISD::BITCAST, MVT::f32, Legal);
546 setOperationAction(ISD::BITCAST, MVT::i32, Legal);
547 setOperationAction(ISD::BITCAST, MVT::i64, Legal);
548 setOperationAction(ISD::BITCAST, MVT::f64, Legal);
549 if (TM.Options.UnsafeFPMath) {
550 setOperationAction(ISD::LRINT, MVT::f64, Legal);
551 setOperationAction(ISD::LRINT, MVT::f32, Legal);
552 setOperationAction(ISD::LLRINT, MVT::f64, Legal);
553 setOperationAction(ISD::LLRINT, MVT::f32, Legal);
554 setOperationAction(ISD::LROUND, MVT::f64, Legal);
555 setOperationAction(ISD::LROUND, MVT::f32, Legal);
556 setOperationAction(ISD::LLROUND, MVT::f64, Legal);
557 setOperationAction(ISD::LLROUND, MVT::f32, Legal);
558 }
559 } else {
560 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
561 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
562 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
563 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
564 }
565
566 // We cannot sextinreg(i1). Expand to shifts.
567 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
568
569 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
570 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
571 // support continuation, user-level threading, and etc.. As a result, no
572 // other SjLj exception interfaces are implemented and please don't build
573 // your own exception handling based on them.
574 // LLVM/Clang supports zero-cost DWARF exception handling.
575 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
576 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
577
578 // We want to legalize GlobalAddress and ConstantPool nodes into the
579 // appropriate instructions to materialize the address.
580 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
581 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
582 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
583 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
584 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
585 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
586 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
587 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
588 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
589 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
590
591 // TRAP is legal.
592 setOperationAction(ISD::TRAP, MVT::Other, Legal);
593
594 // TRAMPOLINE is custom lowered.
595 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
596 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
597
598 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
599 setOperationAction(ISD::VASTART , MVT::Other, Custom);
600
601 if (Subtarget.is64BitELFABI()) {
602 // VAARG always uses double-word chunks, so promote anything smaller.
603 setOperationAction(ISD::VAARG, MVT::i1, Promote);
604 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
605 setOperationAction(ISD::VAARG, MVT::i8, Promote);
606 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
607 setOperationAction(ISD::VAARG, MVT::i16, Promote);
608 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
609 setOperationAction(ISD::VAARG, MVT::i32, Promote);
610 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
611 setOperationAction(ISD::VAARG, MVT::Other, Expand);
612 } else if (Subtarget.is32BitELFABI()) {
613 // VAARG is custom lowered with the 32-bit SVR4 ABI.
614 setOperationAction(ISD::VAARG, MVT::Other, Custom);
615 setOperationAction(ISD::VAARG, MVT::i64, Custom);
616 } else
617 setOperationAction(ISD::VAARG, MVT::Other, Expand);
618
619 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
620 if (Subtarget.is32BitELFABI())
621 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
622 else
623 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
624
625 // Use the default implementation.
626 setOperationAction(ISD::VAEND , MVT::Other, Expand);
627 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
628 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
629 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
630 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
631 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
632 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
633 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
634 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
635
636 // We want to custom lower some of our intrinsics.
637 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
638 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
639 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
640 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
641 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom);
642
643 // To handle counter-based loop conditions.
644 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
645
646 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
647 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
648 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
649 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
650
651 // Comparisons that require checking two conditions.
652 if (Subtarget.hasSPE()) {
653 setCondCodeAction(ISD::SETO, MVT::f32, Expand);
654 setCondCodeAction(ISD::SETO, MVT::f64, Expand);
655 setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
656 setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
657 }
658 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
659 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
660 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
661 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
662 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
663 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
664 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
665 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
666 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
667 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
668 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
669 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
670
671 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
672 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
673
674 if (Subtarget.has64BitSupport()) {
675 // They also have instructions for converting between i64 and fp.
676 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
677 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
678 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
679 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
680 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
681 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
682 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
683 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
684 // This is just the low 32 bits of a (signed) fp->i64 conversion.
685 // We cannot do this with Promote because i64 is not a legal type.
686 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
687 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
688
689 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
690 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
691 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
692 }
693 } else {
694 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
695 if (Subtarget.hasSPE()) {
696 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
697 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
698 } else {
699 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
700 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
701 }
702 }
703
704 // With the instructions enabled under FPCVT, we can do everything.
705 if (Subtarget.hasFPCVT()) {
706 if (Subtarget.has64BitSupport()) {
707 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
708 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
709 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
710 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
711 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
712 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
713 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
714 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
715 }
716
717 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
718 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
719 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
720 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
721 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
722 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
723 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
724 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
725 }
726
727 if (Subtarget.use64BitRegs()) {
728 // 64-bit PowerPC implementations can support i64 types directly
729 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
730 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
731 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
732 // 64-bit PowerPC wants to expand i128 shifts itself.
733 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
734 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
735 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
736 } else {
737 // 32-bit PowerPC wants to expand i64 shifts itself.
738 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
739 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
740 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
741 }
742
743 // PowerPC has better expansions for funnel shifts than the generic
744 // TargetLowering::expandFunnelShift.
745 if (Subtarget.has64BitSupport()) {
746 setOperationAction(ISD::FSHL, MVT::i64, Custom);
747 setOperationAction(ISD::FSHR, MVT::i64, Custom);
748 }
749 setOperationAction(ISD::FSHL, MVT::i32, Custom);
750 setOperationAction(ISD::FSHR, MVT::i32, Custom);
751
752 if (Subtarget.hasVSX()) {
753 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
754 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
755 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
756 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
757 }
758
759 if (Subtarget.hasAltivec()) {
760 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
761 setOperationAction(ISD::SADDSAT, VT, Legal);
762 setOperationAction(ISD::SSUBSAT, VT, Legal);
763 setOperationAction(ISD::UADDSAT, VT, Legal);
764 setOperationAction(ISD::USUBSAT, VT, Legal);
765 }
766 // First set operation action for all vector types to expand. Then we
767 // will selectively turn on ones that can be effectively codegen'd.
768 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
769 // add/sub are legal for all supported vector VT's.
770 setOperationAction(ISD::ADD, VT, Legal);
771 setOperationAction(ISD::SUB, VT, Legal);
772
773 // For v2i64, these are only valid with P8Vector. This is corrected after
774 // the loop.
775 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
776 setOperationAction(ISD::SMAX, VT, Legal);
777 setOperationAction(ISD::SMIN, VT, Legal);
778 setOperationAction(ISD::UMAX, VT, Legal);
779 setOperationAction(ISD::UMIN, VT, Legal);
780 }
781 else {
782 setOperationAction(ISD::SMAX, VT, Expand);
783 setOperationAction(ISD::SMIN, VT, Expand);
784 setOperationAction(ISD::UMAX, VT, Expand);
785 setOperationAction(ISD::UMIN, VT, Expand);
786 }
787
788 if (Subtarget.hasVSX()) {
789 setOperationAction(ISD::FMAXNUM, VT, Legal);
790 setOperationAction(ISD::FMINNUM, VT, Legal);
791 }
792
793 // Vector instructions introduced in P8
794 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
795 setOperationAction(ISD::CTPOP, VT, Legal);
796 setOperationAction(ISD::CTLZ, VT, Legal);
797 }
798 else {
799 setOperationAction(ISD::CTPOP, VT, Expand);
800 setOperationAction(ISD::CTLZ, VT, Expand);
801 }
802
803 // Vector instructions introduced in P9
804 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
805 setOperationAction(ISD::CTTZ, VT, Legal);
806 else
807 setOperationAction(ISD::CTTZ, VT, Expand);
808
809 // We promote all shuffles to v16i8.
810 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
811 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
812
813 // We promote all non-typed operations to v4i32.
814 setOperationAction(ISD::AND , VT, Promote);
815 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
816 setOperationAction(ISD::OR , VT, Promote);
817 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
818 setOperationAction(ISD::XOR , VT, Promote);
819 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
820 setOperationAction(ISD::LOAD , VT, Promote);
821 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
822 setOperationAction(ISD::SELECT, VT, Promote);
823 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
824 setOperationAction(ISD::VSELECT, VT, Legal);
825 setOperationAction(ISD::SELECT_CC, VT, Promote);
826 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
827 setOperationAction(ISD::STORE, VT, Promote);
828 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
829
830 // No other operations are legal.
831 setOperationAction(ISD::MUL , VT, Expand);
832 setOperationAction(ISD::SDIV, VT, Expand);
833 setOperationAction(ISD::SREM, VT, Expand);
834 setOperationAction(ISD::UDIV, VT, Expand);
835 setOperationAction(ISD::UREM, VT, Expand);
836 setOperationAction(ISD::FDIV, VT, Expand);
837 setOperationAction(ISD::FREM, VT, Expand);
838 setOperationAction(ISD::FNEG, VT, Expand);
839 setOperationAction(ISD::FSQRT, VT, Expand);
840 setOperationAction(ISD::FLOG, VT, Expand);
841 setOperationAction(ISD::FLOG10, VT, Expand);
842 setOperationAction(ISD::FLOG2, VT, Expand);
843 setOperationAction(ISD::FEXP, VT, Expand);
844 setOperationAction(ISD::FEXP2, VT, Expand);
845 setOperationAction(ISD::FSIN, VT, Expand);
846 setOperationAction(ISD::FCOS, VT, Expand);
847 setOperationAction(ISD::FABS, VT, Expand);
848 setOperationAction(ISD::FFLOOR, VT, Expand);
849 setOperationAction(ISD::FCEIL, VT, Expand);
850 setOperationAction(ISD::FTRUNC, VT, Expand);
851 setOperationAction(ISD::FRINT, VT, Expand);
852 setOperationAction(ISD::FNEARBYINT, VT, Expand);
853 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
854 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
855 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
856 setOperationAction(ISD::MULHU, VT, Expand);
857 setOperationAction(ISD::MULHS, VT, Expand);
858 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
859 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
860 setOperationAction(ISD::UDIVREM, VT, Expand);
861 setOperationAction(ISD::SDIVREM, VT, Expand);
862 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
863 setOperationAction(ISD::FPOW, VT, Expand);
864 setOperationAction(ISD::BSWAP, VT, Expand);
865 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
866 setOperationAction(ISD::ROTL, VT, Expand);
867 setOperationAction(ISD::ROTR, VT, Expand);
868
869 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
870 setTruncStoreAction(VT, InnerVT, Expand);
871 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
872 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
873 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
874 }
875 }
876 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
877 if (!Subtarget.hasP8Vector()) {
878 setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
879 setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
880 setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
881 setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
882 }
883
884 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
885 // with merges, splats, etc.
886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
887
888 // Vector truncates to sub-word integer that fit in an Altivec/VSX register
889 // are cheap, so handle them before they get expanded to scalar.
890 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
891 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
892 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
893 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
894 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
895
896 setOperationAction(ISD::AND , MVT::v4i32, Legal);
897 setOperationAction(ISD::OR , MVT::v4i32, Legal);
898 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
899 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
900 setOperationAction(ISD::SELECT, MVT::v4i32,
901 Subtarget.useCRBits() ? Legal : Expand);
902 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
903 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
904 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
905 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
906 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
907 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
908 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
909 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
910 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
911 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
912 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
913 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
914 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
915
916 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
917 setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
918 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
919 if (Subtarget.hasAltivec())
920 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
921 setOperationAction(ISD::ROTL, VT, Legal);
922 // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
923 if (Subtarget.hasP8Altivec())
924 setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
925
926 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
927 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
928 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
929 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
930
931 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
932 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
933
934 if (Subtarget.hasVSX()) {
935 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
936 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
938 }
939
940 if (Subtarget.hasP8Altivec())
941 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
942 else
943 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
944
945 if (Subtarget.isISA3_1()) {
946 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
947 setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
948 setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
949 setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
950 setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
951 setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
952 setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
953 setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
954 setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
955 setOperationAction(ISD::UREM, MVT::v2i64, Legal);
956 setOperationAction(ISD::SREM, MVT::v2i64, Legal);
957 setOperationAction(ISD::UREM, MVT::v4i32, Legal);
958 setOperationAction(ISD::SREM, MVT::v4i32, Legal);
959 setOperationAction(ISD::UREM, MVT::v1i128, Legal);
960 setOperationAction(ISD::SREM, MVT::v1i128, Legal);
961 setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
962 setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
963 setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
964 }
965
966 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
967 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
968
969 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
970 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
971
972 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
973 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
974 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
975 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
976
977 // Altivec does not contain unordered floating-point compare instructions
978 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
979 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
980 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
981 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
982
983 if (Subtarget.hasVSX()) {
984 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
985 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
986 if (Subtarget.hasP8Vector()) {
987 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
989 }
990 if (Subtarget.hasDirectMove() && isPPC64) {
991 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
992 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
993 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
994 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
999 }
1000 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
1001
1002 // The nearbyint variants are not allowed to raise the inexact exception
1003 // so we can only code-gen them with unsafe math.
1004 if (TM.Options.UnsafeFPMath) {
1005 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1006 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1007 }
1008
1009 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1010 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1011 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1012 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1013 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1014 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
1015 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1016 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1017
1018 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1019 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1020 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1021 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1022 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1023
1024 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
1025 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1026
1027 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
1028 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
1029
1030 // Share the Altivec comparison restrictions.
1031 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
1032 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
1033 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
1034 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
1035
1036 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1037 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1038
1039 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1040
1041 if (Subtarget.hasP8Vector())
1042 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1043
1044 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1045
1046 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1047 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1048 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1049
1050 if (Subtarget.hasP8Altivec()) {
1051 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1052 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1053 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1054
1055 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1056 // SRL, but not for SRA because of the instructions available:
1057 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1058 // doing
1059 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1060 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1061 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1062
1063 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1064 }
1065 else {
1066 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1067 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1068 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1069
1070 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1071
1072 // VSX v2i64 only supports non-arithmetic operations.
1073 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1074 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1075 }
1076
1077 if (Subtarget.isISA3_1())
1078 setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1079 else
1080 setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1081
1082 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1083 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1084 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1085 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1086
1087 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1088
1089 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1090 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1091 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1092 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1093 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1094 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1095 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1096 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1097
1098 // Custom handling for partial vectors of integers converted to
1099 // floating point. We already have optimal handling for v2i32 through
1100 // the DAG combine, so those aren't necessary.
1101 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1102 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1103 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1104 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1105 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1106 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1107 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1108 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1109 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1110 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1111 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1112 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1113 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1114 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1115 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1116 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1117
1118 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1119 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1120 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1121 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1122 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1123 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1124
1125 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1126 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1127
1128 // Handle constrained floating-point operations of vector.
1129 // The predictor is `hasVSX` because altivec instruction has
1130 // no exception but VSX vector instruction has.
1131 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1132 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1133 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1134 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1135 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1136 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1137 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1138 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1139 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1140 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1141 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal);
1142 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1143 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1144
1145 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1146 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1147 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1148 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1149 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1150 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1151 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1152 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1153 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1154 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1155 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal);
1156 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1157 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1158
1159 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1160 addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1161
1162 for (MVT FPT : MVT::fp_valuetypes())
1163 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1164
1165 // Expand the SELECT to SELECT_CC
1166 setOperationAction(ISD::SELECT, MVT::f128, Expand);
1167
1168 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1169 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1170
1171 // No implementation for these ops for PowerPC.
1172 setOperationAction(ISD::FSIN, MVT::f128, Expand);
1173 setOperationAction(ISD::FCOS, MVT::f128, Expand);
1174 setOperationAction(ISD::FPOW, MVT::f128, Expand);
1175 setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1176 setOperationAction(ISD::FREM, MVT::f128, Expand);
1177 }
1178
1179 if (Subtarget.hasP8Altivec()) {
1180 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1181 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1182 }
1183
1184 if (Subtarget.hasP9Vector()) {
1185 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1186 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1187
1188 // Test data class instructions store results in CR bits.
1189 if (Subtarget.useCRBits()) {
1190 setOperationAction(ISD::IS_FPCLASS, MVT::f32, Custom);
1191 setOperationAction(ISD::IS_FPCLASS, MVT::f64, Custom);
1192 setOperationAction(ISD::IS_FPCLASS, MVT::f128, Custom);
1193 }
1194
1195 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1196 // SRL, but not for SRA because of the instructions available:
1197 // VS{RL} and VS{RL}O.
1198 setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1199 setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1200 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1201
1202 setOperationAction(ISD::FADD, MVT::f128, Legal);
1203 setOperationAction(ISD::FSUB, MVT::f128, Legal);
1204 setOperationAction(ISD::FDIV, MVT::f128, Legal);
1205 setOperationAction(ISD::FMUL, MVT::f128, Legal);
1206 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1207
1208 setOperationAction(ISD::FMA, MVT::f128, Legal);
1209 setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1210 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1211 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1212 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1213 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1214 setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1215
1216 setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1217 setOperationAction(ISD::FRINT, MVT::f128, Legal);
1218 setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1219 setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1220 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1221 setOperationAction(ISD::FROUND, MVT::f128, Legal);
1222
1223 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1224 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1225 setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1226
1227 // Handle constrained floating-point operations of fp128
1228 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1229 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1230 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1231 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1232 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1233 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1234 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1235 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1236 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1237 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1238 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1239 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1240 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1241 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1242 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1243 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1244 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1245 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1246 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1247 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1248 } else if (Subtarget.hasVSX()) {
1249 setOperationAction(ISD::LOAD, MVT::f128, Promote);
1250 setOperationAction(ISD::STORE, MVT::f128, Promote);
1251
1252 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1253 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1254
1255 // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1256 // fp_to_uint and int_to_fp.
1257 setOperationAction(ISD::FADD, MVT::f128, LibCall);
1258 setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1259
1260 setOperationAction(ISD::FMUL, MVT::f128, Expand);
1261 setOperationAction(ISD::FDIV, MVT::f128, Expand);
1262 setOperationAction(ISD::FNEG, MVT::f128, Expand);
1263 setOperationAction(ISD::FABS, MVT::f128, Expand);
1264 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1265 setOperationAction(ISD::FMA, MVT::f128, Expand);
1266 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1267
1268 // Expand the fp_extend if the target type is fp128.
1269 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1270 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1271
1272 // Expand the fp_round if the source type is fp128.
1273 for (MVT VT : {MVT::f32, MVT::f64}) {
1274 setOperationAction(ISD::FP_ROUND, VT, Custom);
1275 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1276 }
1277
1278 setOperationAction(ISD::SETCC, MVT::f128, Custom);
1279 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1280 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1281 setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1282
1283 // Lower following f128 select_cc pattern:
1284 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1285 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1286
1287 // We need to handle f128 SELECT_CC with integer result type.
1288 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1289 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1290 }
1291
1292 if (Subtarget.hasP9Altivec()) {
1293 if (Subtarget.isISA3_1()) {
1294 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
1295 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal);
1296 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal);
1297 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
1298 } else {
1299 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1300 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1301 }
1302 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal);
1303 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1304 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1305 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal);
1306 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1307 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1308 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1309
1310 setOperationAction(ISD::ABDU, MVT::v16i8, Legal);
1311 setOperationAction(ISD::ABDU, MVT::v8i16, Legal);
1312 setOperationAction(ISD::ABDU, MVT::v4i32, Legal);
1313 setOperationAction(ISD::ABDS, MVT::v4i32, Legal);
1314 }
1315
1316 if (Subtarget.hasP10Vector()) {
1317 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1318 }
1319 }
1320
1321 if (Subtarget.pairedVectorMemops()) {
1322 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1323 setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1324 setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1325 }
1326 if (Subtarget.hasMMA()) {
1327 if (Subtarget.isISAFuture())
1328 addRegisterClass(MVT::v512i1, &PPC::WACCRCRegClass);
1329 else
1330 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1331 setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1332 setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1333 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1334 }
1335
1336 if (Subtarget.has64BitSupport())
1337 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1338
1339 if (Subtarget.isISA3_1())
1340 setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1341
1342 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1343
1344 if (!isPPC64) {
1345 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
1346 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1347 }
1348
1349 if (shouldInlineQuadwordAtomics()) {
1350 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
1351 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
1352 setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
1353 }
1354
1355 setBooleanContents(ZeroOrOneBooleanContent);
1356
1357 if (Subtarget.hasAltivec()) {
1358 // Altivec instructions set fields to all zeros or all ones.
1359 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1360 }
1361
1362 setLibcallName(RTLIB::MULO_I128, nullptr);
1363 if (!isPPC64) {
1364 // These libcalls are not available in 32-bit.
1365 setLibcallName(RTLIB::SHL_I128, nullptr);
1366 setLibcallName(RTLIB::SRL_I128, nullptr);
1367 setLibcallName(RTLIB::SRA_I128, nullptr);
1368 setLibcallName(RTLIB::MUL_I128, nullptr);
1369 setLibcallName(RTLIB::MULO_I64, nullptr);
1370 }
1371
1372 if (!isPPC64)
1373 setMaxAtomicSizeInBitsSupported(32);
1374 else if (shouldInlineQuadwordAtomics())
1375 setMaxAtomicSizeInBitsSupported(128);
1376 else
1377 setMaxAtomicSizeInBitsSupported(64);
1378
1379 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1380
1381 // We have target-specific dag combine patterns for the following nodes:
1382 setTargetDAGCombine({ISD::ADD, ISD::SHL, ISD::SRA, ISD::SRL, ISD::MUL,
1383 ISD::FMA, ISD::SINT_TO_FP, ISD::BUILD_VECTOR});
1384 if (Subtarget.hasFPCVT())
1385 setTargetDAGCombine(ISD::UINT_TO_FP);
1386 setTargetDAGCombine({ISD::LOAD, ISD::STORE, ISD::BR_CC});
1387 if (Subtarget.useCRBits())
1388 setTargetDAGCombine(ISD::BRCOND);
1389 setTargetDAGCombine({ISD::BSWAP, ISD::INTRINSIC_WO_CHAIN,
1390 ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID});
1391
1392 setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND, ISD::ANY_EXTEND});
1393
1394 setTargetDAGCombine({ISD::TRUNCATE, ISD::VECTOR_SHUFFLE});
1395
1396 if (Subtarget.useCRBits()) {
1397 setTargetDAGCombine({ISD::TRUNCATE, ISD::SETCC, ISD::SELECT_CC});
1398 }
1399
1400 setLibcallName(RTLIB::LOG_F128, "logf128");
1401 setLibcallName(RTLIB::LOG2_F128, "log2f128");
1402 setLibcallName(RTLIB::LOG10_F128, "log10f128");
1403 setLibcallName(RTLIB::EXP_F128, "expf128");
1404 setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1405 setLibcallName(RTLIB::SIN_F128, "sinf128");
1406 setLibcallName(RTLIB::COS_F128, "cosf128");
1407 setLibcallName(RTLIB::POW_F128, "powf128");
1408 setLibcallName(RTLIB::FMIN_F128, "fminf128");
1409 setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1410 setLibcallName(RTLIB::REM_F128, "fmodf128");
1411 setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1412 setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1413 setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1414 setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1415 setLibcallName(RTLIB::ROUND_F128, "roundf128");
1416 setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1417 setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1418 setLibcallName(RTLIB::RINT_F128, "rintf128");
1419 setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1420 setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1421 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1422 setLibcallName(RTLIB::FMA_F128, "fmaf128");
1423
1424 if (Subtarget.isAIXABI()) {
1425 setLibcallName(RTLIB::MEMCPY, isPPC64 ? "___memmove64" : "___memmove");
1426 setLibcallName(RTLIB::MEMMOVE, isPPC64 ? "___memmove64" : "___memmove");
1427 setLibcallName(RTLIB::MEMSET, isPPC64 ? "___memset64" : "___memset");
1428 setLibcallName(RTLIB::BZERO, isPPC64 ? "___bzero64" : "___bzero");
1429 }
1430
1431 // With 32 condition bits, we don't need to sink (and duplicate) compares
1432 // aggressively in CodeGenPrep.
1433 if (Subtarget.useCRBits()) {
1434 setHasMultipleConditionRegisters();
1435 setJumpIsExpensive();
1436 }
1437
1438 setMinFunctionAlignment(Align(4));
1439
1440 switch (Subtarget.getCPUDirective()) {
1441 default: break;
1442 case PPC::DIR_970:
1443 case PPC::DIR_A2:
1444 case PPC::DIR_E500:
1445 case PPC::DIR_E500mc:
1446 case PPC::DIR_E5500:
1447 case PPC::DIR_PWR4:
1448 case PPC::DIR_PWR5:
1449 case PPC::DIR_PWR5X:
1450 case PPC::DIR_PWR6:
1451 case PPC::DIR_PWR6X:
1452 case PPC::DIR_PWR7:
1453 case PPC::DIR_PWR8:
1454 case PPC::DIR_PWR9:
1455 case PPC::DIR_PWR10:
1456 case PPC::DIR_PWR_FUTURE:
1457 setPrefLoopAlignment(Align(16));
1458 setPrefFunctionAlignment(Align(16));
1459 break;
1460 }
1461
1462 if (Subtarget.enableMachineScheduler())
1463 setSchedulingPreference(Sched::Source);
1464 else
1465 setSchedulingPreference(Sched::Hybrid);
1466
1467 computeRegisterProperties(STI.getRegisterInfo());
1468
1469 // The Freescale cores do better with aggressive inlining of memcpy and
1470 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1471 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1472 Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1473 MaxStoresPerMemset = 32;
1474 MaxStoresPerMemsetOptSize = 16;
1475 MaxStoresPerMemcpy = 32;
1476 MaxStoresPerMemcpyOptSize = 8;
1477 MaxStoresPerMemmove = 32;
1478 MaxStoresPerMemmoveOptSize = 8;
1479 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1480 // The A2 also benefits from (very) aggressive inlining of memcpy and
1481 // friends. The overhead of a the function call, even when warm, can be
1482 // over one hundred cycles.
1483 MaxStoresPerMemset = 128;
1484 MaxStoresPerMemcpy = 128;
1485 MaxStoresPerMemmove = 128;
1486 MaxLoadsPerMemcmp = 128;
1487 } else {
1488 MaxLoadsPerMemcmp = 8;
1489 MaxLoadsPerMemcmpOptSize = 4;
1490 }
1491
1492 IsStrictFPEnabled = true;
1493
1494 // Let the subtarget (CPU) decide if a predictable select is more expensive
1495 // than the corresponding branch. This information is used in CGP to decide
1496 // when to convert selects into branches.
1497 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1498}
1499
1500// *********************************** NOTE ************************************
1501// For selecting load and store instructions, the addressing modes are defined
1502// as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1503// patterns to match the load the store instructions.
1504//
1505// The TD definitions for the addressing modes correspond to their respective
1506// Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1507// on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1508// address mode flags of a particular node. Afterwards, the computed address
1509// flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1510// addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1511// accordingly, based on the preferred addressing mode.
1512//
1513// Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1514// MemOpFlags contains all the possible flags that can be used to compute the
1515// optimal addressing mode for load and store instructions.
1516// AddrMode contains all the possible load and store addressing modes available
1517// on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1518//
1519// When adding new load and store instructions, it is possible that new address
1520// flags may need to be added into MemOpFlags, and a new addressing mode will
1521// need to be added to AddrMode. An entry of the new addressing mode (consisting
1522// of the minimal and main distinguishing address flags for the new load/store
1523// instructions) will need to be added into initializeAddrModeMap() below.
1524// Finally, when adding new addressing modes, the getAddrModeForFlags() will
1525// need to be updated to account for selecting the optimal addressing mode.
1526// *****************************************************************************
1527/// Initialize the map that relates the different addressing modes of the load
1528/// and store instructions to a set of flags. This ensures the load/store
1529/// instruction is correctly matched during instruction selection.
1530void PPCTargetLowering::initializeAddrModeMap() {
1531 AddrModesMap[PPC::AM_DForm] = {
1532 // LWZ, STW
1533 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1534 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1535 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1536 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1537 // LBZ, LHZ, STB, STH
1538 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1539 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1540 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1541 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1542 // LHA
1543 PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1544 PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1545 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1546 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1547 // LFS, LFD, STFS, STFD
1548 PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1549 PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1550 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1551 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1552 };
1553 AddrModesMap[PPC::AM_DSForm] = {
1554 // LWA
1555 PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1556 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1557 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1558 // LD, STD
1559 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1560 PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1561 PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1562 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1563 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1564 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1565 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1566 };
1567 AddrModesMap[PPC::AM_DQForm] = {
1568 // LXV, STXV
1569 PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1570 PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1571 PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1572 };
1573 AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1574 PPC::MOF_SubtargetP10};
1575 // TODO: Add mapping for quadword load/store.
1576}
1577
1578/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1579/// the desired ByVal argument alignment.
1580static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1581 if (MaxAlign == MaxMaxAlign)
1582 return;
1583 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1584 if (MaxMaxAlign >= 32 &&
1585 VTy->getPrimitiveSizeInBits().getFixedValue() >= 256)
1586 MaxAlign = Align(32);
1587 else if (VTy->getPrimitiveSizeInBits().getFixedValue() >= 128 &&
1588 MaxAlign < 16)
1589 MaxAlign = Align(16);
1590 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1591 Align EltAlign;
1592 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1593 if (EltAlign > MaxAlign)
1594 MaxAlign = EltAlign;
1595 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1596 for (auto *EltTy : STy->elements()) {
1597 Align EltAlign;
1598 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1599 if (EltAlign > MaxAlign)
1600 MaxAlign = EltAlign;
1601 if (MaxAlign == MaxMaxAlign)
1602 break;
1603 }
1604 }
1605}
1606
1607/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1608/// function arguments in the caller parameter area.
1609uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1610 const DataLayout &DL) const {
1611 // 16byte and wider vectors are passed on 16byte boundary.
1612 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1613 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1614 if (Subtarget.hasAltivec())
1615 getMaxByValAlign(Ty, Alignment, Align(16));
1616 return Alignment.value();
1617}
1618
1619bool PPCTargetLowering::useSoftFloat() const {
1620 return Subtarget.useSoftFloat();
1621}
1622
1623bool PPCTargetLowering::hasSPE() const {
1624 return Subtarget.hasSPE();
1625}
1626
1627bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1628 return VT.isScalarInteger();
1629}
1630
1631const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1632 switch ((PPCISD::NodeType)Opcode) {
1633 case PPCISD::FIRST_NUMBER: break;
1634 case PPCISD::FSEL: return "PPCISD::FSEL";
1635 case PPCISD::XSMAXC: return "PPCISD::XSMAXC";
1636 case PPCISD::XSMINC: return "PPCISD::XSMINC";
1637 case PPCISD::FCFID: return "PPCISD::FCFID";
1638 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1639 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1640 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1641 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1642 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1643 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1644 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1645 case PPCISD::FP_TO_UINT_IN_VSR:
1646 return "PPCISD::FP_TO_UINT_IN_VSR,";
1647 case PPCISD::FP_TO_SINT_IN_VSR:
1648 return "PPCISD::FP_TO_SINT_IN_VSR";
1649 case PPCISD::FRE: return "PPCISD::FRE";
1650 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1651 case PPCISD::FTSQRT:
1652 return "PPCISD::FTSQRT";
1653 case PPCISD::FSQRT:
1654 return "PPCISD::FSQRT";
1655 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1656 case PPCISD::VPERM: return "PPCISD::VPERM";
1657 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1658 case PPCISD::XXSPLTI_SP_TO_DP:
1659 return "PPCISD::XXSPLTI_SP_TO_DP";
1660 case PPCISD::XXSPLTI32DX:
1661 return "PPCISD::XXSPLTI32DX";
1662 case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1663 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1664 case PPCISD::XXPERM:
1665 return "PPCISD::XXPERM";
1666 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1667 case PPCISD::CMPB: return "PPCISD::CMPB";
1668 case PPCISD::Hi: return "PPCISD::Hi";
1669 case PPCISD::Lo: return "PPCISD::Lo";
1670 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1671 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1672 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1673 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1674 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1675 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA";
1676 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1677 case PPCISD::SRL: return "PPCISD::SRL";
1678 case PPCISD::SRA: return "PPCISD::SRA";
1679 case PPCISD::SHL: return "PPCISD::SHL";
1680 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1681 case PPCISD::CALL: return "PPCISD::CALL";
1682 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1683 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC";
1684 case PPCISD::CALL_RM:
1685 return "PPCISD::CALL_RM";
1686 case PPCISD::CALL_NOP_RM:
1687 return "PPCISD::CALL_NOP_RM";
1688 case PPCISD::CALL_NOTOC_RM:
1689 return "PPCISD::CALL_NOTOC_RM";
1690 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1691 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1692 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1693 case PPCISD::BCTRL_RM:
1694 return "PPCISD::BCTRL_RM";
1695 case PPCISD::BCTRL_LOAD_TOC_RM:
1696 return "PPCISD::BCTRL_LOAD_TOC_RM";
1697 case PPCISD::RET_GLUE: return "PPCISD::RET_GLUE";
1698 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1699 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1700 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1701 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1702 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1703 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1704 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1705 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1706 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1707 case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1708 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1709 case PPCISD::ANDI_rec_1_EQ_BIT:
1710 return "PPCISD::ANDI_rec_1_EQ_BIT";
1711 case PPCISD::ANDI_rec_1_GT_BIT:
1712 return "PPCISD::ANDI_rec_1_GT_BIT";
1713 case PPCISD::VCMP: return "PPCISD::VCMP";
1714 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec";
1715 case PPCISD::LBRX: return "PPCISD::LBRX";
1716 case PPCISD::STBRX: return "PPCISD::STBRX";
1717 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1718 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1719 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1720 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1721 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1722 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1723 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1724 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE";
1725 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE";
1726 case PPCISD::ST_VSR_SCAL_INT:
1727 return "PPCISD::ST_VSR_SCAL_INT";
1728 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1729 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1730 case PPCISD::BDZ: return "PPCISD::BDZ";
1731 case PPCISD::MFFS: return "PPCISD::MFFS";
1732 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1733 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1734 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1735 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1736 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1737 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1738 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1739 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1740 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1741 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1742 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1743 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1744 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1745 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX";
1746 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1747 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1748 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1749 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1750 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1751 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1752 case PPCISD::PADDI_DTPREL:
1753 return "PPCISD::PADDI_DTPREL";
1754 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1755 case PPCISD::SC: return "PPCISD::SC";
1756 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1757 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1758 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1759 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1760 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1761 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1762 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64";
1763 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE";
1764 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
1765 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
1766 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF";
1767 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR";
1768 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1769 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1770 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1771 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1772 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD";
1773 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD";
1774 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1775 case PPCISD::XXMFACC: return "PPCISD::XXMFACC";
1776 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT";
1777 case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT";
1778 case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT";
1779 case PPCISD::FNMSUB: return "PPCISD::FNMSUB";
1780 case PPCISD::STRICT_FADDRTZ:
1781 return "PPCISD::STRICT_FADDRTZ";
1782 case PPCISD::STRICT_FCTIDZ:
1783 return "PPCISD::STRICT_FCTIDZ";
1784 case PPCISD::STRICT_FCTIWZ:
1785 return "PPCISD::STRICT_FCTIWZ";
1786 case PPCISD::STRICT_FCTIDUZ:
1787 return "PPCISD::STRICT_FCTIDUZ";
1788 case PPCISD::STRICT_FCTIWUZ:
1789 return "PPCISD::STRICT_FCTIWUZ";
1790 case PPCISD::STRICT_FCFID:
1791 return "PPCISD::STRICT_FCFID";
1792 case PPCISD::STRICT_FCFIDU:
1793 return "PPCISD::STRICT_FCFIDU";
1794 case PPCISD::STRICT_FCFIDS:
1795 return "PPCISD::STRICT_FCFIDS";
1796 case PPCISD::STRICT_FCFIDUS:
1797 return "PPCISD::STRICT_FCFIDUS";
1798 case PPCISD::LXVRZX: return "PPCISD::LXVRZX";
1799 case PPCISD::STORE_COND:
1800 return "PPCISD::STORE_COND";
1801 }
1802 return nullptr;
1803}
1804
1805EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1806 EVT VT) const {
1807 if (!VT.isVector())
1808 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1809
1810 return VT.changeVectorElementTypeToInteger();
1811}
1812
1813bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1814 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", 1814, __extension__
__PRETTY_FUNCTION__))
;
1815 return true;
1816}
1817
1818//===----------------------------------------------------------------------===//
1819// Node matching predicates, for use by the tblgen matching code.
1820//===----------------------------------------------------------------------===//
1821
1822/// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1823static bool isFloatingPointZero(SDValue Op) {
1824 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1825 return CFP->getValueAPF().isZero();
1826 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1827 // Maybe this has already been legalized into the constant pool?
1828 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1829 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1830 return CFP->getValueAPF().isZero();
1831 }
1832 return false;
1833}
1834
1835/// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1836/// true if Op is undef or if it matches the specified value.
1837static bool isConstantOrUndef(int Op, int Val) {
1838 return Op < 0 || Op == Val;
1839}
1840
1841/// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1842/// VPKUHUM instruction.
1843/// The ShuffleKind distinguishes between big-endian operations with
1844/// two different inputs (0), either-endian operations with two identical
1845/// inputs (1), and little-endian operations with two different inputs (2).
1846/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1847bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1848 SelectionDAG &DAG) {
1849 bool IsLE = DAG.getDataLayout().isLittleEndian();
1850 if (ShuffleKind == 0) {
1851 if (IsLE)
1852 return false;
1853 for (unsigned i = 0; i != 16; ++i)
1854 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1855 return false;
1856 } else if (ShuffleKind == 2) {
1857 if (!IsLE)
1858 return false;
1859 for (unsigned i = 0; i != 16; ++i)
1860 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1861 return false;
1862 } else if (ShuffleKind == 1) {
1863 unsigned j = IsLE ? 0 : 1;
1864 for (unsigned i = 0; i != 8; ++i)
1865 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1866 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1867 return false;
1868 }
1869 return true;
1870}
1871
1872/// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1873/// VPKUWUM instruction.
1874/// The ShuffleKind distinguishes between big-endian operations with
1875/// two different inputs (0), either-endian operations with two identical
1876/// inputs (1), and little-endian operations with two different inputs (2).
1877/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1878bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1879 SelectionDAG &DAG) {
1880 bool IsLE = DAG.getDataLayout().isLittleEndian();
1881 if (ShuffleKind == 0) {
1882 if (IsLE)
1883 return false;
1884 for (unsigned i = 0; i != 16; i += 2)
1885 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1886 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1887 return false;
1888 } else if (ShuffleKind == 2) {
1889 if (!IsLE)
1890 return false;
1891 for (unsigned i = 0; i != 16; i += 2)
1892 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1893 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1894 return false;
1895 } else if (ShuffleKind == 1) {
1896 unsigned j = IsLE ? 0 : 2;
1897 for (unsigned i = 0; i != 8; i += 2)
1898 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1899 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1900 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1901 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1902 return false;
1903 }
1904 return true;
1905}
1906
1907/// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1908/// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1909/// current subtarget.
1910///
1911/// The ShuffleKind distinguishes between big-endian operations with
1912/// two different inputs (0), either-endian operations with two identical
1913/// inputs (1), and little-endian operations with two different inputs (2).
1914/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1915bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1916 SelectionDAG &DAG) {
1917 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
1918 if (!Subtarget.hasP8Vector())
1919 return false;
1920
1921 bool IsLE = DAG.getDataLayout().isLittleEndian();
1922 if (ShuffleKind == 0) {
1923 if (IsLE)
1924 return false;
1925 for (unsigned i = 0; i != 16; i += 4)
1926 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1927 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1928 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1929 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1930 return false;
1931 } else if (ShuffleKind == 2) {
1932 if (!IsLE)
1933 return false;
1934 for (unsigned i = 0; i != 16; i += 4)
1935 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1936 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1937 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1938 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1939 return false;
1940 } else if (ShuffleKind == 1) {
1941 unsigned j = IsLE ? 0 : 4;
1942 for (unsigned i = 0; i != 8; i += 4)
1943 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1944 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1945 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1946 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1947 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1948 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1949 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1950 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1951 return false;
1952 }
1953 return true;
1954}
1955
1956/// isVMerge - Common function, used to match vmrg* shuffles.
1957///
1958static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1959 unsigned LHSStart, unsigned RHSStart) {
1960 if (N->getValueType(0) != MVT::v16i8)
1961 return false;
1962 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", 1963, __extension__
__PRETTY_FUNCTION__))
1963 "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", 1963, __extension__
__PRETTY_FUNCTION__))
;
1964
1965 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1966 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1967 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1968 LHSStart+j+i*UnitSize) ||
1969 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1970 RHSStart+j+i*UnitSize))
1971 return false;
1972 }
1973 return true;
1974}
1975
1976/// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1977/// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1978/// The ShuffleKind distinguishes between big-endian merges with two
1979/// different inputs (0), either-endian merges with two identical inputs (1),
1980/// and little-endian merges with two different inputs (2). For the latter,
1981/// the input operands are swapped (see PPCInstrAltivec.td).
1982bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1983 unsigned ShuffleKind, SelectionDAG &DAG) {
1984 if (DAG.getDataLayout().isLittleEndian()) {
1985 if (ShuffleKind == 1) // unary
1986 return isVMerge(N, UnitSize, 0, 0);
1987 else if (ShuffleKind == 2) // swapped
1988 return isVMerge(N, UnitSize, 0, 16);
1989 else
1990 return false;
1991 } else {
1992 if (ShuffleKind == 1) // unary
1993 return isVMerge(N, UnitSize, 8, 8);
1994 else if (ShuffleKind == 0) // normal
1995 return isVMerge(N, UnitSize, 8, 24);
1996 else
1997 return false;
1998 }
1999}
2000
2001/// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
2002/// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
2003/// The ShuffleKind distinguishes between big-endian merges with two
2004/// different inputs (0), either-endian merges with two identical inputs (1),
2005/// and little-endian merges with two different inputs (2). For the latter,
2006/// the input operands are swapped (see PPCInstrAltivec.td).
2007bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
2008 unsigned ShuffleKind, SelectionDAG &DAG) {
2009 if (DAG.getDataLayout().isLittleEndian()) {
2010 if (ShuffleKind == 1) // unary
2011 return isVMerge(N, UnitSize, 8, 8);
2012 else if (ShuffleKind == 2) // swapped
2013 return isVMerge(N, UnitSize, 8, 24);
2014 else
2015 return false;
2016 } else {
2017 if (ShuffleKind == 1) // unary
2018 return isVMerge(N, UnitSize, 0, 0);
2019 else if (ShuffleKind == 0) // normal
2020 return isVMerge(N, UnitSize, 0, 16);
2021 else
2022 return false;
2023 }
2024}
2025
2026/**
2027 * Common function used to match vmrgew and vmrgow shuffles
2028 *
2029 * The indexOffset determines whether to look for even or odd words in
2030 * the shuffle mask. This is based on the of the endianness of the target
2031 * machine.
2032 * - Little Endian:
2033 * - Use offset of 0 to check for odd elements
2034 * - Use offset of 4 to check for even elements
2035 * - Big Endian:
2036 * - Use offset of 0 to check for even elements
2037 * - Use offset of 4 to check for odd elements
2038 * A detailed description of the vector element ordering for little endian and
2039 * big endian can be found at
2040 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
2041 * Targeting your applications - what little endian and big endian IBM XL C/C++
2042 * compiler differences mean to you
2043 *
2044 * The mask to the shuffle vector instruction specifies the indices of the
2045 * elements from the two input vectors to place in the result. The elements are
2046 * numbered in array-access order, starting with the first vector. These vectors
2047 * are always of type v16i8, thus each vector will contain 16 elements of size
2048 * 8. More info on the shuffle vector can be found in the
2049 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2050 * Language Reference.
2051 *
2052 * The RHSStartValue indicates whether the same input vectors are used (unary)
2053 * or two different input vectors are used, based on the following:
2054 * - If the instruction uses the same vector for both inputs, the range of the
2055 * indices will be 0 to 15. In this case, the RHSStart value passed should
2056 * be 0.
2057 * - If the instruction has two different vectors then the range of the
2058 * indices will be 0 to 31. In this case, the RHSStart value passed should
2059 * be 16 (indices 0-15 specify elements in the first vector while indices 16
2060 * to 31 specify elements in the second vector).
2061 *
2062 * \param[in] N The shuffle vector SD Node to analyze
2063 * \param[in] IndexOffset Specifies whether to look for even or odd elements
2064 * \param[in] RHSStartValue Specifies the starting index for the righthand input
2065 * vector to the shuffle_vector instruction
2066 * \return true iff this shuffle vector represents an even or odd word merge
2067 */
2068static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2069 unsigned RHSStartValue) {
2070 if (N->getValueType(0) != MVT::v16i8)
2071 return false;
2072
2073 for (unsigned i = 0; i < 2; ++i)
2074 for (unsigned j = 0; j < 4; ++j)
2075 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2076 i*RHSStartValue+j+IndexOffset) ||
2077 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2078 i*RHSStartValue+j+IndexOffset+8))
2079 return false;
2080 return true;
2081}
2082
2083/**
2084 * Determine if the specified shuffle mask is suitable for the vmrgew or
2085 * vmrgow instructions.
2086 *
2087 * \param[in] N The shuffle vector SD Node to analyze
2088 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2089 * \param[in] ShuffleKind Identify the type of merge:
2090 * - 0 = big-endian merge with two different inputs;
2091 * - 1 = either-endian merge with two identical inputs;
2092 * - 2 = little-endian merge with two different inputs (inputs are swapped for
2093 * little-endian merges).
2094 * \param[in] DAG The current SelectionDAG
2095 * \return true iff this shuffle mask
2096 */
2097bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2098 unsigned ShuffleKind, SelectionDAG &DAG) {
2099 if (DAG.getDataLayout().isLittleEndian()) {
2100 unsigned indexOffset = CheckEven ? 4 : 0;
2101 if (ShuffleKind == 1) // Unary
2102 return isVMerge(N, indexOffset, 0);
2103 else if (ShuffleKind == 2) // swapped
2104 return isVMerge(N, indexOffset, 16);
2105 else
2106 return false;
2107 }
2108 else {
2109 unsigned indexOffset = CheckEven ? 0 : 4;
2110 if (ShuffleKind == 1) // Unary
2111 return isVMerge(N, indexOffset, 0);
2112 else if (ShuffleKind == 0) // Normal
2113 return isVMerge(N, indexOffset, 16);
2114 else
2115 return false;
2116 }
2117 return false;
2118}
2119
2120/// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2121/// amount, otherwise return -1.
2122/// The ShuffleKind distinguishes between big-endian operations with two
2123/// different inputs (0), either-endian operations with two identical inputs
2124/// (1), and little-endian operations with two different inputs (2). For the
2125/// latter, the input operands are swapped (see PPCInstrAltivec.td).
2126int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2127 SelectionDAG &DAG) {
2128 if (N->getValueType(0) != MVT::v16i8)
2129 return -1;
2130
2131 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2132
2133 // Find the first non-undef value in the shuffle mask.
2134 unsigned i;
2135 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2136 /*search*/;
2137
2138 if (i == 16) return -1; // all undef.
2139
2140 // Otherwise, check to see if the rest of the elements are consecutively
2141 // numbered from this value.
2142 unsigned ShiftAmt = SVOp->getMaskElt(i);
2143 if (ShiftAmt < i) return -1;
2144
2145 ShiftAmt -= i;
2146 bool isLE = DAG.getDataLayout().isLittleEndian();
2147
2148 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2149 // Check the rest of the elements to see if they are consecutive.
2150 for (++i; i != 16; ++i)
2151 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2152 return -1;
2153 } else if (ShuffleKind == 1) {
2154 // Check the rest of the elements to see if they are consecutive.
2155 for (++i; i != 16; ++i)
2156 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2157 return -1;
2158 } else
2159 return -1;
2160
2161 if (isLE)
2162 ShiftAmt = 16 - ShiftAmt;
2163
2164 return ShiftAmt;
2165}
2166
2167/// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2168/// specifies a splat of a single element that is suitable for input to
2169/// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2170bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2171 EVT VT = N->getValueType(0);
2172 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2173 return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1);
2174
2175 assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) &&(static_cast <bool> (VT == MVT::v16i8 && isPowerOf2_32
(EltSize) && EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"
) ? void (0) : __assert_fail ("VT == MVT::v16i8 && isPowerOf2_32(EltSize) && EltSize <= 8 && \"Can only handle 1,2,4,8 byte element sizes\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 2176, __extension__
__PRETTY_FUNCTION__))
2176 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes")(static_cast <bool> (VT == MVT::v16i8 && isPowerOf2_32
(EltSize) && EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"
) ? void (0) : __assert_fail ("VT == MVT::v16i8 && isPowerOf2_32(EltSize) && EltSize <= 8 && \"Can only handle 1,2,4,8 byte element sizes\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 2176, __extension__
__PRETTY_FUNCTION__))
;
2177
2178 // The consecutive indices need to specify an element, not part of two
2179 // different elements. So abandon ship early if this isn't the case.
2180 if (N->getMaskElt(0) % EltSize != 0)
2181 return false;
2182
2183 // This is a splat operation if each element of the permute is the same, and
2184 // if the value doesn't reference the second vector.
2185 unsigned ElementBase = N->getMaskElt(0);
2186
2187 // FIXME: Handle UNDEF elements too!
2188 if (ElementBase >= 16)
2189 return false;
2190
2191 // Check that the indices are consecutive, in the case of a multi-byte element
2192 // splatted with a v16i8 mask.
2193 for (unsigned i = 1; i != EltSize; ++i)
2194 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2195 return false;
2196
2197 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2198 if (N->getMaskElt(i) < 0) continue;
2199 for (unsigned j = 0; j != EltSize; ++j)
2200 if (N->getMaskElt(i+j) != N->getMaskElt(j))
2201 return false;
2202 }
2203 return true;
2204}
2205
2206/// Check that the mask is shuffling N byte elements. Within each N byte
2207/// element of the mask, the indices could be either in increasing or
2208/// decreasing order as long as they are consecutive.
2209/// \param[in] N the shuffle vector SD Node to analyze
2210/// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2211/// Word/DoubleWord/QuadWord).
2212/// \param[in] StepLen the delta indices number among the N byte element, if
2213/// the mask is in increasing/decreasing order then it is 1/-1.
2214/// \return true iff the mask is shuffling N byte elements.
2215static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2216 int StepLen) {
2217 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", 2218, __extension__
__PRETTY_FUNCTION__))
2218 "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", 2218, __extension__
__PRETTY_FUNCTION__))
;
2219 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", 2219, __extension__
__PRETTY_FUNCTION__))
;
2220
2221 unsigned NumOfElem = 16 / Width;
2222 unsigned MaskVal[16]; // Width is never greater than 16
2223 for (unsigned i = 0; i < NumOfElem; ++i) {
2224 MaskVal[0] = N->getMaskElt(i * Width);
2225 if ((StepLen == 1) && (MaskVal[0] % Width)) {
2226 return false;
2227 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2228 return false;
2229 }
2230
2231 for (unsigned int j = 1; j < Width; ++j) {
2232 MaskVal[j] = N->getMaskElt(i * Width + j);
2233 if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2234 return false;
2235 }
2236 }
2237 }
2238
2239 return true;
2240}
2241
2242bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2243 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2244 if (!isNByteElemShuffleMask(N, 4, 1))
2245 return false;
2246
2247 // Now we look at mask elements 0,4,8,12
2248 unsigned M0 = N->getMaskElt(0) / 4;
2249 unsigned M1 = N->getMaskElt(4) / 4;
2250 unsigned M2 = N->getMaskElt(8) / 4;
2251 unsigned M3 = N->getMaskElt(12) / 4;
2252 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2253 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2254
2255 // Below, let H and L be arbitrary elements of the shuffle mask
2256 // where H is in the range [4,7] and L is in the range [0,3].
2257 // H, 1, 2, 3 or L, 5, 6, 7
2258 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2259 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2260 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2261 InsertAtByte = IsLE ? 12 : 0;
2262 Swap = M0 < 4;
2263 return true;
2264 }
2265 // 0, H, 2, 3 or 4, L, 6, 7
2266 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2267 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2268 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2269 InsertAtByte = IsLE ? 8 : 4;
2270 Swap = M1 < 4;
2271 return true;
2272 }
2273 // 0, 1, H, 3 or 4, 5, L, 7
2274 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2275 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2276 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2277 InsertAtByte = IsLE ? 4 : 8;
2278 Swap = M2 < 4;
2279 return true;
2280 }
2281 // 0, 1, 2, H or 4, 5, 6, L
2282 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2283 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2284 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2285 InsertAtByte = IsLE ? 0 : 12;
2286 Swap = M3 < 4;
2287 return true;
2288 }
2289
2290 // If both vector operands for the shuffle are the same vector, the mask will
2291 // contain only elements from the first one and the second one will be undef.
2292 if (N->getOperand(1).isUndef()) {
2293 ShiftElts = 0;
2294 Swap = true;
2295 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2296 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2297 InsertAtByte = IsLE ? 12 : 0;
2298 return true;
2299 }
2300 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2301 InsertAtByte = IsLE ? 8 : 4;
2302 return true;
2303 }
2304 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2305 InsertAtByte = IsLE ? 4 : 8;
2306 return true;
2307 }
2308 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2309 InsertAtByte = IsLE ? 0 : 12;
2310 return true;
2311 }
2312 }
2313
2314 return false;
2315}
2316
2317bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2318 bool &Swap, bool IsLE) {
2319 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", 2319, __extension__
__PRETTY_FUNCTION__))
;
14
'?' condition is true
2320 // Ensure each byte index of the word is consecutive.
2321 if (!isNByteElemShuffleMask(N, 4, 1))
15
Assuming the condition is false
16
Taking false branch
2322 return false;
2323
2324 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2325 unsigned M0 = N->getMaskElt(0) / 4;
2326 unsigned M1 = N->getMaskElt(4) / 4;
2327 unsigned M2 = N->getMaskElt(8) / 4;
2328 unsigned M3 = N->getMaskElt(12) / 4;
2329
2330 // If both vector operands for the shuffle are the same vector, the mask will
2331 // contain only elements from the first one and the second one will be undef.
2332 if (N->getOperand(1).isUndef()) {
2333 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", 2333, __extension__
__PRETTY_FUNCTION__))
;
2334 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2335 return false;
2336
2337 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2338 Swap = false;
2339 return true;
2340 }
2341
2342 // Ensure each word index of the ShuffleVector Mask is consecutive.
2343 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
17
Assuming the condition is false
18
Assuming the condition is false
19
Assuming the condition is false
20
Taking false branch
2344 return false;
2345
2346 if (IsLE
20.1
'IsLE' is false
) {
2347 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2348 // Input vectors don't need to be swapped if the leading element
2349 // of the result is one of the 3 left elements of the second vector
2350 // (or if there is no shift to be done at all).
2351 Swap = false;
2352 ShiftElts = (8 - M0) % 8;
2353 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2354 // Input vectors need to be swapped if the leading element
2355 // of the result is one of the 3 left elements of the first vector
2356 // (or if we're shifting by 4 - thereby simply swapping the vectors).
2357 Swap = true;
2358 ShiftElts = (4 - M0) % 4;
2359 }
2360
2361 return true;
2362 } else { // BE
2363 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
21
Assuming 'M0' is not equal to 0
22
Assuming 'M0' is not equal to 1
23
Assuming 'M0' is not equal to 2
24
Assuming 'M0' is not equal to 3
2364 // Input vectors don't need to be swapped if the leading element
2365 // of the result is one of the 4 elements of the first vector.
2366 Swap = false;
2367 ShiftElts = M0;
2368 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
25
Assuming 'M0' is not equal to 4
26
Assuming 'M0' is not equal to 5
27
Assuming 'M0' is not equal to 6
28
Assuming 'M0' is not equal to 7
29
Taking false branch
2369 // Input vectors need to be swapped if the leading element
2370 // of the result is one of the 4 elements of the right vector.
2371 Swap = true;
2372 ShiftElts = M0 - 4;
2373 }
2374
2375 return true;
30
Returning without writing to 'ShiftElts'
2376 }
2377}
2378
2379bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2380 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", 2380, __extension__
__PRETTY_FUNCTION__))
;
2381
2382 if (!isNByteElemShuffleMask(N, Width, -1))
2383 return false;
2384
2385 for (int i = 0; i < 16; i += Width)
2386 if (N->getMaskElt(i) != i + Width - 1)
2387 return false;
2388
2389 return true;
2390}
2391
2392bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2393 return isXXBRShuffleMaskHelper(N, 2);
2394}
2395
2396bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2397 return isXXBRShuffleMaskHelper(N, 4);
2398}
2399
2400bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2401 return isXXBRShuffleMaskHelper(N, 8);
2402}
2403
2404bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2405 return isXXBRShuffleMaskHelper(N, 16);
2406}
2407
2408/// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2409/// if the inputs to the instruction should be swapped and set \p DM to the
2410/// value for the immediate.
2411/// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2412/// AND element 0 of the result comes from the first input (LE) or second input
2413/// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2414/// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2415/// mask.
2416bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2417 bool &Swap, bool IsLE) {
2418 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", 2418, __extension__
__PRETTY_FUNCTION__))
;
2419
2420 // Ensure each byte index of the double word is consecutive.
2421 if (!isNByteElemShuffleMask(N, 8, 1))
2422 return false;
2423
2424 unsigned M0 = N->getMaskElt(0) / 8;
2425 unsigned M1 = N->getMaskElt(8) / 8;
2426 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", 2426, __extension__
__PRETTY_FUNCTION__))
;
2427
2428 // If both vector operands for the shuffle are the same vector, the mask will
2429 // contain only elements from the first one and the second one will be undef.
2430 if (N->getOperand(1).isUndef()) {
2431 if ((M0 | M1) < 2) {
2432 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2433 Swap = false;
2434 return true;
2435 } else
2436 return false;
2437 }
2438
2439 if (IsLE) {
2440 if (M0 > 1 && M1 < 2) {
2441 Swap = false;
2442 } else if (M0 < 2 && M1 > 1) {
2443 M0 = (M0 + 2) % 4;
2444 M1 = (M1 + 2) % 4;
2445 Swap = true;
2446 } else
2447 return false;
2448
2449 // Note: if control flow comes here that means Swap is already set above
2450 DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2451 return true;
2452 } else { // BE
2453 if (M0 < 2 && M1 > 1) {
2454 Swap = false;
2455 } else if (M0 > 1 && M1 < 2) {
2456 M0 = (M0 + 2) % 4;
2457 M1 = (M1 + 2) % 4;
2458 Swap = true;
2459 } else
2460 return false;
2461
2462 // Note: if control flow comes here that means Swap is already set above
2463 DM = (M0 << 1) + (M1 & 1);
2464 return true;
2465 }
2466}
2467
2468
2469/// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2470/// appropriate for PPC mnemonics (which have a big endian bias - namely
2471/// elements are counted from the left of the vector register).
2472unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2473 SelectionDAG &DAG) {
2474 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2475 assert(isSplatShuffleMask(SVOp, EltSize))(static_cast <bool> (isSplatShuffleMask(SVOp, EltSize))
? void (0) : __assert_fail ("isSplatShuffleMask(SVOp, EltSize)"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 2475, __extension__
__PRETTY_FUNCTION__))
;
2476 EVT VT = SVOp->getValueType(0);
2477
2478 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2479 return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0)
2480 : SVOp->getMaskElt(0);
2481
2482 if (DAG.getDataLayout().isLittleEndian())
2483 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2484 else
2485 return SVOp->getMaskElt(0) / EltSize;
2486}
2487
2488/// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2489/// by using a vspltis[bhw] instruction of the specified element size, return
2490/// the constant being splatted. The ByteSize field indicates the number of
2491/// bytes of each element [124] -> [bhw].
2492SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2493 SDValue OpVal;
2494
2495 // If ByteSize of the splat is bigger than the element size of the
2496 // build_vector, then we have a case where we are checking for a splat where
2497 // multiple elements of the buildvector are folded together into a single
2498 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2499 unsigned EltSize = 16/N->getNumOperands();
2500 if (EltSize < ByteSize) {
2501 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2502 SDValue UniquedVals[4];
2503 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", 2503, __extension__
__PRETTY_FUNCTION__))
;
2504
2505 // See if all of the elements in the buildvector agree across.
2506 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2507 if (N->getOperand(i).isUndef()) continue;
2508 // If the element isn't a constant, bail fully out.
2509 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2510
2511 if (!UniquedVals[i&(Multiple-1)].getNode())
2512 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2513 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2514 return SDValue(); // no match.
2515 }
2516
2517 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2518 // either constant or undef values that are identical for each chunk. See
2519 // if these chunks can form into a larger vspltis*.
2520
2521 // Check to see if all of the leading entries are either 0 or -1. If
2522 // neither, then this won't fit into the immediate field.
2523 bool LeadingZero = true;
2524 bool LeadingOnes = true;
2525 for (unsigned i = 0; i != Multiple-1; ++i) {
2526 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2527
2528 LeadingZero &= isNullConstant(UniquedVals[i]);
2529 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2530 }
2531 // Finally, check the least significant entry.
2532 if (LeadingZero) {
2533 if (!UniquedVals[Multiple-1].getNode())
2534 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2535 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2536 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2537 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2538 }
2539 if (LeadingOnes) {
2540 if (!UniquedVals[Multiple-1].getNode())
2541 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2542 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2543 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2544 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2545 }
2546
2547 return SDValue();
2548 }
2549
2550 // Check to see if this buildvec has a single non-undef value in its elements.
2551 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2552 if (N->getOperand(i).isUndef()) continue;
2553 if (!OpVal.getNode())
2554 OpVal = N->getOperand(i);
2555 else if (OpVal != N->getOperand(i))
2556 return SDValue();
2557 }
2558
2559 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2560
2561 unsigned ValSizeInBytes = EltSize;
2562 uint64_t Value = 0;
2563 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2564 Value = CN->getZExtValue();
2565 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2566 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", 2566, __extension__
__PRETTY_FUNCTION__))
;
2567 Value = llvm::bit_cast<uint32_t>(CN->getValueAPF().convertToFloat());
2568 }
2569
2570 // If the splat value is larger than the element value, then we can never do
2571 // this splat. The only case that we could fit the replicated bits into our
2572 // immediate field for would be zero, and we prefer to use vxor for it.
2573 if (ValSizeInBytes < ByteSize) return SDValue();
2574
2575 // If the element value is larger than the splat value, check if it consists
2576 // of a repeated bit pattern of size ByteSize.
2577 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2578 return SDValue();
2579
2580 // Properly sign extend the value.
2581 int MaskVal = SignExtend32(Value, ByteSize * 8);
2582
2583 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2584 if (MaskVal == 0) return SDValue();
2585
2586 // Finally, if this value fits in a 5 bit sext field, return it
2587 if (SignExtend32<5>(MaskVal) == MaskVal)
2588 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2589 return SDValue();
2590}
2591
2592//===----------------------------------------------------------------------===//
2593// Addressing Mode Selection
2594//===----------------------------------------------------------------------===//
2595
2596/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2597/// or 64-bit immediate, and if the value can be accurately represented as a
2598/// sign extension from a 16-bit value. If so, this returns true and the
2599/// immediate.
2600bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2601 if (!isa<ConstantSDNode>(N))
2602 return false;
2603
2604 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2605 if (N->getValueType(0) == MVT::i32)
2606 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2607 else
2608 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2609}
2610bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2611 return isIntS16Immediate(Op.getNode(), Imm);
2612}
2613
2614/// Used when computing address flags for selecting loads and stores.
2615/// If we have an OR, check if the LHS and RHS are provably disjoint.
2616/// An OR of two provably disjoint values is equivalent to an ADD.
2617/// Most PPC load/store instructions compute the effective address as a sum,
2618/// so doing this conversion is useful.
2619static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2620 if (N.getOpcode() != ISD::OR)
2621 return false;
2622 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2623 if (!LHSKnown.Zero.getBoolValue())
2624 return false;
2625 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2626 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2627}
2628
2629/// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2630/// be represented as an indexed [r+r] operation.
2631bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2632 SDValue &Index,
2633 SelectionDAG &DAG) const {
2634 for (SDNode *U : N->uses()) {
2635 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2636 if (Memop->getMemoryVT() == MVT::f64) {
2637 Base = N.getOperand(0);
2638 Index = N.getOperand(1);
2639 return true;
2640 }
2641 }
2642 }
2643 return false;
2644}
2645
2646/// isIntS34Immediate - This method tests if value of node given can be
2647/// accurately represented as a sign extension from a 34-bit value. If so,
2648/// this returns true and the immediate.
2649bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2650 if (!isa<ConstantSDNode>(N))
2651 return false;
2652
2653 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2654 return isInt<34>(Imm);
2655}
2656bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2657 return isIntS34Immediate(Op.getNode(), Imm);
2658}
2659
2660/// SelectAddressRegReg - Given the specified addressed, check to see if it
2661/// can be represented as an indexed [r+r] operation. Returns false if it
2662/// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2663/// non-zero and N can be represented by a base register plus a signed 16-bit
2664/// displacement, make a more precise judgement by checking (displacement % \p
2665/// EncodingAlignment).
2666bool PPCTargetLowering::SelectAddressRegReg(
2667 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2668 MaybeAlign EncodingAlignment) const {
2669 // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2670 // a [pc+imm].
2671 if (SelectAddressPCRel(N, Base))
2672 return false;
2673
2674 int16_t Imm = 0;
2675 if (N.getOpcode() == ISD::ADD) {
2676 // Is there any SPE load/store (f64), which can't handle 16bit offset?
2677 // SPE load/store can only handle 8-bit offsets.
2678 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2679 return true;
2680 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2681 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2682 return false; // r+i
2683 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2684 return false; // r+i
2685
2686 Base = N.getOperand(0);
2687 Index = N.getOperand(1);
2688 return true;
2689 } else if (N.getOpcode() == ISD::OR) {
2690 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2691 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2692 return false; // r+i can fold it if we can.
2693
2694 // If this is an or of disjoint bitfields, we can codegen this as an add
2695 // (for better address arithmetic) if the LHS and RHS of the OR are provably
2696 // disjoint.
2697 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2698
2699 if (LHSKnown.Zero.getBoolValue()) {
2700 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2701 // If all of the bits are known zero on the LHS or RHS, the add won't
2702 // carry.
2703 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2704 Base = N.getOperand(0);
2705 Index = N.getOperand(1);
2706 return true;
2707 }
2708 }
2709 }
2710
2711 return false;
2712}
2713
2714// If we happen to be doing an i64 load or store into a stack slot that has
2715// less than a 4-byte alignment, then the frame-index elimination may need to
2716// use an indexed load or store instruction (because the offset may not be a
2717// multiple of 4). The extra register needed to hold the offset comes from the
2718// register scavenger, and it is possible that the scavenger will need to use
2719// an emergency spill slot. As a result, we need to make sure that a spill slot
2720// is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2721// stack slot.
2722static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2723 // FIXME: This does not handle the LWA case.
2724 if (VT != MVT::i64)
2725 return;
2726
2727 // NOTE: We'll exclude negative FIs here, which come from argument
2728 // lowering, because there are no known test cases triggering this problem
2729 // using packed structures (or similar). We can remove this exclusion if
2730 // we find such a test case. The reason why this is so test-case driven is
2731 // because this entire 'fixup' is only to prevent crashes (from the
2732 // register scavenger) on not-really-valid inputs. For example, if we have:
2733 // %a = alloca i1
2734 // %b = bitcast i1* %a to i64*
2735 // store i64* a, i64 b
2736 // then the store should really be marked as 'align 1', but is not. If it
2737 // were marked as 'align 1' then the indexed form would have been
2738 // instruction-selected initially, and the problem this 'fixup' is preventing
2739 // won't happen regardless.
2740 if (FrameIdx < 0)
2741 return;
2742
2743 MachineFunction &MF = DAG.getMachineFunction();
2744 MachineFrameInfo &MFI = MF.getFrameInfo();
2745
2746 if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2747 return;
2748
2749 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2750 FuncInfo->setHasNonRISpills();
2751}
2752
2753/// Returns true if the address N can be represented by a base register plus
2754/// a signed 16-bit displacement [r+imm], and if it is not better
2755/// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2756/// displacements that are multiples of that value.
2757bool PPCTargetLowering::SelectAddressRegImm(
2758 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2759 MaybeAlign EncodingAlignment) const {
2760 // FIXME dl should come from parent load or store, not from address
2761 SDLoc dl(N);
2762
2763 // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2764 // a [pc+imm].
2765 if (SelectAddressPCRel(N, Base))
2766 return false;
2767
2768 // If this can be more profitably realized as r+r, fail.
2769 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2770 return false;
2771
2772 if (N.getOpcode() == ISD::ADD) {
2773 int16_t imm = 0;
2774 if (isIntS16Immediate(N.getOperand(1), imm) &&
2775 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2776 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2777 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2778 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2779 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2780 } else {
2781 Base = N.getOperand(0);
2782 }
2783 return true; // [r+i]
2784 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2785 // Match LOAD (ADD (X, Lo(G))).
2786 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", 2787, __extension__
__PRETTY_FUNCTION__))
2787 && "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", 2787, __extension__
__PRETTY_FUNCTION__))
;
2788 Disp = N.getOperand(1).getOperand(0); // The global address.
2789 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", 2792, __extension__
__PRETTY_FUNCTION__))
2790 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", 2792, __extension__
__PRETTY_FUNCTION__))
2791 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", 2792, __extension__
__PRETTY_FUNCTION__))
2792 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", 2792, __extension__
__PRETTY_FUNCTION__))
;
2793 Base = N.getOperand(0);
2794 return true; // [&g+r]
2795 }
2796 } else if (N.getOpcode() == ISD::OR) {
2797 int16_t imm = 0;
2798 if (isIntS16Immediate(N.getOperand(1), imm) &&
2799 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2800 // If this is an or of disjoint bitfields, we can codegen this as an add
2801 // (for better address arithmetic) if the LHS and RHS of the OR are
2802 // provably disjoint.
2803 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2804
2805 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2806 // If all of the bits are known zero on the LHS or RHS, the add won't
2807 // carry.
2808 if (FrameIndexSDNode *FI =
2809 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2810 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2811 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2812 } else {
2813 Base = N.getOperand(0);
2814 }
2815 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2816 return true;
2817 }
2818 }
2819 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2820 // Loading from a constant address.
2821
2822 // If this address fits entirely in a 16-bit sext immediate field, codegen
2823 // this as "d, 0"
2824 int16_t Imm;
2825 if (isIntS16Immediate(CN, Imm) &&
2826 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2827 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2828 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2829 CN->getValueType(0));
2830 return true;
2831 }
2832
2833 // Handle 32-bit sext immediates with LIS + addr mode.
2834 if ((CN->getValueType(0) == MVT::i32 ||
2835 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2836 (!EncodingAlignment ||
2837 isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2838 int Addr = (int)CN->getZExtValue();
2839
2840 // Otherwise, break this down into an LIS + disp.
2841 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2842
2843 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2844 MVT::i32);
2845 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2846 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2847 return true;
2848 }
2849 }
2850
2851 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2852 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2853 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2854 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2855 } else
2856 Base = N;
2857 return true; // [r+0]
2858}
2859
2860/// Similar to the 16-bit case but for instructions that take a 34-bit
2861/// displacement field (prefixed loads/stores).
2862bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2863 SDValue &Base,
2864 SelectionDAG &DAG) const {
2865 // Only on 64-bit targets.
2866 if (N.getValueType() != MVT::i64)
2867 return false;
2868
2869 SDLoc dl(N);
2870 int64_t Imm = 0;
2871
2872 if (N.getOpcode() == ISD::ADD) {
2873 if (!isIntS34Immediate(N.getOperand(1), Imm))
2874 return false;
2875 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2876 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2877 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2878 else
2879 Base = N.getOperand(0);
2880 return true;
2881 }
2882
2883 if (N.getOpcode() == ISD::OR) {
2884 if (!isIntS34Immediate(N.getOperand(1), Imm))
2885 return false;
2886 // If this is an or of disjoint bitfields, we can codegen this as an add
2887 // (for better address arithmetic) if the LHS and RHS of the OR are
2888 // provably disjoint.
2889 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2890 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2891 return false;
2892 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2893 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2894 else
2895 Base = N.getOperand(0);
2896 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2897 return true;
2898 }
2899
2900 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2901 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2902 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2903 return true;
2904 }
2905
2906 return false;
2907}
2908
2909/// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2910/// represented as an indexed [r+r] operation.
2911bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2912 SDValue &Index,
2913 SelectionDAG &DAG) const {
2914 // Check to see if we can easily represent this as an [r+r] address. This
2915 // will fail if it thinks that the address is more profitably represented as
2916 // reg+imm, e.g. where imm = 0.
2917 if (SelectAddressRegReg(N, Base, Index, DAG))
2918 return true;
2919
2920 // If the address is the result of an add, we will utilize the fact that the
2921 // address calculation includes an implicit add. However, we can reduce
2922 // register pressure if we do not materialize a constant just for use as the
2923 // index register. We only get rid of the add if it is not an add of a
2924 // value and a 16-bit signed constant and both have a single use.
2925 int16_t imm = 0;
2926 if (N.getOpcode() == ISD::ADD &&
2927 (!isIntS16Immediate(N.getOperand(1), imm) ||
2928 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2929 Base = N.getOperand(0);
2930 Index = N.getOperand(1);
2931 return true;
2932 }
2933
2934 // Otherwise, do it the hard way, using R0 as the base register.
2935 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2936 N.getValueType());
2937 Index = N;
2938 return true;
2939}
2940
2941template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2942 Ty *PCRelCand = dyn_cast<Ty>(N);
2943 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2944}
2945
2946/// Returns true if this address is a PC Relative address.
2947/// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2948/// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2949bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2950 // This is a materialize PC Relative node. Always select this as PC Relative.
2951 Base = N;
2952 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2953 return true;
2954 if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2955 isValidPCRelNode<GlobalAddressSDNode>(N) ||
2956 isValidPCRelNode<JumpTableSDNode>(N) ||
2957 isValidPCRelNode<BlockAddressSDNode>(N))
2958 return true;
2959 return false;
2960}
2961
2962/// Returns true if we should use a direct load into vector instruction
2963/// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2964static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2965
2966 // If there are any other uses other than scalar to vector, then we should
2967 // keep it as a scalar load -> direct move pattern to prevent multiple
2968 // loads.
2969 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2970 if (!LD)
2971 return false;
2972
2973 EVT MemVT = LD->getMemoryVT();
2974 if (!MemVT.isSimple())
2975 return false;
2976 switch(MemVT.getSimpleVT().SimpleTy) {
2977 case MVT::i64:
2978 break;
2979 case MVT::i32:
2980 if (!ST.hasP8Vector())
2981 return false;
2982 break;
2983 case MVT::i16:
2984 case MVT::i8:
2985 if (!ST.hasP9Vector())
2986 return false;
2987 break;
2988 default:
2989 return false;
2990 }
2991
2992 SDValue LoadedVal(N, 0);
2993 if (!LoadedVal.hasOneUse())
2994 return false;
2995
2996 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2997 UI != UE; ++UI)
2998 if (UI.getUse().get().getResNo() == 0 &&
2999 UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
3000 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
3001 return false;
3002
3003 return true;
3004}
3005
3006/// getPreIndexedAddressParts - returns true by value, base pointer and
3007/// offset pointer and addressing mode by reference if the node's address
3008/// can be legally represented as pre-indexed load / store address.
3009bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
3010 SDValue &Offset,
3011 ISD::MemIndexedMode &AM,
3012 SelectionDAG &DAG) const {
3013 if (DisablePPCPreinc) return false;
3014
3015 bool isLoad = true;
3016 SDValue Ptr;
3017 EVT VT;
3018 Align Alignment;
3019 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3020 Ptr = LD->getBasePtr();
3021 VT = LD->getMemoryVT();
3022 Alignment = LD->getAlign();
3023 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3024 Ptr = ST->getBasePtr();
3025 VT = ST->getMemoryVT();
3026 Alignment = ST->getAlign();
3027 isLoad = false;
3028 } else
3029 return false;
3030
3031 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
3032 // instructions because we can fold these into a more efficient instruction
3033 // instead, (such as LXSD).
3034 if (isLoad && usePartialVectorLoads(N, Subtarget)) {
3035 return false;
3036 }
3037
3038 // PowerPC doesn't have preinc load/store instructions for vectors
3039 if (VT.isVector())
3040 return false;
3041
3042 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
3043 // Common code will reject creating a pre-inc form if the base pointer
3044 // is a frame index, or if N is a store and the base pointer is either
3045 // the same as or a predecessor of the value being stored. Check for
3046 // those situations here, and try with swapped Base/Offset instead.
3047 bool Swap = false;
3048
3049 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
3050 Swap = true;
3051 else if (!isLoad) {
3052 SDValue Val = cast<StoreSDNode>(N)->getValue();
3053 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
3054 Swap = true;
3055 }
3056
3057 if (Swap)
3058 std::swap(Base, Offset);
3059
3060 AM = ISD::PRE_INC;
3061 return true;
3062 }
3063
3064 // LDU/STU can only handle immediates that are a multiple of 4.
3065 if (VT != MVT::i64) {
3066 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, std::nullopt))
3067 return false;
3068 } else {
3069 // LDU/STU need an address with at least 4-byte alignment.
3070 if (Alignment < Align(4))
3071 return false;
3072
3073 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3074 return false;
3075 }
3076
3077 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3078 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
3079 // sext i32 to i64 when addr mode is r+i.
3080 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3081 LD->getExtensionType() == ISD::SEXTLOAD &&
3082 isa<ConstantSDNode>(Offset))
3083 return false;
3084 }
3085
3086 AM = ISD::PRE_INC;
3087 return true;
3088}
3089
3090//===----------------------------------------------------------------------===//
3091// LowerOperation implementation
3092//===----------------------------------------------------------------------===//
3093
3094/// Return true if we should reference labels using a PICBase, set the HiOpFlags
3095/// and LoOpFlags to the target MO flags.
3096static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3097 unsigned &HiOpFlags, unsigned &LoOpFlags,
3098 const GlobalValue *GV = nullptr) {
3099 HiOpFlags = PPCII::MO_HA;
3100 LoOpFlags = PPCII::MO_LO;
3101
3102 // Don't use the pic base if not in PIC relocation model.
3103 if (IsPIC) {
3104 HiOpFlags |= PPCII::MO_PIC_FLAG;
3105 LoOpFlags |= PPCII::MO_PIC_FLAG;
3106 }
3107}
3108
3109static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3110 SelectionDAG &DAG) {
3111 SDLoc DL(HiPart);
3112 EVT PtrVT = HiPart.getValueType();
3113 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3114
3115 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3116 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3117
3118 // With PIC, the first instruction is actually "GR+hi(&G)".
3119 if (isPIC)
3120 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3121 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3122
3123 // Generate non-pic code that has direct accesses to the constant pool.
3124 // The address of the global is just (hi(&g)+lo(&g)).
3125 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3126}
3127
3128static void setUsesTOCBasePtr(MachineFunction &MF) {
3129 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3130 FuncInfo->setUsesTOCBasePtr();
3131}
3132
3133static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3134 setUsesTOCBasePtr(DAG.getMachineFunction());
3135}
3136
3137SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3138 SDValue GA) const {
3139 const bool Is64Bit = Subtarget.isPPC64();
3140 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3141 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3142 : Subtarget.isAIXABI()
3143 ? DAG.getRegister(PPC::R2, VT)
3144 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3145 SDValue Ops[] = { GA, Reg };
3146 return DAG.getMemIntrinsicNode(
3147 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3148 MachinePointerInfo::getGOT(DAG.getMachineFunction()), std::nullopt,
3149 MachineMemOperand::MOLoad);
3150}
3151
3152SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3153 SelectionDAG &DAG) const {
3154 EVT PtrVT = Op.getValueType();
3155 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3156 const Constant *C = CP->getConstVal();
3157
3158 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3159 // The actual address of the GlobalValue is stored in the TOC.
3160 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3161 if (Subtarget.isUsingPCRelativeCalls()) {
3162 SDLoc DL(CP);
3163 EVT Ty = getPointerTy(DAG.getDataLayout());
3164 SDValue ConstPool = DAG.getTargetConstantPool(
3165 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3166 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3167 }
3168 setUsesTOCBasePtr(DAG);
3169 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3170 return getTOCEntry(DAG, SDLoc(CP), GA);
3171 }
3172
3173 unsigned MOHiFlag, MOLoFlag;
3174 bool IsPIC = isPositionIndependent();
3175 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3176
3177 if (IsPIC && Subtarget.isSVR4ABI()) {
3178 SDValue GA =
3179 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3180 return getTOCEntry(DAG, SDLoc(CP), GA);
3181 }
3182
3183 SDValue CPIHi =
3184 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3185 SDValue CPILo =
3186 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3187 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3188}
3189
3190// For 64-bit PowerPC, prefer the more compact relative encodings.
3191// This trades 32 bits per jump table entry for one or two instructions
3192// on the jump site.
3193unsigned PPCTargetLowering::getJumpTableEncoding() const {
3194 if (isJumpTableRelative())
3195 return MachineJumpTableInfo::EK_LabelDifference32;
3196
3197 return TargetLowering::getJumpTableEncoding();
3198}
3199
3200bool PPCTargetLowering::isJumpTableRelative() const {
3201 if (UseAbsoluteJumpTables)
3202 return false;
3203 if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3204 return true;
3205 return TargetLowering::isJumpTableRelative();
3206}
3207
3208SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3209 SelectionDAG &DAG) const {
3210 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3211 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3212
3213 switch (getTargetMachine().getCodeModel()) {
3214 case CodeModel::Small:
3215 case CodeModel::Medium:
3216 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3217 default:
3218 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3219 getPointerTy(DAG.getDataLayout()));
3220 }
3221}
3222
3223const MCExpr *
3224PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3225 unsigned JTI,
3226 MCContext &Ctx) const {
3227 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3228 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3229
3230 switch (getTargetMachine().getCodeModel()) {
3231 case CodeModel::Small:
3232 case CodeModel::Medium:
3233 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3234 default:
3235 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3236 }
3237}
3238
3239SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3240 EVT PtrVT = Op.getValueType();
3241 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3242
3243 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3244 if (Subtarget.isUsingPCRelativeCalls()) {
3245 SDLoc DL(JT);
3246 EVT Ty = getPointerTy(DAG.getDataLayout());
3247 SDValue GA =
3248 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3249 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3250 return MatAddr;
3251 }
3252
3253 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3254 // The actual address of the GlobalValue is stored in the TOC.
3255 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3256 setUsesTOCBasePtr(DAG);
3257 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3258 return getTOCEntry(DAG, SDLoc(JT), GA);
3259 }
3260
3261 unsigned MOHiFlag, MOLoFlag;
3262 bool IsPIC = isPositionIndependent();
3263 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3264
3265 if (IsPIC && Subtarget.isSVR4ABI()) {
3266 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3267 PPCII::MO_PIC_FLAG);
3268 return getTOCEntry(DAG, SDLoc(GA), GA);
3269 }
3270
3271 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3272 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3273 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3274}
3275
3276SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3277 SelectionDAG &DAG) const {
3278 EVT PtrVT = Op.getValueType();
3279 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3280 const BlockAddress *BA = BASDN->getBlockAddress();
3281
3282 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3283 if (Subtarget.isUsingPCRelativeCalls()) {
3284 SDLoc DL(BASDN);
3285 EVT Ty = getPointerTy(DAG.getDataLayout());
3286 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3287 PPCII::MO_PCREL_FLAG);
3288 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3289 return MatAddr;
3290 }
3291
3292 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3293 // The actual BlockAddress is stored in the TOC.
3294 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3295 setUsesTOCBasePtr(DAG);
3296 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3297 return getTOCEntry(DAG, SDLoc(BASDN), GA);
3298 }
3299
3300 // 32-bit position-independent ELF stores the BlockAddress in the .got.
3301 if (Subtarget.is32BitELFABI() && isPositionIndependent())
3302 return getTOCEntry(
3303 DAG, SDLoc(BASDN),
3304 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3305
3306 unsigned MOHiFlag, MOLoFlag;
3307 bool IsPIC = isPositionIndependent();
3308 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3309 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3310 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3311 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3312}
3313
3314SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3315 SelectionDAG &DAG) const {
3316 if (Subtarget.isAIXABI())
3317 return LowerGlobalTLSAddressAIX(Op, DAG);
3318
3319 return LowerGlobalTLSAddressLinux(Op, DAG);
3320}
3321
3322SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3323 SelectionDAG &DAG) const {
3324 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3325
3326 if (DAG.getTarget().useEmulatedTLS())
3327 report_fatal_error("Emulated TLS is not yet supported on AIX");
3328
3329 SDLoc dl(GA);
3330 const GlobalValue *GV = GA->getGlobal();
3331 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3332
3333 // The general-dynamic model is the only access model supported for now, so
3334 // all the GlobalTLSAddress nodes are lowered with this model.
3335 // We need to generate two TOC entries, one for the variable offset, one for
3336 // the region handle. The global address for the TOC entry of the region
3337 // handle is created with the MO_TLSGDM_FLAG flag and the global address
3338 // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3339 SDValue VariableOffsetTGA =
3340 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3341 SDValue RegionHandleTGA =
3342 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3343 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3344 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3345 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3346 RegionHandle);
3347}
3348
3349SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3350 SelectionDAG &DAG) const {
3351 // FIXME: TLS addresses currently use medium model code sequences,
3352 // which is the most useful form. Eventually support for small and
3353 // large models could be added if users need it, at the cost of
3354 // additional complexity.
3355 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3356 if (DAG.getTarget().useEmulatedTLS())
3357 return LowerToTLSEmulatedModel(GA, DAG);
3358
3359 SDLoc dl(GA);
3360 const GlobalValue *GV = GA->getGlobal();
3361 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3362 bool is64bit = Subtarget.isPPC64();
3363 const Module *M = DAG.getMachineFunction().getFunction().getParent();
3364 PICLevel::Level picLevel = M->getPICLevel();
3365
3366 const TargetMachine &TM = getTargetMachine();
3367 TLSModel::Model Model = TM.getTLSModel(GV);
3368
3369 if (Model == TLSModel::LocalExec) {
3370 if (Subtarget.isUsingPCRelativeCalls()) {
3371 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3372 SDValue TGA = DAG.getTargetGlobalAddress(
3373 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3374 SDValue MatAddr =
3375 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3376 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3377 }
3378
3379 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3380 PPCII::MO_TPREL_HA);
3381 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3382 PPCII::MO_TPREL_LO);
3383 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3384 : DAG.getRegister(PPC::R2, MVT::i32);
3385
3386 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3387 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3388 }
3389
3390 if (Model == TLSModel::InitialExec) {
3391 bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3392 SDValue TGA = DAG.getTargetGlobalAddress(
3393 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3394 SDValue TGATLS = DAG.getTargetGlobalAddress(
3395 GV, dl, PtrVT, 0,
3396 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3397 SDValue TPOffset;
3398 if (IsPCRel) {
3399 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3400 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3401 MachinePointerInfo());
3402 } else {
3403 SDValue GOTPtr;
3404 if (is64bit) {
3405 setUsesTOCBasePtr(DAG);
3406 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3407 GOTPtr =
3408 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3409 } else {
3410 if (!TM.isPositionIndependent())
3411 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3412 else if (picLevel == PICLevel::SmallPIC)
3413 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3414 else
3415 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3416 }
3417 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3418 }
3419 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3420 }
3421
3422 if (Model == TLSModel::GeneralDynamic) {
3423 if (Subtarget.isUsingPCRelativeCalls()) {
3424 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3425 PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3426 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3427 }
3428
3429 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3430 SDValue GOTPtr;
3431 if (is64bit) {
3432 setUsesTOCBasePtr(DAG);
3433 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3434 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3435 GOTReg, TGA);
3436 } else {
3437 if (picLevel == PICLevel::SmallPIC)
3438 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3439 else
3440 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3441 }
3442 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3443 GOTPtr, TGA, TGA);
3444 }
3445
3446 if (Model == TLSModel::LocalDynamic) {
3447 if (Subtarget.isUsingPCRelativeCalls()) {
3448 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3449 PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3450 SDValue MatPCRel =
3451 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3452 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3453 }
3454
3455 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3456 SDValue GOTPtr;
3457 if (is64bit) {
3458 setUsesTOCBasePtr(DAG);
3459 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3460 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3461 GOTReg, TGA);
3462 } else {
3463 if (picLevel == PICLevel::SmallPIC)
3464 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3465 else
3466 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3467 }
3468 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3469 PtrVT, GOTPtr, TGA, TGA);
3470 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3471 PtrVT, TLSAddr, TGA);
3472 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3473 }
3474
3475 llvm_unreachable("Unknown TLS model!")::llvm::llvm_unreachable_internal("Unknown TLS model!", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3475)
;
3476}
3477
3478SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3479 SelectionDAG &DAG) const {
3480 EVT PtrVT = Op.getValueType();
3481 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3482 SDLoc DL(GSDN);
3483 const GlobalValue *GV = GSDN->getGlobal();
3484
3485 // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3486 // The actual address of the GlobalValue is stored in the TOC.
3487 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3488 if (Subtarget.isUsingPCRelativeCalls()) {
3489 EVT Ty = getPointerTy(DAG.getDataLayout());
3490 if (isAccessedAsGotIndirect(Op)) {
3491 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3492 PPCII::MO_PCREL_FLAG |
3493 PPCII::MO_GOT_FLAG);
3494 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3495 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3496 MachinePointerInfo());
3497 return Load;
3498 } else {
3499 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3500 PPCII::MO_PCREL_FLAG);
3501 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3502 }
3503 }
3504 setUsesTOCBasePtr(DAG);
3505 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3506 return getTOCEntry(DAG, DL, GA);
3507 }
3508
3509 unsigned MOHiFlag, MOLoFlag;
3510 bool IsPIC = isPositionIndependent();
3511 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3512
3513 if (IsPIC && Subtarget.isSVR4ABI()) {
3514 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3515 GSDN->getOffset(),
3516 PPCII::MO_PIC_FLAG);
3517 return getTOCEntry(DAG, DL, GA);
3518 }
3519
3520 SDValue GAHi =
3521 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3522 SDValue GALo =
3523 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3524
3525 return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3526}
3527
3528SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3529 bool IsStrict = Op->isStrictFPOpcode();
3530 ISD::CondCode CC =
3531 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3532 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3533 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3534 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3535 EVT LHSVT = LHS.getValueType();
3536 SDLoc dl(Op);
3537
3538 // Soften the setcc with libcall if it is fp128.
3539 if (LHSVT == MVT::f128) {
3540 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", 3541, __extension__
__PRETTY_FUNCTION__))
3541 "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", 3541, __extension__
__PRETTY_FUNCTION__))
;
3542 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3543 Op->getOpcode() == ISD::STRICT_FSETCCS);
3544 if (RHS.getNode())
3545 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3546 DAG.getCondCode(CC));
3547 if (IsStrict)
3548 return DAG.getMergeValues({LHS, Chain}, dl);
3549 return LHS;
3550 }
3551
3552 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", 3552, __extension__
__PRETTY_FUNCTION__))
;
3553
3554 if (Op.getValueType() == MVT::v2i64) {
3555 // When the operands themselves are v2i64 values, we need to do something
3556 // special because VSX has no underlying comparison operations for these.
3557 if (LHS.getValueType() == MVT::v2i64) {
3558 // Equality can be handled by casting to the legal type for Altivec
3559 // comparisons, everything else needs to be expanded.
3560 if (CC != ISD::SETEQ && CC != ISD::SETNE)
3561 return SDValue();
3562 SDValue SetCC32 = DAG.getSetCC(
3563 dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3564 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
3565 int ShuffV[] = {1, 0, 3, 2};
3566 SDValue Shuff =
3567 DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
3568 return DAG.getBitcast(MVT::v2i64,
3569 DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR,
3570 dl, MVT::v4i32, Shuff, SetCC32));
3571 }
3572
3573 // We handle most of these in the usual way.
3574 return Op;
3575 }
3576
3577 // If we're comparing for equality to zero, expose the fact that this is
3578 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3579 // fold the new nodes.
3580 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3581 return V;
3582
3583 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3584 // Leave comparisons against 0 and -1 alone for now, since they're usually
3585 // optimized. FIXME: revisit this when we can custom lower all setcc
3586 // optimizations.
3587 if (C->isAllOnes() || C->isZero())
3588 return SDValue();
3589 }
3590
3591 // If we have an integer seteq/setne, turn it into a compare against zero
3592 // by xor'ing the rhs with the lhs, which is faster than setting a
3593 // condition register, reading it back out, and masking the correct bit. The
3594 // normal approach here uses sub to do this instead of xor. Using xor exposes
3595 // the result to other bit-twiddling opportunities.
3596 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3597 EVT VT = Op.getValueType();
3598 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3599 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3600 }
3601 return SDValue();
3602}
3603
3604SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3605 SDNode *Node = Op.getNode();
3606 EVT VT = Node->getValueType(0);
3607 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3608 SDValue InChain = Node->getOperand(0);
3609 SDValue VAListPtr = Node->getOperand(1);
3610 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3611 SDLoc dl(Node);
3612
3613 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", 3613, __extension__
__PRETTY_FUNCTION__))
;
3614
3615 // gpr_index
3616 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3617 VAListPtr, MachinePointerInfo(SV), MVT::i8);
3618 InChain = GprIndex.getValue(1);
3619
3620 if (VT == MVT::i64) {
3621 // Check if GprIndex is even
3622 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3623 DAG.getConstant(1, dl, MVT::i32));
3624 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3625 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3626 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3627 DAG.getConstant(1, dl, MVT::i32));
3628 // Align GprIndex to be even if it isn't
3629 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3630 GprIndex);
3631 }
3632
3633 // fpr index is 1 byte after gpr
3634 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3635 DAG.getConstant(1, dl, MVT::i32));
3636
3637 // fpr
3638 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3639 FprPtr, MachinePointerInfo(SV), MVT::i8);
3640 InChain = FprIndex.getValue(1);
3641
3642 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3643 DAG.getConstant(8, dl, MVT::i32));
3644
3645 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3646 DAG.getConstant(4, dl, MVT::i32));
3647
3648 // areas
3649 SDValue OverflowArea =
3650 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3651 InChain = OverflowArea.getValue(1);
3652
3653 SDValue RegSaveArea =
3654 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3655 InChain = RegSaveArea.getValue(1);
3656
3657 // select overflow_area if index > 8
3658 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3659 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3660
3661 // adjustment constant gpr_index * 4/8
3662 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3663 VT.isInteger() ? GprIndex : FprIndex,
3664 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3665 MVT::i32));
3666
3667 // OurReg = RegSaveArea + RegConstant
3668 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3669 RegConstant);
3670
3671 // Floating types are 32 bytes into RegSaveArea
3672 if (VT.isFloatingPoint())
3673 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3674 DAG.getConstant(32, dl, MVT::i32));
3675
3676 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3677 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3678 VT.isInteger() ? GprIndex : FprIndex,
3679 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3680 MVT::i32));
3681
3682 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3683 VT.isInteger() ? VAListPtr : FprPtr,
3684 MachinePointerInfo(SV), MVT::i8);
3685
3686 // determine if we should load from reg_save_area or overflow_area
3687 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3688
3689 // increase overflow_area by 4/8 if gpr/fpr > 8
3690 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3691 DAG.getConstant(VT.isInteger() ? 4 : 8,
3692 dl, MVT::i32));
3693
3694 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3695 OverflowAreaPlusN);
3696
3697 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3698 MachinePointerInfo(), MVT::i32);
3699
3700 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3701}
3702
3703SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3704 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", 3704, __extension__
__PRETTY_FUNCTION__))
;
3705
3706 // We have to copy the entire va_list struct:
3707 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3708 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3709 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3710 false, true, false, MachinePointerInfo(),
3711 MachinePointerInfo());
3712}
3713
3714SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3715 SelectionDAG &DAG) const {
3716 if (Subtarget.isAIXABI())
3717 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3718
3719 return Op.getOperand(0);
3720}
3721
3722SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3723 MachineFunction &MF = DAG.getMachineFunction();
3724 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3725
3726 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", 3728, __extension__
__PRETTY_FUNCTION__))
3727 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", 3728, __extension__
__PRETTY_FUNCTION__))
3728 "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", 3728, __extension__
__PRETTY_FUNCTION__))
;
3729
3730 // If an LR store is already known to be required then there is not point in
3731 // checking this ASM as well.
3732 if (MFI.isLRStoreRequired())
3733 return Op;
3734
3735 // Inline ASM nodes have an optional last operand that is an incoming Flag of
3736 // type MVT::Glue. We want to ignore this last operand if that is the case.
3737 unsigned NumOps = Op.getNumOperands();
3738 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3739 --NumOps;
3740
3741 // Check all operands that may contain the LR.
3742 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3743 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3744 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3745 ++i; // Skip the ID value.
3746
3747 switch (InlineAsm::getKind(Flags)) {
3748 default:
3749 llvm_unreachable("Bad flags!")::llvm::llvm_unreachable_internal("Bad flags!", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3749)
;
3750 case InlineAsm::Kind_RegUse:
3751 case InlineAsm::Kind_Imm:
3752 case InlineAsm::Kind_Mem:
3753 i += NumVals;
3754 break;
3755 case InlineAsm::Kind_Clobber:
3756 case InlineAsm::Kind_RegDef:
3757 case InlineAsm::Kind_RegDefEarlyClobber: {
3758 for (; NumVals; --NumVals, ++i) {
3759 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3760 if (Reg != PPC::LR && Reg != PPC::LR8)
3761 continue;
3762 MFI.setLRStoreRequired();
3763 return Op;
3764 }
3765 break;
3766 }
3767 }
3768 }
3769
3770 return Op;
3771}
3772
3773SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3774 SelectionDAG &DAG) const {
3775 if (Subtarget.isAIXABI())
3776 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3777
3778 SDValue Chain = Op.getOperand(0);
3779 SDValue Trmp = Op.getOperand(1); // trampoline
3780 SDValue FPtr = Op.getOperand(2); // nested function
3781 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3782 SDLoc dl(Op);
3783
3784 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3785 bool isPPC64 = (PtrVT == MVT::i64);
3786 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3787
3788 TargetLowering::ArgListTy Args;
3789 TargetLowering::ArgListEntry Entry;
3790
3791 Entry.Ty = IntPtrTy;
3792 Entry.Node = Trmp; Args.push_back(Entry);
3793
3794 // TrampSize == (isPPC64 ? 48 : 40);
3795 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3796 isPPC64 ? MVT::i64 : MVT::i32);
3797 Args.push_back(Entry);
3798
3799 Entry.Node = FPtr; Args.push_back(Entry);
3800 Entry.Node = Nest; Args.push_back(Entry);
3801
3802 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3803 TargetLowering::CallLoweringInfo CLI(DAG);
3804 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3805 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3806 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3807
3808 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3809 return CallResult.second;
3810}
3811
3812SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3813 MachineFunction &MF = DAG.getMachineFunction();
3814 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3815 EVT PtrVT = getPointerTy(MF.getDataLayout());
3816
3817 SDLoc dl(Op);
3818
3819 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3820 // vastart just stores the address of the VarArgsFrameIndex slot into the
3821 // memory location argument.
3822 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3823 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3824 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3825 MachinePointerInfo(SV));
3826 }
3827
3828 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3829 // We suppose the given va_list is already allocated.
3830 //
3831 // typedef struct {
3832 // char gpr; /* index into the array of 8 GPRs
3833 // * stored in the register save area
3834 // * gpr=0 corresponds to r3,
3835 // * gpr=1 to r4, etc.
3836 // */
3837 // char fpr; /* index into the array of 8 FPRs
3838 // * stored in the register save area
3839 // * fpr=0 corresponds to f1,
3840 // * fpr=1 to f2, etc.
3841 // */
3842 // char *overflow_arg_area;
3843 // /* location on stack that holds
3844 // * the next overflow argument
3845 // */
3846 // char *reg_save_area;
3847 // /* where r3:r10 and f1:f8 (if saved)
3848 // * are stored
3849 // */
3850 // } va_list[1];
3851
3852 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3853 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3854 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3855 PtrVT);
3856 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3857 PtrVT);
3858
3859 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3860 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3861
3862 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3863 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3864
3865 uint64_t FPROffset = 1;
3866 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3867
3868 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3869
3870 // Store first byte : number of int regs
3871 SDValue firstStore =
3872 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3873 MachinePointerInfo(SV), MVT::i8);
3874 uint64_t nextOffset = FPROffset;
3875 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3876 ConstFPROffset);
3877
3878 // Store second byte : number of float regs
3879 SDValue secondStore =
3880 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3881 MachinePointerInfo(SV, nextOffset), MVT::i8);
3882 nextOffset += StackOffset;
3883 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3884
3885 // Store second word : arguments given on stack
3886 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3887 MachinePointerInfo(SV, nextOffset));
3888 nextOffset += FrameOffset;
3889 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3890
3891 // Store third word : arguments given in registers
3892 return DAG.getStore(thirdStore, dl, FR, nextPtr,
3893 MachinePointerInfo(SV, nextOffset));
3894}
3895
3896/// FPR - The set of FP registers that should be allocated for arguments
3897/// on Darwin and AIX.
3898static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
3899 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
3900 PPC::F11, PPC::F12, PPC::F13};
3901
3902/// CalculateStackSlotSize - Calculates the size reserved for this argument on
3903/// the stack.
3904static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3905 unsigned PtrByteSize) {
3906 unsigned ArgSize = ArgVT.getStoreSize();
3907 if (Flags.isByVal())
3908 ArgSize = Flags.getByValSize();
3909
3910 // Round up to multiples of the pointer size, except for array members,
3911 // which are always packed.
3912 if (!Flags.isInConsecutiveRegs())
3913 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3914
3915 return ArgSize;
3916}
3917
3918/// CalculateStackSlotAlignment - Calculates the alignment of this argument
3919/// on the stack.
3920static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3921 ISD::ArgFlagsTy Flags,
3922 unsigned PtrByteSize) {
3923 Align Alignment(PtrByteSize);
3924
3925 // Altivec parameters are padded to a 16 byte boundary.
3926 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3927 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3928 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3929 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3930 Alignment = Align(16);
3931
3932 // ByVal parameters are aligned as requested.
3933 if (Flags.isByVal()) {
3934 auto BVAlign = Flags.getNonZeroByValAlign();
3935 if (BVAlign > PtrByteSize) {
3936 if (BVAlign.value() % PtrByteSize != 0)
3937 llvm_unreachable(::llvm::llvm_unreachable_internal("ByVal alignment is not a multiple of the pointer size"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 3938)
3938 "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", 3938)
;
3939
3940 Alignment = BVAlign;
3941 }
3942 }
3943
3944 // Array members are always packed to their original alignment.
3945 if (Flags.isInConsecutiveRegs()) {
3946 // If the array member was split into multiple registers, the first
3947 // needs to be aligned to the size of the full type. (Except for
3948 // ppcf128, which is only aligned as its f64 components.)
3949 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3950 Alignment = Align(OrigVT.getStoreSize());
3951 else
3952 Alignment = Align(ArgVT.getStoreSize());
3953 }
3954
3955 return Alignment;
3956}
3957
3958/// CalculateStackSlotUsed - Return whether this argument will use its
3959/// stack slot (instead of being passed in registers). ArgOffset,
3960/// AvailableFPRs, and AvailableVRs must hold the current argument
3961/// position, and will be updated to account for this argument.
3962static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3963 unsigned PtrByteSize, unsigned LinkageSize,
3964 unsigned ParamAreaSize, unsigned &ArgOffset,
3965 unsigned &AvailableFPRs,
3966 unsigned &AvailableVRs) {
3967 bool UseMemory = false;
3968
3969 // Respect alignment of argument on the stack.
3970 Align Alignment =
3971 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3972 ArgOffset = alignTo(ArgOffset, Alignment);
3973 // If there's no space left in the argument save area, we must
3974 // use memory (this check also catches zero-sized arguments).
3975 if (ArgOffset >= LinkageSize + ParamAreaSize)
3976 UseMemory = true;
3977
3978 // Allocate argument on the stack.
3979 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3980 if (Flags.isInConsecutiveRegsLast())
3981 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3982 // If we overran the argument save area, we must use memory
3983 // (this check catches arguments passed partially in memory)
3984 if (ArgOffset > LinkageSize + ParamAreaSize)
3985 UseMemory = true;
3986
3987 // However, if the argument is actually passed in an FPR or a VR,
3988 // we don't use memory after all.
3989 if (!Flags.isByVal()) {
3990 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3991 if (AvailableFPRs > 0) {
3992 --AvailableFPRs;
3993 return false;
3994 }
3995 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3996 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3997 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3998 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3999 if (AvailableVRs > 0) {
4000 --AvailableVRs;
4001 return false;
4002 }
4003 }
4004
4005 return UseMemory;
4006}
4007
4008/// EnsureStackAlignment - Round stack frame size up from NumBytes to
4009/// ensure minimum alignment required for target.
4010static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
4011 unsigned NumBytes) {
4012 return alignTo(NumBytes, Lowering->getStackAlign());
4013}
4014
4015SDValue PPCTargetLowering::LowerFormalArguments(
4016 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4017 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4018 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4019 if (Subtarget.isAIXABI())
4020 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
4021 InVals);
4022 if (Subtarget.is64BitELFABI())
4023 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
4024 InVals);
4025 assert(Subtarget.is32BitELFABI())(static_cast <bool> (Subtarget.is32BitELFABI()) ? void (
0) : __assert_fail ("Subtarget.is32BitELFABI()", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4025, __extension__ __PRETTY_FUNCTION__))
;
4026 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
4027 InVals);
4028}
4029
4030SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
4031 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4032 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4033 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4034
4035 // 32-bit SVR4 ABI Stack Frame Layout:
4036 // +-----------------------------------+
4037 // +--> | Back chain |
4038 // | +-----------------------------------+
4039 // | | Floating-point register save area |
4040 // | +-----------------------------------+
4041 // | | General register save area |
4042 // | +-----------------------------------+
4043 // | | CR save word |
4044 // | +-----------------------------------+
4045 // | | VRSAVE save word |
4046 // | +-----------------------------------+
4047 // | | Alignment padding |
4048 // | +-----------------------------------+
4049 // | | Vector register save area |
4050 // | +-----------------------------------+
4051 // | | Local variable space |
4052 // | +-----------------------------------+
4053 // | | Parameter list area |
4054 // | +-----------------------------------+
4055 // | | LR save word |
4056 // | +-----------------------------------+
4057 // SP--> +--- | Back chain |
4058 // +-----------------------------------+
4059 //
4060 // Specifications:
4061 // System V Application Binary Interface PowerPC Processor Supplement
4062 // AltiVec Technology Programming Interface Manual
4063
4064 MachineFunction &MF = DAG.getMachineFunction();
4065 MachineFrameInfo &MFI = MF.getFrameInfo();
4066 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4067
4068 EVT PtrVT = getPointerTy(MF.getDataLayout());
4069 // Potential tail calls could cause overwriting of argument stack slots.
4070 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4071 (CallConv == CallingConv::Fast));
4072 const Align PtrAlign(4);
4073
4074 // Assign locations to all of the incoming arguments.
4075 SmallVector<CCValAssign, 16> ArgLocs;
4076 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4077 *DAG.getContext());
4078
4079 // Reserve space for the linkage area on the stack.
4080 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4081 CCInfo.AllocateStack(LinkageSize, PtrAlign);
4082 if (useSoftFloat())
4083 CCInfo.PreAnalyzeFormalArguments(Ins);
4084
4085 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4086 CCInfo.clearWasPPCF128();
4087
4088 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4089 CCValAssign &VA = ArgLocs[i];
4090
4091 // Arguments stored in registers.
4092 if (VA.isRegLoc()) {
4093 const TargetRegisterClass *RC;
4094 EVT ValVT = VA.getValVT();
4095
4096 switch (ValVT.getSimpleVT().SimpleTy) {
4097 default:
4098 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", 4098)
;
4099 case MVT::i1:
4100 case MVT::i32:
4101 RC = &PPC::GPRCRegClass;
4102 break;
4103 case MVT::f32:
4104 if (Subtarget.hasP8Vector())
4105 RC = &PPC::VSSRCRegClass;
4106 else if (Subtarget.hasSPE())
4107 RC = &PPC::GPRCRegClass;
4108 else
4109 RC = &PPC::F4RCRegClass;
4110 break;
4111 case MVT::f64:
4112 if (Subtarget.hasVSX())
4113 RC = &PPC::VSFRCRegClass;
4114 else if (Subtarget.hasSPE())
4115 // SPE passes doubles in GPR pairs.
4116 RC = &PPC::GPRCRegClass;
4117 else
4118 RC = &PPC::F8RCRegClass;
4119 break;
4120 case MVT::v16i8:
4121 case MVT::v8i16:
4122 case MVT::v4i32:
4123 RC = &PPC::VRRCRegClass;
4124 break;
4125 case MVT::v4f32:
4126 RC = &PPC::VRRCRegClass;
4127 break;
4128 case MVT::v2f64:
4129 case MVT::v2i64:
4130 RC = &PPC::VRRCRegClass;
4131 break;
4132 }
4133
4134 SDValue ArgValue;
4135 // Transform the arguments stored in physical registers into
4136 // virtual ones.
4137 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4138 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", 4138, __extension__
__PRETTY_FUNCTION__))
;
4139 Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4140 Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4141 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4142 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4143 if (!Subtarget.isLittleEndian())
4144 std::swap (ArgValueLo, ArgValueHi);
4145 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4146 ArgValueHi);
4147 } else {
4148 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4149 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4150 ValVT == MVT::i1 ? MVT::i32 : ValVT);
4151 if (ValVT == MVT::i1)
4152 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4153 }
4154
4155 InVals.push_back(ArgValue);
4156 } else {
4157 // Argument stored in memory.
4158 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4158, __extension__ __PRETTY_FUNCTION__))
;
4159
4160 // Get the extended size of the argument type in stack
4161 unsigned ArgSize = VA.getLocVT().getStoreSize();
4162 // Get the actual size of the argument type
4163 unsigned ObjSize = VA.getValVT().getStoreSize();
4164 unsigned ArgOffset = VA.getLocMemOffset();
4165 // Stack objects in PPC32 are right justified.
4166 ArgOffset += ArgSize - ObjSize;
4167 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4168
4169 // Create load nodes to retrieve arguments from the stack.
4170 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4171 InVals.push_back(
4172 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4173 }
4174 }
4175
4176 // Assign locations to all of the incoming aggregate by value arguments.
4177 // Aggregates passed by value are stored in the local variable space of the
4178 // caller's stack frame, right above the parameter list area.
4179 SmallVector<CCValAssign, 16> ByValArgLocs;
4180 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4181 ByValArgLocs, *DAG.getContext());
4182
4183 // Reserve stack space for the allocations in CCInfo.
4184 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4185
4186 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4187
4188 // Area that is at least reserved in the caller of this function.
4189 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4190 MinReservedArea = std::max(MinReservedArea, LinkageSize);
4191
4192 // Set the size that is at least reserved in caller of this function. Tail
4193 // call optimized function's reserved stack space needs to be aligned so that
4194 // taking the difference between two stack areas will result in an aligned
4195 // stack.
4196 MinReservedArea =
4197 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4198 FuncInfo->setMinReservedArea(MinReservedArea);
4199
4200 SmallVector<SDValue, 8> MemOps;
4201
4202 // If the function takes variable number of arguments, make a frame index for
4203 // the start of the first vararg value... for expansion of llvm.va_start.
4204 if (isVarArg) {
4205 static const MCPhysReg GPArgRegs[] = {
4206 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4207 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4208 };
4209 const unsigned NumGPArgRegs = std::size(GPArgRegs);
4210
4211 static const MCPhysReg FPArgRegs[] = {
4212 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4213 PPC::F8
4214 };
4215 unsigned NumFPArgRegs = std::size(FPArgRegs);
4216
4217 if (useSoftFloat() || hasSPE())
4218 NumFPArgRegs = 0;
4219
4220 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4221 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4222
4223 // Make room for NumGPArgRegs and NumFPArgRegs.
4224 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4225 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4226
4227 FuncInfo->setVarArgsStackOffset(
4228 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4229 CCInfo.getNextStackOffset(), true));
4230
4231 FuncInfo->setVarArgsFrameIndex(
4232 MFI.CreateStackObject(Depth, Align(8), false));
4233 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4234
4235 // The fixed integer arguments of a variadic function are stored to the
4236 // VarArgsFrameIndex on the stack so that they may be loaded by
4237 // dereferencing the result of va_next.
4238 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4239 // Get an existing live-in vreg, or add a new one.
4240 Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4241 if (!VReg)
4242 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4243
4244 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4245 SDValue Store =
4246 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4247 MemOps.push_back(Store);
4248 // Increment the address by four for the next argument to store
4249 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4250 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4251 }
4252
4253 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4254 // is set.
4255 // The double arguments are stored to the VarArgsFrameIndex
4256 // on the stack.
4257 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4258 // Get an existing live-in vreg, or add a new one.
4259 Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4260 if (!VReg)
4261 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4262
4263 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4264 SDValue Store =
4265 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4266 MemOps.push_back(Store);
4267 // Increment the address by eight for the next argument to store
4268 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4269 PtrVT);
4270 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4271 }
4272 }
4273
4274 if (!MemOps.empty())
4275 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4276
4277 return Chain;
4278}
4279
4280// PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4281// value to MVT::i64 and then truncate to the correct register size.
4282SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4283 EVT ObjectVT, SelectionDAG &DAG,
4284 SDValue ArgVal,
4285 const SDLoc &dl) const {
4286 if (Flags.isSExt())
4287 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4288 DAG.getValueType(ObjectVT));
4289 else if (Flags.isZExt())
4290 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4291 DAG.getValueType(ObjectVT));
4292
4293 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4294}
4295
4296SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4297 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4298 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4299 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4300 // TODO: add description of PPC stack frame format, or at least some docs.
4301 //
4302 bool isELFv2ABI = Subtarget.isELFv2ABI();
4303 bool isLittleEndian = Subtarget.isLittleEndian();
4304 MachineFunction &MF = DAG.getMachineFunction();
4305 MachineFrameInfo &MFI = MF.getFrameInfo();
4306 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4307
4308 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", 4309, __extension__
__PRETTY_FUNCTION__))
4309 "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", 4309, __extension__
__PRETTY_FUNCTION__))
;
4310
4311 EVT PtrVT = getPointerTy(MF.getDataLayout());
4312 // Potential tail calls could cause overwriting of argument stack slots.
4313 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4314 (CallConv == CallingConv::Fast));
4315 unsigned PtrByteSize = 8;
4316 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4317
4318 static const MCPhysReg GPR[] = {
4319 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4320 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4321 };
4322 static const MCPhysReg VR[] = {
4323 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4324 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4325 };
4326
4327 const unsigned Num_GPR_Regs = std::size(GPR);
4328 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4329 const unsigned Num_VR_Regs = std::size(VR);
4330
4331 // Do a first pass over the arguments to determine whether the ABI
4332 // guarantees that our caller has allocated the parameter save area
4333 // on its stack frame. In the ELFv1 ABI, this is always the case;
4334 // in the ELFv2 ABI, it is true if this is a vararg function or if
4335 // any parameter is located in a stack slot.
4336
4337 bool HasParameterArea = !isELFv2ABI || isVarArg;
4338 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4339 unsigned NumBytes = LinkageSize;
4340 unsigned AvailableFPRs = Num_FPR_Regs;
4341 unsigned AvailableVRs = Num_VR_Regs;
4342 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4343 if (Ins[i].Flags.isNest())
4344 continue;
4345
4346 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4347 PtrByteSize, LinkageSize, ParamAreaSize,
4348 NumBytes, AvailableFPRs, AvailableVRs))
4349 HasParameterArea = true;
4350 }
4351
4352 // Add DAG nodes to load the arguments or copy them out of registers. On
4353 // entry to a function on PPC, the arguments start after the linkage area,
4354 // although the first ones are often in registers.
4355
4356 unsigned ArgOffset = LinkageSize;
4357 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4358 SmallVector<SDValue, 8> MemOps;
4359 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4360 unsigned CurArgIdx = 0;
4361 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4362 SDValue ArgVal;
4363 bool needsLoad = false;
4364 EVT ObjectVT = Ins[ArgNo].VT;
4365 EVT OrigVT = Ins[ArgNo].ArgVT;
4366 unsigned ObjSize = ObjectVT.getStoreSize();
4367 unsigned ArgSize = ObjSize;
4368 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4369 if (Ins[ArgNo].isOrigArg()) {
4370 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4371 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4372 }
4373 // We re-align the argument offset for each argument, except when using the
4374 // fast calling convention, when we need to make sure we do that only when
4375 // we'll actually use a stack slot.
4376 unsigned CurArgOffset;
4377 Align Alignment;
4378 auto ComputeArgOffset = [&]() {
4379 /* Respect alignment of argument on the stack. */
4380 Alignment =
4381 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4382 ArgOffset = alignTo(ArgOffset, Alignment);
4383 CurArgOffset = ArgOffset;
4384 };
4385
4386 if (CallConv != CallingConv::Fast) {
4387 ComputeArgOffset();
4388
4389 /* Compute GPR index associated with argument offset. */
4390 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4391 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4392 }
4393
4394 // FIXME the codegen can be much improved in some cases.
4395 // We do not have to keep everything in memory.
4396 if (Flags.isByVal()) {
4397 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", 4397, __extension__
__PRETTY_FUNCTION__))
;
4398
4399 if (CallConv == CallingConv::Fast)
4400 ComputeArgOffset();
4401
4402 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4403 ObjSize = Flags.getByValSize();
4404 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4405 // Empty aggregate parameters do not take up registers. Examples:
4406 // struct { } a;
4407 // union { } b;
4408 // int c[0];
4409 // etc. However, we have to provide a place-holder in InVals, so
4410 // pretend we have an 8-byte item at the current address for that
4411 // purpose.
4412 if (!ObjSize) {
4413 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4414 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4415 InVals.push_back(FIN);
4416 continue;
4417 }
4418
4419 // Create a stack object covering all stack doublewords occupied
4420 // by the argument. If the argument is (fully or partially) on
4421 // the stack, or if the argument is fully in registers but the
4422 // caller has allocated the parameter save anyway, we can refer
4423 // directly to the caller's stack frame. Otherwise, create a
4424 // local copy in our own frame.
4425 int FI;
4426 if (HasParameterArea ||
4427 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4428 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4429 else
4430 FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4431 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4432
4433 // Handle aggregates smaller than 8 bytes.
4434 if (ObjSize < PtrByteSize) {
4435 // The value of the object is its address, which differs from the
4436 // address of the enclosing doubleword on big-endian systems.
4437 SDValue Arg = FIN;
4438 if (!isLittleEndian) {
4439 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4440 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4441 }
4442 InVals.push_back(Arg);
4443
4444 if (GPR_idx != Num_GPR_Regs) {
4445 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4446 FuncInfo->addLiveInAttr(VReg, Flags);
4447 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4448 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4449 SDValue Store =
4450 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4451 MachinePointerInfo(&*FuncArg), ObjType);
4452 MemOps.push_back(Store);
4453 }
4454 // Whether we copied from a register or not, advance the offset
4455 // into the parameter save area by a full doubleword.
4456 ArgOffset += PtrByteSize;
4457 continue;
4458 }
4459
4460 // The value of the object is its address, which is the address of
4461 // its first stack doubleword.
4462 InVals.push_back(FIN);
4463
4464 // Store whatever pieces of the object are in registers to memory.
4465 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4466 if (GPR_idx == Num_GPR_Regs)
4467 break;
4468
4469 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4470 FuncInfo->addLiveInAttr(VReg, Flags);
4471 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4472 SDValue Addr = FIN;
4473 if (j) {
4474 SDValue Off = DAG.getConstant(j, dl, PtrVT);
4475 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4476 }
4477 unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8;
4478 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits);
4479 SDValue Store =
4480 DAG.getTruncStore(Val.getValue(1), dl, Val, Addr,
4481 MachinePointerInfo(&*FuncArg, j), ObjType);
4482 MemOps.push_back(Store);
4483 ++GPR_idx;
4484 }
4485 ArgOffset += ArgSize;
4486 continue;
4487 }
4488
4489 switch (ObjectVT.getSimpleVT().SimpleTy) {
4490 default: llvm_unreachable("Unhandled argument type!")::llvm::llvm_unreachable_internal("Unhandled argument type!",
"llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 4490)
;
4491 case MVT::i1:
4492 case MVT::i32:
4493 case MVT::i64:
4494 if (Flags.isNest()) {
4495 // The 'nest' parameter, if any, is passed in R11.
4496 Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4497 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4498
4499 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4500 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4501
4502 break;
4503 }
4504
4505 // These can be scalar arguments or elements of an integer array type
4506 // passed directly. Clang may use those instead of "byval" aggregate
4507 // types to avoid forcing arguments to memory unnecessarily.
4508 if (GPR_idx != Num_GPR_Regs) {
4509 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4510 FuncInfo->addLiveInAttr(VReg, Flags);
4511 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4512
4513 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4514 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4515 // value to MVT::i64 and then truncate to the correct register size.
4516 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4517 } else {
4518 if (CallConv == CallingConv::Fast)
4519 ComputeArgOffset();
4520
4521 needsLoad = true;
4522 ArgSize = PtrByteSize;
4523 }
4524 if (CallConv != CallingConv::Fast || needsLoad)
4525 ArgOffset += 8;
4526 break;
4527
4528 case MVT::f32:
4529 case MVT::f64:
4530 // These can be scalar arguments or elements of a float array type
4531 // passed directly. The latter are used to implement ELFv2 homogenous
4532 // float aggregates.
4533 if (FPR_idx != Num_FPR_Regs) {
4534 unsigned VReg;
4535
4536 if (ObjectVT == MVT::f32)
4537 VReg = MF.addLiveIn(FPR[FPR_idx],
4538 Subtarget.hasP8Vector()
4539 ? &PPC::VSSRCRegClass
4540 : &PPC::F4RCRegClass);
4541 else
4542 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4543 ? &PPC::VSFRCRegClass
4544 : &PPC::F8RCRegClass);
4545
4546 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4547 ++FPR_idx;
4548 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4549 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4550 // once we support fp <-> gpr moves.
4551
4552 // This can only ever happen in the presence of f32 array types,
4553 // since otherwise we never run out of FPRs before running out
4554 // of GPRs.
4555 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4556 FuncInfo->addLiveInAttr(VReg, Flags);
4557 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4558
4559 if (ObjectVT == MVT::f32) {
4560 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4561 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4562 DAG.getConstant(32, dl, MVT::i32));
4563 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4564 }
4565
4566 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4567 } else {
4568 if (CallConv == CallingConv::Fast)
4569 ComputeArgOffset();
4570
4571 needsLoad = true;
4572 }
4573
4574 // When passing an array of floats, the array occupies consecutive
4575 // space in the argument area; only round up to the next doubleword
4576 // at the end of the array. Otherwise, each float takes 8 bytes.
4577 if (CallConv != CallingConv::Fast || needsLoad) {
4578 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4579 ArgOffset += ArgSize;
4580 if (Flags.isInConsecutiveRegsLast())
4581 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4582 }
4583 break;
4584 case MVT::v4f32:
4585 case MVT::v4i32:
4586 case MVT::v8i16:
4587 case MVT::v16i8:
4588 case MVT::v2f64:
4589 case MVT::v2i64:
4590 case MVT::v1i128:
4591 case MVT::f128:
4592 // These can be scalar arguments or elements of a vector array type
4593 // passed directly. The latter are used to implement ELFv2 homogenous
4594 // vector aggregates.
4595 if (VR_idx != Num_VR_Regs) {
4596 Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4597 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4598 ++VR_idx;
4599 } else {
4600 if (CallConv == CallingConv::Fast)
4601 ComputeArgOffset();
4602 needsLoad = true;
4603 }
4604 if (CallConv != CallingConv::Fast || needsLoad)
4605 ArgOffset += 16;
4606 break;
4607 }
4608
4609 // We need to load the argument to a virtual register if we determined
4610 // above that we ran out of physical registers of the appropriate type.
4611 if (needsLoad) {
4612 if (ObjSize < ArgSize && !isLittleEndian)
4613 CurArgOffset += ArgSize - ObjSize;
4614 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4615 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4616 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4617 }
4618
4619 InVals.push_back(ArgVal);
4620 }
4621
4622 // Area that is at least reserved in the caller of this function.
4623 unsigned MinReservedArea;
4624 if (HasParameterArea)
4625 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4626 else
4627 MinReservedArea = LinkageSize;
4628
4629 // Set the size that is at least reserved in caller of this function. Tail
4630 // call optimized functions' reserved stack space needs to be aligned so that
4631 // taking the difference between two stack areas will result in an aligned
4632 // stack.
4633 MinReservedArea =
4634 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4635 FuncInfo->setMinReservedArea(MinReservedArea);
4636
4637 // If the function takes variable number of arguments, make a frame index for
4638 // the start of the first vararg value... for expansion of llvm.va_start.
4639 // On ELFv2ABI spec, it writes:
4640 // C programs that are intended to be *portable* across different compilers
4641 // and architectures must use the header file <stdarg.h> to deal with variable
4642 // argument lists.
4643 if (isVarArg && MFI.hasVAStart()) {
4644 int Depth = ArgOffset;
4645
4646 FuncInfo->setVarArgsFrameIndex(
4647 MFI.CreateFixedObject(PtrByteSize, Depth, true));
4648 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4649
4650 // If this function is vararg, store any remaining integer argument regs
4651 // to their spots on the stack so that they may be loaded by dereferencing
4652 // the result of va_next.
4653 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4654 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4655 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4656 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4657 SDValue Store =
4658 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4659 MemOps.push_back(Store);
4660 // Increment the address by four for the next argument to store
4661 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4662 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4663 }
4664 }
4665
4666 if (!MemOps.empty())
4667 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4668
4669 return Chain;
4670}
4671
4672/// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4673/// adjusted to accommodate the arguments for the tailcall.
4674static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4675 unsigned ParamSize) {
4676
4677 if (!isTailCall) return 0;
4678
4679 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4680 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4681 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4682 // Remember only if the new adjustment is bigger.
4683 if (SPDiff < FI->getTailCallSPDelta())
4684 FI->setTailCallSPDelta(SPDiff);
4685
4686 return SPDiff;
4687}
4688
4689static bool isFunctionGlobalAddress(const GlobalValue *CalleeGV);
4690
4691static bool callsShareTOCBase(const Function *Caller,
4692 const GlobalValue *CalleeGV,
4693 const TargetMachine &TM) {
4694 // It does not make sense to call callsShareTOCBase() with a caller that
4695 // is PC Relative since PC Relative callers do not have a TOC.
4696#ifndef NDEBUG
4697 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4698 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", 4699, __extension__
__PRETTY_FUNCTION__))
4699 "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", 4699, __extension__
__PRETTY_FUNCTION__))
;
4700#endif
4701
4702 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4703 // don't have enough information to determine if the caller and callee share
4704 // the same TOC base, so we have to pessimistically assume they don't for
4705 // correctness.
4706 if (!CalleeGV)
4707 return false;
4708
4709 // If the callee is preemptable, then the static linker will use a plt-stub
4710 // which saves the toc to the stack, and needs a nop after the call
4711 // instruction to convert to a toc-restore.
4712 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), CalleeGV))
4713 return false;
4714
4715 // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4716 // We may need a TOC restore in the situation where the caller requires a
4717 // valid TOC but the callee is PC Relative and does not.
4718 const Function *F = dyn_cast<Function>(CalleeGV);
4719 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(CalleeGV);
4720
4721 // If we have an Alias we can try to get the function from there.
4722 if (Alias) {
4723 const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4724 F = dyn_cast<Function>(GlobalObj);
4725 }
4726
4727 // If we still have no valid function pointer we do not have enough
4728 // information to determine if the callee uses PC Relative calls so we must
4729 // assume that it does.
4730 if (!F)
4731 return false;
4732
4733 // If the callee uses PC Relative we cannot guarantee that the callee won't
4734 // clobber the TOC of the caller and so we must assume that the two
4735 // functions do not share a TOC base.
4736 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4737 if (STICallee->isUsingPCRelativeCalls())
4738 return false;
4739
4740 // If the GV is not a strong definition then we need to assume it can be
4741 // replaced by another function at link time. The function that replaces
4742 // it may not share the same TOC as the caller since the callee may be
4743 // replaced by a PC Relative version of the same function.
4744 if (!CalleeGV->isStrongDefinitionForLinker())
4745 return false;
4746
4747 // The medium and large code models are expected to provide a sufficiently
4748 // large TOC to provide all data addressing needs of a module with a
4749 // single TOC.
4750 if (CodeModel::Medium == TM.getCodeModel() ||
4751 CodeModel::Large == TM.getCodeModel())
4752 return true;
4753
4754 // Any explicitly-specified sections and section prefixes must also match.
4755 // Also, if we're using -ffunction-sections, then each function is always in
4756 // a different section (the same is true for COMDAT functions).
4757 if (TM.getFunctionSections() || CalleeGV->hasComdat() ||
4758 Caller->hasComdat() || CalleeGV->getSection() != Caller->getSection())
4759 return false;
4760 if (const auto *F = dyn_cast<Function>(CalleeGV)) {
4761 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4762 return false;
4763 }
4764
4765 return true;
4766}
4767
4768static bool
4769needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4770 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4771 assert(Subtarget.is64BitELFABI())(static_cast <bool> (Subtarget.is64BitELFABI()) ? void (
0) : __assert_fail ("Subtarget.is64BitELFABI()", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4771, __extension__ __PRETTY_FUNCTION__))
;
4772
4773 const unsigned PtrByteSize = 8;
4774 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4775
4776 static const MCPhysReg GPR[] = {
4777 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4778 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4779 };
4780 static const MCPhysReg VR[] = {
4781 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4782 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4783 };
4784
4785 const unsigned NumGPRs = std::size(GPR);
4786 const unsigned NumFPRs = 13;
4787 const unsigned NumVRs = std::size(VR);
4788 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4789
4790 unsigned NumBytes = LinkageSize;
4791 unsigned AvailableFPRs = NumFPRs;
4792 unsigned AvailableVRs = NumVRs;
4793
4794 for (const ISD::OutputArg& Param : Outs) {
4795 if (Param.Flags.isNest()) continue;
4796
4797 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4798 LinkageSize, ParamAreaSize, NumBytes,
4799 AvailableFPRs, AvailableVRs))
4800 return true;
4801 }
4802 return false;
4803}
4804
4805static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4806 if (CB.arg_size() != CallerFn->arg_size())
4807 return false;
4808
4809 auto CalleeArgIter = CB.arg_begin();
4810 auto CalleeArgEnd = CB.arg_end();
4811 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4812
4813 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4814 const Value* CalleeArg = *CalleeArgIter;
4815 const Value* CallerArg = &(*CallerArgIter);
4816 if (CalleeArg == CallerArg)
4817 continue;
4818
4819 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4820 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4821 // }
4822 // 1st argument of callee is undef and has the same type as caller.
4823 if (CalleeArg->getType() == CallerArg->getType() &&
4824 isa<UndefValue>(CalleeArg))
4825 continue;
4826
4827 return false;
4828 }
4829
4830 return true;
4831}
4832
4833// Returns true if TCO is possible between the callers and callees
4834// calling conventions.
4835static bool
4836areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4837 CallingConv::ID CalleeCC) {
4838 // Tail calls are possible with fastcc and ccc.
4839 auto isTailCallableCC = [] (CallingConv::ID CC){
4840 return CC == CallingConv::C || CC == CallingConv::Fast;
4841 };
4842 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4843 return false;
4844
4845 // We can safely tail call both fastcc and ccc callees from a c calling
4846 // convention caller. If the caller is fastcc, we may have less stack space
4847 // than a non-fastcc caller with the same signature so disable tail-calls in
4848 // that case.
4849 return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4850}
4851
4852bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4853 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
4854 CallingConv::ID CallerCC, const CallBase *CB, bool isVarArg,
4855 const SmallVectorImpl<ISD::OutputArg> &Outs,
4856 const SmallVectorImpl<ISD::InputArg> &Ins, const Function *CallerFunc,
4857 bool isCalleeExternalSymbol) const {
4858 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4859
4860 if (DisableSCO && !TailCallOpt) return false;
4861
4862 // Variadic argument functions are not supported.
4863 if (isVarArg) return false;
4864
4865 // Check that the calling conventions are compatible for tco.
4866 if (!areCallingConvEligibleForTCO_64SVR4(CallerCC, CalleeCC))
4867 return false;
4868
4869 // Caller contains any byval parameter is not supported.
4870 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4871 return false;
4872
4873 // Callee contains any byval parameter is not supported, too.
4874 // Note: This is a quick work around, because in some cases, e.g.
4875 // caller's stack size > callee's stack size, we are still able to apply
4876 // sibling call optimization. For example, gcc is able to do SCO for caller1
4877 // in the following example, but not for caller2.
4878 // struct test {
4879 // long int a;
4880 // char ary[56];
4881 // } gTest;
4882 // __attribute__((noinline)) int callee(struct test v, struct test *b) {
4883 // b->a = v.a;
4884 // return 0;
4885 // }
4886 // void caller1(struct test a, struct test c, struct test *b) {
4887 // callee(gTest, b); }
4888 // void caller2(struct test *b) { callee(gTest, b); }
4889 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4890 return false;
4891
4892 // If callee and caller use different calling conventions, we cannot pass
4893 // parameters on stack since offsets for the parameter area may be different.
4894 if (CallerCC != CalleeCC && needStackSlotPassParameters(Subtarget, Outs))
4895 return false;
4896
4897 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4898 // the caller and callee share the same TOC for TCO/SCO. If the caller and
4899 // callee potentially have different TOC bases then we cannot tail call since
4900 // we need to restore the TOC pointer after the call.
4901 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4902 // We cannot guarantee this for indirect calls or calls to external functions.
4903 // When PC-Relative addressing is used, the concept of the TOC is no longer
4904 // applicable so this check is not required.
4905 // Check first for indirect calls.
4906 if (!Subtarget.isUsingPCRelativeCalls() &&
4907 !isFunctionGlobalAddress(CalleeGV) && !isCalleeExternalSymbol)
4908 return false;
4909
4910 // Check if we share the TOC base.
4911 if (!Subtarget.isUsingPCRelativeCalls() &&
4912 !callsShareTOCBase(CallerFunc, CalleeGV, getTargetMachine()))
4913 return false;
4914
4915 // TCO allows altering callee ABI, so we don't have to check further.
4916 if (CalleeCC == CallingConv::Fast && TailCallOpt)
4917 return true;
4918
4919 if (DisableSCO) return false;
4920
4921 // If callee use the same argument list that caller is using, then we can
4922 // apply SCO on this case. If it is not, then we need to check if callee needs
4923 // stack for passing arguments.
4924 // PC Relative tail calls may not have a CallBase.
4925 // If there is no CallBase we cannot verify if we have the same argument
4926 // list so assume that we don't have the same argument list.
4927 if (CB && !hasSameArgumentList(CallerFunc, *CB) &&
4928 needStackSlotPassParameters(Subtarget, Outs))
4929 return false;
4930 else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4931 return false;
4932
4933 return true;
4934}
4935
4936/// IsEligibleForTailCallOptimization - Check whether the call is eligible
4937/// for tail call optimization. Targets which want to do tail call
4938/// optimization should implement this function.
4939bool PPCTargetLowering::IsEligibleForTailCallOptimization(
4940 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
4941 CallingConv::ID CallerCC, bool isVarArg,
4942 const SmallVectorImpl<ISD::InputArg> &Ins) const {
4943 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4944 return false;
4945
4946 // Variable argument functions are not supported.
4947 if (isVarArg)
4948 return false;
4949
4950 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4951 // Functions containing by val parameters are not supported.
4952 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4953 return false;
4954
4955 // Non-PIC/GOT tail calls are supported.
4956 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4957 return true;
4958
4959 // At the moment we can only do local tail calls (in same module, hidden
4960 // or protected) if we are generating PIC.
4961 if (CalleeGV)
4962 return CalleeGV->hasHiddenVisibility() ||
4963 CalleeGV->hasProtectedVisibility();
4964 }
4965
4966 return false;
4967}
4968
4969/// isCallCompatibleAddress - Return the immediate to use if the specified
4970/// 32-bit value is representable in the immediate field of a BxA instruction.
4971static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4972 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4973 if (!C) return nullptr;
4974
4975 int Addr = C->getZExtValue();
4976 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
4977 SignExtend32<26>(Addr) != Addr)
4978 return nullptr; // Top 6 bits have to be sext of immediate.
4979
4980 return DAG
4981 .getConstant(
4982 (int)C->getZExtValue() >> 2, SDLoc(Op),
4983 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4984 .getNode();
4985}
4986
4987namespace {
4988
4989struct TailCallArgumentInfo {
4990 SDValue Arg;
4991 SDValue FrameIdxOp;
4992 int FrameIdx = 0;
4993
4994 TailCallArgumentInfo() = default;
4995};
4996
4997} // end anonymous namespace
4998
4999/// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5000static void StoreTailCallArgumentsToStackSlot(
5001 SelectionDAG &DAG, SDValue Chain,
5002 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5003 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5004 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5005 SDValue Arg = TailCallArgs[i].Arg;
5006 SDValue FIN = TailCallArgs[i].FrameIdxOp;
5007 int FI = TailCallArgs[i].FrameIdx;
5008 // Store relative to framepointer.
5009 MemOpChains.push_back(DAG.getStore(
5010 Chain, dl, Arg, FIN,
5011 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
5012 }
5013}
5014
5015/// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5016/// the appropriate stack slot for the tail call optimized function call.
5017static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
5018 SDValue OldRetAddr, SDValue OldFP,
5019 int SPDiff, const SDLoc &dl) {
5020 if (SPDiff) {
5021 // Calculate the new stack slot for the return address.
5022 MachineFunction &MF = DAG.getMachineFunction();
5023 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5024 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5025 bool isPPC64 = Subtarget.isPPC64();
5026 int SlotSize = isPPC64 ? 8 : 4;
5027 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5028 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5029 NewRetAddrLoc, true);
5030 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5031 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5032 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5033 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5034 }
5035 return Chain;
5036}
5037
5038/// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5039/// the position of the argument.
5040static void
5041CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5042 SDValue Arg, int SPDiff, unsigned ArgOffset,
5043 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5044 int Offset = ArgOffset + SPDiff;
5045 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5046 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5047 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5048 SDValue FIN = DAG.getFrameIndex(FI, VT);
5049 TailCallArgumentInfo Info;
5050 Info.Arg = Arg;
5051 Info.FrameIdxOp = FIN;
5052 Info.FrameIdx = FI;
5053 TailCallArguments.push_back(Info);
5054}
5055
5056/// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5057/// stack slot. Returns the chain as result and the loaded frame pointers in
5058/// LROpOut/FPOpout. Used when tail calling.
5059SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5060 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5061 SDValue &FPOpOut, const SDLoc &dl) const {
5062 if (SPDiff) {
5063 // Load the LR and FP stack slot for later adjusting.
5064 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5065 LROpOut = getReturnAddrFrameIndex(DAG);
5066 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5067 Chain = SDValue(LROpOut.getNode(), 1);
5068 }
5069 return Chain;
5070}
5071
5072/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5073/// by "Src" to address "Dst" of size "Size". Alignment information is
5074/// specified by the specific parameter attribute. The copy will be passed as
5075/// a byval function parameter.
5076/// Sometimes what we are copying is the end of a larger object, the part that
5077/// does not fit in registers.
5078static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5079 SDValue Chain, ISD::ArgFlagsTy Flags,
5080 SelectionDAG &DAG, const SDLoc &dl) {
5081 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5082 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5083 Flags.getNonZeroByValAlign(), false, false, false,
5084 MachinePointerInfo(), MachinePointerInfo());
5085}
5086
5087/// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5088/// tail calls.
5089static void LowerMemOpCallTo(
5090 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5091 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5092 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5093 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5094 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5095 if (!isTailCall) {
5096 if (isVector) {
5097 SDValue StackPtr;
5098 if (isPPC64)
5099 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5100 else
5101 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5102 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5103 DAG.getConstant(ArgOffset, dl, PtrVT));
5104 }
5105 MemOpChains.push_back(
5106 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5107 // Calculate and remember argument location.
5108 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5109 TailCallArguments);
5110}
5111
5112static void
5113PrepareTailCall(SelectionDAG &DAG, SDValue &InGlue, SDValue &Chain,
5114 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5115 SDValue FPOp,
5116 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5117 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5118 // might overwrite each other in case of tail call optimization.
5119 SmallVector<SDValue, 8> MemOpChains2;
5120 // Do not flag preceding copytoreg stuff together with the following stuff.
5121 InGlue = SDValue();
5122 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5123 MemOpChains2, dl);
5124 if (!MemOpChains2.empty())
5125 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5126
5127 // Store the return address to the appropriate stack slot.
5128 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5129
5130 // Emit callseq_end just before tailcall node.
5131 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, dl);
5132 InGlue = Chain.getValue(1);
5133}
5134
5135// Is this global address that of a function that can be called by name? (as
5136// opposed to something that must hold a descriptor for an indirect call).
5137static bool isFunctionGlobalAddress(const GlobalValue *GV) {
5138 if (GV) {
5139 if (GV->isThreadLocal())
5140 return false;
5141
5142 return GV->getValueType()->isFunctionTy();
5143 }
5144
5145 return false;
5146}
5147
5148SDValue PPCTargetLowering::LowerCallResult(
5149 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
5150 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5151 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5152 SmallVector<CCValAssign, 16> RVLocs;
5153 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5154 *DAG.getContext());
5155
5156 CCRetInfo.AnalyzeCallResult(
5157 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5158 ? RetCC_PPC_Cold
5159 : RetCC_PPC);
5160
5161 // Copy all of the result registers out of their specified physreg.
5162 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5163 CCValAssign &VA = RVLocs[i];
5164 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", 5164, __extension__
__PRETTY_FUNCTION__))
;
5165
5166 SDValue Val;
5167
5168 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5169 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5170 InGlue);
5171 Chain = Lo.getValue(1);
5172 InGlue = Lo.getValue(2);
5173 VA = RVLocs[++i]; // skip ahead to next loc
5174 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5175 InGlue);
5176 Chain = Hi.getValue(1);
5177 InGlue = Hi.getValue(2);
5178 if (!Subtarget.isLittleEndian())
5179 std::swap (Lo, Hi);
5180 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5181 } else {
5182 Val = DAG.getCopyFromReg(Chain, dl,
5183 VA.getLocReg(), VA.getLocVT(), InGlue);
5184 Chain = Val.getValue(1);
5185 InGlue = Val.getValue(2);
5186 }
5187
5188 switch (VA.getLocInfo()) {
5189 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5189)
;
5190 case CCValAssign::Full: break;
5191 case CCValAssign::AExt:
5192 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5193 break;
5194 case CCValAssign::ZExt:
5195 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5196 DAG.getValueType(VA.getValVT()));
5197 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5198 break;
5199 case CCValAssign::SExt:
5200 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5201 DAG.getValueType(VA.getValVT()));
5202 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5203 break;
5204 }
5205
5206 InVals.push_back(Val);
5207 }
5208
5209 return Chain;
5210}
5211
5212static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5213 const PPCSubtarget &Subtarget, bool isPatchPoint) {
5214 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5215 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5216
5217 // PatchPoint calls are not indirect.
5218 if (isPatchPoint)
5219 return false;
5220
5221 if (isFunctionGlobalAddress(GV) || isa<ExternalSymbolSDNode>(Callee))
5222 return false;
5223
5224 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5225 // becuase the immediate function pointer points to a descriptor instead of
5226 // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5227 // pointer immediate points to the global entry point, while the BLA would
5228 // need to jump to the local entry point (see rL211174).
5229 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5230 isBLACompatibleAddress(Callee, DAG))
5231 return false;
5232
5233 return true;
5234}
5235
5236// AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5237static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5238 return Subtarget.isAIXABI() ||
5239 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5240}
5241
5242static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5243 const Function &Caller, const SDValue &Callee,
5244 const PPCSubtarget &Subtarget,
5245 const TargetMachine &TM,
5246 bool IsStrictFPCall = false) {
5247 if (CFlags.IsTailCall)
5248 return PPCISD::TC_RETURN;
5249
5250 unsigned RetOpc = 0;
5251 // This is a call through a function pointer.
5252 if (CFlags.IsIndirect) {
5253 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5254 // indirect calls. The save of the caller's TOC pointer to the stack will be
5255 // inserted into the DAG as part of call lowering. The restore of the TOC
5256 // pointer is modeled by using a pseudo instruction for the call opcode that
5257 // represents the 2 instruction sequence of an indirect branch and link,
5258 // immediately followed by a load of the TOC pointer from the the stack save
5259 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5260 // as it is not saved or used.
5261 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5262 : PPCISD::BCTRL;
5263 } else if (Subtarget.isUsingPCRelativeCalls()) {
5264 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", 5264, __extension__
__PRETTY_FUNCTION__))
;
5265 RetOpc = PPCISD::CALL_NOTOC;
5266 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) {
5267 // The ABIs that maintain a TOC pointer accross calls need to have a nop
5268 // immediately following the call instruction if the caller and callee may
5269 // have different TOC bases. At link time if the linker determines the calls
5270 // may not share a TOC base, the call is redirected to a trampoline inserted
5271 // by the linker. The trampoline will (among other things) save the callers
5272 // TOC pointer at an ABI designated offset in the linkage area and the
5273 // linker will rewrite the nop to be a load of the TOC pointer from the
5274 // linkage area into gpr2.
5275 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5276 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5277 RetOpc =
5278 callsShareTOCBase(&Caller, GV, TM) ? PPCISD::CALL : PPCISD::CALL_NOP;
5279 } else
5280 RetOpc = PPCISD::CALL;
5281 if (IsStrictFPCall) {
5282 switch (RetOpc) {
5283 default:
5284 llvm_unreachable("Unknown call opcode")::llvm::llvm_unreachable_internal("Unknown call opcode", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5284)
;
5285 case PPCISD::BCTRL_LOAD_TOC:
5286 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5287 break;
5288 case PPCISD::BCTRL:
5289 RetOpc = PPCISD::BCTRL_RM;
5290 break;
5291 case PPCISD::CALL_NOTOC:
5292 RetOpc = PPCISD::CALL_NOTOC_RM;
5293 break;
5294 case PPCISD::CALL:
5295 RetOpc = PPCISD::CALL_RM;
5296 break;
5297 case PPCISD::CALL_NOP:
5298 RetOpc = PPCISD::CALL_NOP_RM;
5299 break;
5300 }
5301 }
5302 return RetOpc;
5303}
5304
5305static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5306 const SDLoc &dl, const PPCSubtarget &Subtarget) {
5307 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5308 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5309 return SDValue(Dest, 0);
5310
5311 // Returns true if the callee is local, and false otherwise.
5312 auto isLocalCallee = [&]() {
5313 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5314 const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5315 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5316
5317 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5318 !isa_and_nonnull<GlobalIFunc>(GV);
5319 };
5320
5321 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in
5322 // a static relocation model causes some versions of GNU LD (2.17.50, at
5323 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5324 // built with secure-PLT.
5325 bool UsePlt =
5326 Subtarget.is32BitELFABI() && !isLocalCallee() &&
5327 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5328
5329 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5330 const TargetMachine &TM = Subtarget.getTargetMachine();
5331 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5332 MCSymbolXCOFF *S =
5333 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5334
5335 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5336 return DAG.getMCSymbol(S, PtrVT);
5337 };
5338
5339 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5340 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5341 if (isFunctionGlobalAddress(GV)) {
5342 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5343
5344 if (Subtarget.isAIXABI()) {
5345 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", 5345, __extension__
__PRETTY_FUNCTION__))
;
5346 return getAIXFuncEntryPointSymbolSDNode(GV);
5347 }
5348 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5349 UsePlt ? PPCII::MO_PLT : 0);
5350 }
5351
5352 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5353 const char *SymName = S->getSymbol();
5354 if (Subtarget.isAIXABI()) {
5355 // If there exists a user-declared function whose name is the same as the
5356 // ExternalSymbol's, then we pick up the user-declared version.
5357 const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5358 if (const Function *F =
5359 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5360 return getAIXFuncEntryPointSymbolSDNode(F);
5361
5362 // On AIX, direct function calls reference the symbol for the function's
5363 // entry point, which is named by prepending a "." before the function's
5364 // C-linkage name. A Qualname is returned here because an external
5365 // function entry point is a csect with XTY_ER property.
5366 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5367 auto &Context = DAG.getMachineFunction().getMMI().getContext();
5368 MCSectionXCOFF *Sec = Context.getXCOFFSection(
5369 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5370 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5371 return Sec->getQualNameSymbol();
5372 };
5373
5374 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5375 }
5376 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5377 UsePlt ? PPCII::MO_PLT : 0);
5378 }
5379
5380 // No transformation needed.
5381 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", 5381, __extension__
__PRETTY_FUNCTION__))
;
5382 return Callee;
5383}
5384
5385static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5386 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", 5387, __extension__
__PRETTY_FUNCTION__))
5387 "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", 5387, __extension__
__PRETTY_FUNCTION__))
;
5388
5389 // The last operand is the chain, except when the node has glue. If the node
5390 // has glue, then the last operand is the glue, and the chain is the second
5391 // last operand.
5392 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5393 if (LastValue.getValueType() != MVT::Glue)
5394 return LastValue;
5395
5396 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5397}
5398
5399// Creates the node that moves a functions address into the count register
5400// to prepare for an indirect call instruction.
5401static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5402 SDValue &Glue, SDValue &Chain,
5403 const SDLoc &dl) {
5404 SDValue MTCTROps[] = {Chain, Callee, Glue};
5405 EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5406 Chain = DAG.getNode(PPCISD::MTCTR, dl, ArrayRef(ReturnTypes, 2),
5407 ArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5408 // The glue is the second value produced.
5409 Glue = Chain.getValue(1);
5410}
5411
5412static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5413 SDValue &Glue, SDValue &Chain,
5414 SDValue CallSeqStart,
5415 const CallBase *CB, const SDLoc &dl,
5416 bool hasNest,
5417 const PPCSubtarget &Subtarget) {
5418 // Function pointers in the 64-bit SVR4 ABI do not point to the function
5419 // entry point, but to the function descriptor (the function entry point
5420 // address is part of the function descriptor though).
5421 // The function descriptor is a three doubleword structure with the
5422 // following fields: function entry point, TOC base address and
5423 // environment pointer.
5424 // Thus for a call through a function pointer, the following actions need
5425 // to be performed:
5426 // 1. Save the TOC of the caller in the TOC save area of its stack
5427 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5428 // 2. Load the address of the function entry point from the function
5429 // descriptor.
5430 // 3. Load the TOC of the callee from the function descriptor into r2.
5431 // 4. Load the environment pointer from the function descriptor into
5432 // r11.
5433 // 5. Branch to the function entry point address.
5434 // 6. On return of the callee, the TOC of the caller needs to be
5435 // restored (this is done in FinishCall()).
5436 //
5437 // The loads are scheduled at the beginning of the call sequence, and the
5438 // register copies are flagged together to ensure that no other
5439 // operations can be scheduled in between. E.g. without flagging the
5440 // copies together, a TOC access in the caller could be scheduled between
5441 // the assignment of the callee TOC and the branch to the callee, which leads
5442 // to incorrect code.
5443
5444 // Start by loading the function address from the descriptor.
5445 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5446 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5447 ? (MachineMemOperand::MODereferenceable |
5448 MachineMemOperand::MOInvariant)
5449 : MachineMemOperand::MONone;
5450
5451 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5452
5453 // Registers used in building the DAG.
5454 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5455 const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5456
5457 // Offsets of descriptor members.
5458 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5459 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5460
5461 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5462 const Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
5463
5464 // One load for the functions entry point address.
5465 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5466 Alignment, MMOFlags);
5467
5468 // One for loading the TOC anchor for the module that contains the called
5469 // function.
5470 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5471 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5472 SDValue TOCPtr =
5473 DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5474 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5475
5476 // One for loading the environment pointer.
5477 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5478 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5479 SDValue LoadEnvPtr =
5480 DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5481 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5482
5483
5484 // Then copy the newly loaded TOC anchor to the TOC pointer.
5485 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5486 Chain = TOCVal.getValue(0);
5487 Glue = TOCVal.getValue(1);
5488
5489 // If the function call has an explicit 'nest' parameter, it takes the
5490 // place of the environment pointer.
5491 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", 5492, __extension__
__PRETTY_FUNCTION__))
5492 "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", 5492, __extension__
__PRETTY_FUNCTION__))
;
5493 if (!hasNest) {
5494 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5495 Chain = EnvVal.getValue(0);
5496 Glue = EnvVal.getValue(1);
5497 }
5498
5499 // The rest of the indirect call sequence is the same as the non-descriptor
5500 // DAG.
5501 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5502}
5503
5504static void
5505buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5506 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5507 SelectionDAG &DAG,
5508 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5509 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5510 const PPCSubtarget &Subtarget) {
5511 const bool IsPPC64 = Subtarget.isPPC64();
5512 // MVT for a general purpose register.
5513 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5514
5515 // First operand is always the chain.
5516 Ops.push_back(Chain);
5517
5518 // If it's a direct call pass the callee as the second operand.
5519 if (!CFlags.IsIndirect)
5520 Ops.push_back(Callee);
5521 else {
5522 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", 5522, __extension__
__PRETTY_FUNCTION__))
;
5523
5524 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5525 // on the stack (this would have been done in `LowerCall_64SVR4` or
5526 // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5527 // represents both the indirect branch and a load that restores the TOC
5528 // pointer from the linkage area. The operand for the TOC restore is an add
5529 // of the TOC save offset to the stack pointer. This must be the second
5530 // operand: after the chain input but before any other variadic arguments.
5531 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5532 // saved or used.
5533 if (isTOCSaveRestoreRequired(Subtarget)) {
5534 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5535
5536 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5537 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5538 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5539 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5540 Ops.push_back(AddTOC);
5541 }
5542
5543 // Add the register used for the environment pointer.
5544 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5545 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5546 RegVT));
5547
5548
5549 // Add CTR register as callee so a bctr can be emitted later.
5550 if (CFlags.IsTailCall)
5551 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5552 }
5553
5554 // If this is a tail call add stack pointer delta.
5555 if (CFlags.IsTailCall)
5556 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5557
5558 // Add argument registers to the end of the list so that they are known live
5559 // into the call.
5560 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5561 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5562 RegsToPass[i].second.getValueType()));
5563
5564 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5565 // no way to mark dependencies as implicit here.
5566 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5567 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5568 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5569 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5570
5571 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5572 if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5573 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5574
5575 // Add a register mask operand representing the call-preserved registers.
5576 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5577 const uint32_t *Mask =
5578 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5579 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", 5579, __extension__
__PRETTY_FUNCTION__))
;
5580 Ops.push_back(DAG.getRegisterMask(Mask));
5581
5582 // If the glue is valid, it is the last operand.
5583 if (Glue.getNode())
5584 Ops.push_back(Glue);
5585}
5586
5587SDValue PPCTargetLowering::FinishCall(
5588 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5589 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5590 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5591 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5592 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5593
5594 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5595 Subtarget.isAIXABI())
5596 setUsesTOCBasePtr(DAG);
5597
5598 unsigned CallOpc =
5599 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5600 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5601
5602 if (!CFlags.IsIndirect)
5603 Callee = transformCallee(Callee, DAG, dl, Subtarget);
5604 else if (Subtarget.usesFunctionDescriptors())
5605 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5606 dl, CFlags.HasNest, Subtarget);
5607 else
5608 prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5609
5610 // Build the operand list for the call instruction.
5611 SmallVector<SDValue, 8> Ops;
5612 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5613 SPDiff, Subtarget);
5614
5615 // Emit tail call.
5616 if (CFlags.IsTailCall) {
5617 // Indirect tail call when using PC Relative calls do not have the same
5618 // constraints.
5619 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", 5627, __extension__
__PRETTY_FUNCTION__))
5620 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", 5627, __extension__
__PRETTY_FUNCTION__))
5621 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", 5627, __extension__
__PRETTY_FUNCTION__))
5622 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", 5627, __extension__
__PRETTY_FUNCTION__))
5623 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", 5627, __extension__
__PRETTY_FUNCTION__))
5624 (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", 5627, __extension__
__PRETTY_FUNCTION__))
5625 "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", 5627, __extension__
__PRETTY_FUNCTION__))
5626 "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", 5627, __extension__
__PRETTY_FUNCTION__))
5627 "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", 5627, __extension__
__PRETTY_FUNCTION__))
;
5628 // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5629 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", 5630, __extension__
__PRETTY_FUNCTION__))
5630 "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", 5630, __extension__
__PRETTY_FUNCTION__))
;
5631 DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5632 return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5633 }
5634
5635 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5636 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5637 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5638 Glue = Chain.getValue(1);
5639
5640 // When performing tail call optimization the callee pops its arguments off
5641 // the stack. Account for this here so these bytes can be pushed back on in
5642 // PPCFrameLowering::eliminateCallFramePseudoInstr.
5643 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5644 getTargetMachine().Options.GuaranteedTailCallOpt)
5645 ? NumBytes
5646 : 0;
5647
5648 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, BytesCalleePops, Glue, dl);
5649 Glue = Chain.getValue(1);
5650
5651 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5652 DAG, InVals);
5653}
5654
5655bool PPCTargetLowering::supportsTailCallFor(const CallBase *CB) const {
5656 CallingConv::ID CalleeCC = CB->getCallingConv();
5657 const Function *CallerFunc = CB->getCaller();
5658 CallingConv::ID CallerCC = CallerFunc->getCallingConv();
5659 const Function *CalleeFunc = CB->getCalledFunction();
5660 if (!CalleeFunc)
5661 return false;
5662 const GlobalValue *CalleeGV = dyn_cast<GlobalValue>(CalleeFunc);
5663
5664 SmallVector<ISD::OutputArg, 2> Outs;
5665 SmallVector<ISD::InputArg, 2> Ins;
5666
5667 GetReturnInfo(CalleeCC, CalleeFunc->getReturnType(),
5668 CalleeFunc->getAttributes(), Outs, *this,
5669 CalleeFunc->getParent()->getDataLayout());
5670
5671 return isEligibleForTCO(CalleeGV, CalleeCC, CallerCC, CB,
5672 CalleeFunc->isVarArg(), Outs, Ins, CallerFunc,
5673 false /*isCalleeExternalSymbol*/);
5674}
5675
5676bool PPCTargetLowering::isEligibleForTCO(
5677 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5678 CallingConv::ID CallerCC, const CallBase *CB, bool isVarArg,
5679 const SmallVectorImpl<ISD::OutputArg> &Outs,
5680 const SmallVectorImpl<ISD::InputArg> &Ins, const Function *CallerFunc,
5681 bool isCalleeExternalSymbol) const {
5682 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5683 return false;
5684
5685 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5686 return IsEligibleForTailCallOptimization_64SVR4(
5687 CalleeGV, CalleeCC, CallerCC, CB, isVarArg, Outs, Ins, CallerFunc,
5688 isCalleeExternalSymbol);
5689 else
5690 return IsEligibleForTailCallOptimization(CalleeGV, CalleeCC, CallerCC,
5691 isVarArg, Ins);
5692}
5693
5694SDValue
5695PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5696 SmallVectorImpl<SDValue> &InVals) const {
5697 SelectionDAG &DAG = CLI.DAG;
5698 SDLoc &dl = CLI.DL;
5699 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5700 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
5701 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
5702 SDValue Chain = CLI.Chain;
5703 SDValue Callee = CLI.Callee;
5704 bool &isTailCall = CLI.IsTailCall;
5705 CallingConv::ID CallConv = CLI.CallConv;
5706 bool isVarArg = CLI.IsVarArg;
5707 bool isPatchPoint = CLI.IsPatchPoint;
5708 const CallBase *CB = CLI.CB;
5709
5710 if (isTailCall) {
5711 MachineFunction &MF = DAG.getMachineFunction();
5712 CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
5713 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5714 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5715 bool IsCalleeExternalSymbol = isa<ExternalSymbolSDNode>(Callee);
5716
5717 isTailCall =
5718 isEligibleForTCO(GV, CallConv, CallerCC, CB, isVarArg, Outs, Ins,
5719 &(MF.getFunction()), IsCalleeExternalSymbol);
5720 if (isTailCall) {
5721 ++NumTailCalls;
5722 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5723 ++NumSiblingCalls;
5724
5725 // PC Relative calls no longer guarantee that the callee is a Global
5726 // Address Node. The callee could be an indirect tail call in which
5727 // case the SDValue for the callee could be a load (to load the address
5728 // of a function pointer) or it may be a register copy (to move the
5729 // address of the callee from a function parameter into a virtual
5730 // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5731 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", 5733, __extension__
__PRETTY_FUNCTION__))
5732 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", 5733, __extension__
__PRETTY_FUNCTION__))
5733 "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", 5733, __extension__
__PRETTY_FUNCTION__))
;
5734
5735 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)
5736 << "\nTCO callee: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { dbgs() << "TCO caller: " << DAG
.getMachineFunction().getName() << "\nTCO callee: "; } }
while (false)
;
5737 LLVM_DEBUG(Callee.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { Callee.dump(); } } while (false)
;
5738 }
5739 }
5740
5741 if (!isTailCall && CB && CB->isMustTailCall())
5742 report_fatal_error("failed to perform tail call elimination on a call "
5743 "site marked musttail");
5744
5745 // When long calls (i.e. indirect calls) are always used, calls are always
5746 // made via function pointer. If we have a function name, first translate it
5747 // into a pointer.
5748 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5749 !isTailCall)
5750 Callee = LowerGlobalAddress(Callee, DAG);
5751
5752 CallFlags CFlags(
5753 CallConv, isTailCall, isVarArg, isPatchPoint,
5754 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5755 // hasNest
5756 Subtarget.is64BitELFABI() &&
5757 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5758 CLI.NoMerge);
5759
5760 if (Subtarget.isAIXABI())
5761 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5762 InVals, CB);
5763
5764 assert(Subtarget.isSVR4ABI())(static_cast <bool> (Subtarget.isSVR4ABI()) ? void (0) :
__assert_fail ("Subtarget.isSVR4ABI()", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5764, __extension__ __PRETTY_FUNCTION__))
;
5765 if (Subtarget.isPPC64())
5766 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5767 InVals, CB);
5768 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5769 InVals, CB);
5770}
5771
5772SDValue PPCTargetLowering::LowerCall_32SVR4(
5773 SDValue Chain, SDValue Callee, CallFlags CFlags,
5774 const SmallVectorImpl<ISD::OutputArg> &Outs,
5775 const SmallVectorImpl<SDValue> &OutVals,
5776 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5777 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5778 const CallBase *CB) const {
5779 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5780 // of the 32-bit SVR4 ABI stack frame layout.
5781
5782 const CallingConv::ID CallConv = CFlags.CallConv;
5783 const bool IsVarArg = CFlags.IsVarArg;
5784 const bool IsTailCall = CFlags.IsTailCall;
5785
5786 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", 5788, __extension__
__PRETTY_FUNCTION__))
5787 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", 5788, __extension__
__PRETTY_FUNCTION__))
5788 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", 5788, __extension__
__PRETTY_FUNCTION__))
;
5789
5790 const Align PtrAlign(4);
5791
5792 MachineFunction &MF = DAG.getMachineFunction();
5793
5794 // Mark this function as potentially containing a function that contains a
5795 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5796 // and restoring the callers stack pointer in this functions epilog. This is
5797 // done because by tail calling the called function might overwrite the value
5798 // in this function's (MF) stack pointer stack slot 0(SP).
5799 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5800 CallConv == CallingConv::Fast)
5801 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5802
5803 // Count how many bytes are to be pushed on the stack, including the linkage
5804 // area, parameter list area and the part of the local variable space which
5805 // contains copies of aggregates which are passed by value.
5806
5807 // Assign locations to all of the outgoing arguments.
5808 SmallVector<CCValAssign, 16> ArgLocs;
5809 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5810
5811 // Reserve space for the linkage area on the stack.
5812 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5813 PtrAlign);
5814 if (useSoftFloat())
5815 CCInfo.PreAnalyzeCallOperands(Outs);
5816
5817 if (IsVarArg) {
5818 // Handle fixed and variable vector arguments differently.
5819 // Fixed vector arguments go into registers as long as registers are
5820 // available. Variable vector arguments always go into memory.
5821 unsigned NumArgs = Outs.size();
5822
5823 for (unsigned i = 0; i != NumArgs; ++i) {
5824 MVT ArgVT = Outs[i].VT;
5825 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5826 bool Result;
5827
5828 if (Outs[i].IsFixed) {
5829 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5830 CCInfo);
5831 } else {
5832 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5833 ArgFlags, CCInfo);
5834 }
5835
5836 if (Result) {
5837#ifndef NDEBUG
5838 errs() << "Call operand #" << i << " has unhandled type "
5839 << ArgVT << "\n";
5840#endif
5841 llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5841)
;
5842 }
5843 }
5844 } else {
5845 // All arguments are treated the same.
5846 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5847 }
5848 CCInfo.clearWasPPCF128();
5849
5850 // Assign locations to all of the outgoing aggregate by value arguments.
5851 SmallVector<CCValAssign, 16> ByValArgLocs;
5852 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5853
5854 // Reserve stack space for the allocations in CCInfo.
5855 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5856
5857 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5858
5859 // Size of the linkage area, parameter list area and the part of the local
5860 // space variable where copies of aggregates which are passed by value are
5861 // stored.
5862 unsigned NumBytes = CCByValInfo.getNextStackOffset();
5863
5864 // Calculate by how many bytes the stack has to be adjusted in case of tail
5865 // call optimization.
5866 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5867
5868 // Adjust the stack pointer for the new arguments...
5869 // These operations are automatically eliminated by the prolog/epilog pass
5870 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5871 SDValue CallSeqStart = Chain;
5872
5873 // Load the return address and frame pointer so it can be moved somewhere else
5874 // later.
5875 SDValue LROp, FPOp;
5876 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5877
5878 // Set up a copy of the stack pointer for use loading and storing any
5879 // arguments that may not fit in the registers available for argument
5880 // passing.
5881 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5882
5883 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5884 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5885 SmallVector<SDValue, 8> MemOpChains;
5886
5887 bool seenFloatArg = false;
5888 // Walk the register/memloc assignments, inserting copies/loads.
5889 // i - Tracks the index into the list of registers allocated for the call
5890 // RealArgIdx - Tracks the index into the list of actual function arguments
5891 // j - Tracks the index into the list of byval arguments
5892 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5893 i != e;
5894 ++i, ++RealArgIdx) {
5895 CCValAssign &VA = ArgLocs[i];
5896 SDValue Arg = OutVals[RealArgIdx];
5897 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5898
5899 if (Flags.isByVal()) {
5900 // Argument is an aggregate which is passed by value, thus we need to
5901 // create a copy of it in the local variable space of the current stack
5902 // frame (which is the stack frame of the caller) and pass the address of
5903 // this copy to the callee.
5904 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", 5904, __extension__
__PRETTY_FUNCTION__))
;
5905 CCValAssign &ByValVA = ByValArgLocs[j++];
5906 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", 5906, __extension__
__PRETTY_FUNCTION__))
;
5907
5908 // Memory reserved in the local variable space of the callers stack frame.
5909 unsigned LocMemOffset = ByValVA.getLocMemOffset();
5910
5911 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5912 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5913 StackPtr, PtrOff);
5914
5915 // Create a copy of the argument in the local area of the current
5916 // stack frame.
5917 SDValue MemcpyCall =
5918 CreateCopyOfByValArgument(Arg, PtrOff,
5919 CallSeqStart.getNode()->getOperand(0),
5920 Flags, DAG, dl);
5921
5922 // This must go outside the CALLSEQ_START..END.
5923 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5924 SDLoc(MemcpyCall));
5925 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5926 NewCallSeqStart.getNode());
5927 Chain = CallSeqStart = NewCallSeqStart;
5928
5929 // Pass the address of the aggregate copy on the stack either in a
5930 // physical register or in the parameter list area of the current stack
5931 // frame to the callee.
5932 Arg = PtrOff;
5933 }
5934
5935 // When useCRBits() is true, there can be i1 arguments.
5936 // It is because getRegisterType(MVT::i1) => MVT::i1,
5937 // and for other integer types getRegisterType() => MVT::i32.
5938 // Extend i1 and ensure callee will get i32.
5939 if (Arg.getValueType() == MVT::i1)
5940 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5941 dl, MVT::i32, Arg);
5942
5943 if (VA.isRegLoc()) {
5944 seenFloatArg |= VA.getLocVT().isFloatingPoint();
5945 // Put argument in a physical register.
5946 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5947 bool IsLE = Subtarget.isLittleEndian();
5948 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5949 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5950 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5951 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5952 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5953 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5954 SVal.getValue(0)));
5955 } else
5956 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5957 } else {
5958 // Put argument in the parameter list area of the current stack frame.
5959 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5959, __extension__ __PRETTY_FUNCTION__))
;
5960 unsigned LocMemOffset = VA.getLocMemOffset();
5961
5962 if (!IsTailCall) {
5963 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5964 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5965 StackPtr, PtrOff);
5966
5967 MemOpChains.push_back(
5968 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5969 } else {
5970 // Calculate and remember argument location.
5971 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5972 TailCallArguments);
5973 }
5974 }
5975 }
5976
5977 if (!MemOpChains.empty())
5978 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5979
5980 // Build a sequence of copy-to-reg nodes chained together with token chain
5981 // and flag operands which copy the outgoing args into the appropriate regs.
5982 SDValue InGlue;
5983 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5984 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5985 RegsToPass[i].second, InGlue);
5986 InGlue = Chain.getValue(1);
5987 }
5988
5989 // Set CR bit 6 to true if this is a vararg call with floating args passed in
5990 // registers.
5991 if (IsVarArg) {
5992 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5993 SDValue Ops[] = { Chain, InGlue };
5994
5995 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, dl,
5996 VTs, ArrayRef(Ops, InGlue.getNode() ? 2 : 1));
5997
5998 InGlue = Chain.getValue(1);
5999 }
6000
6001 if (IsTailCall)
6002 PrepareTailCall(DAG, InGlue, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6003 TailCallArguments);
6004
6005 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
6006 Callee, SPDiff, NumBytes, Ins, InVals, CB);
6007}
6008
6009// Copy an argument into memory, being careful to do this outside the
6010// call sequence for the call to which the argument belongs.
6011SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
6012 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
6013 SelectionDAG &DAG, const SDLoc &dl) const {
6014 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
6015 CallSeqStart.getNode()->getOperand(0),
6016 Flags, DAG, dl);
6017 // The MEMCPY must go outside the CALLSEQ_START..END.
6018 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
6019 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
6020 SDLoc(MemcpyCall));
6021 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6022 NewCallSeqStart.getNode());
6023 return NewCallSeqStart;
6024}
6025
6026SDValue PPCTargetLowering::LowerCall_64SVR4(
6027 SDValue Chain, SDValue Callee, CallFlags CFlags,
6028 const SmallVectorImpl<ISD::OutputArg> &Outs,
6029 const SmallVectorImpl<SDValue> &OutVals,
6030 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6031 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6032 const CallBase *CB) const {
6033 bool isELFv2ABI = Subtarget.isELFv2ABI();
6034 bool isLittleEndian = Subtarget.isLittleEndian();
6035 unsigned NumOps = Outs.size();
6036 bool IsSibCall = false;
6037 bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
6038
6039 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6040 unsigned PtrByteSize = 8;
6041
6042 MachineFunction &MF = DAG.getMachineFunction();
6043
6044 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6045 IsSibCall = true;
6046
6047 // Mark this function as potentially containing a function that contains a
6048 // tail call. As a consequence the frame pointer will be used for dynamicalloc
6049 // and restoring the callers stack pointer in this functions epilog. This is
6050 // done because by tail calling the called function might overwrite the value
6051 // in this function's (MF) stack pointer stack slot 0(SP).
6052 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6053 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6054
6055 assert(!(IsFastCall && CFlags.IsVarArg) &&(static_cast <bool> (!(IsFastCall && CFlags.IsVarArg
) && "fastcc not supported on varargs functions") ? void
(0) : __assert_fail ("!(IsFastCall && CFlags.IsVarArg) && \"fastcc not supported on varargs functions\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6056, __extension__
__PRETTY_FUNCTION__))
6056 "fastcc not supported on varargs functions")(static_cast <bool> (!(IsFastCall && CFlags.IsVarArg
) && "fastcc not supported on varargs functions") ? void
(0) : __assert_fail ("!(IsFastCall && CFlags.IsVarArg) && \"fastcc not supported on varargs functions\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6056, __extension__
__PRETTY_FUNCTION__))
;
6057
6058 // Count how many bytes are to be pushed on the stack, including the linkage
6059 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
6060 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6061 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6062 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6063 unsigned NumBytes = LinkageSize;
6064 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6065
6066 static const MCPhysReg GPR[] = {
6067 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6068 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6069 };
6070 static const MCPhysReg VR[] = {
6071 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6072 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6073 };
6074
6075 const unsigned NumGPRs = std::size(GPR);
6076 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6077 const unsigned NumVRs = std::size(VR);
6078
6079 // On ELFv2, we can avoid allocating the parameter area if all the arguments
6080 // can be passed to the callee in registers.
6081 // For the fast calling convention, there is another check below.
6082 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6083 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6084 if (!HasParameterArea) {
6085 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6086 unsigned AvailableFPRs = NumFPRs;
6087 unsigned AvailableVRs = NumVRs;
6088 unsigned NumBytesTmp = NumBytes;
6089 for (unsigned i = 0; i != NumOps; ++i) {
6090 if (Outs[i].Flags.isNest()) continue;
6091 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6092 PtrByteSize, LinkageSize, ParamAreaSize,
6093 NumBytesTmp, AvailableFPRs, AvailableVRs))
6094 HasParameterArea = true;
6095 }
6096 }
6097
6098 // When using the fast calling convention, we don't provide backing for
6099 // arguments that will be in registers.
6100 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6101
6102 // Avoid allocating parameter area for fastcc functions if all the arguments
6103 // can be passed in the registers.
6104 if (IsFastCall)
6105 HasParameterArea = false;
6106
6107 // Add up all the space actually used.
6108 for (unsigned i = 0; i != NumOps; ++i) {
6109 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6110 EVT ArgVT = Outs[i].VT;
6111 EVT OrigVT = Outs[i].ArgVT;
6112
6113 if (Flags.isNest())
6114 continue;
6115
6116 if (IsFastCall) {
6117 if (Flags.isByVal()) {
6118 NumGPRsUsed += (Flags.getByValSize()+7)/8;
6119 if (NumGPRsUsed > NumGPRs)
6120 HasParameterArea = true;
6121 } else {
6122 switch (ArgVT.getSimpleVT().SimpleTy) {
6123 default: llvm_unreachable("Unexpected ValueType for argument!")::llvm::llvm_unreachable_internal("Unexpected ValueType for argument!"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6123)
;
6124 case MVT::i1:
6125 case MVT::i32:
6126 case MVT::i64:
6127 if (++NumGPRsUsed <= NumGPRs)
6128 continue;
6129 break;
6130 case MVT::v4i32:
6131 case MVT::v8i16:
6132 case MVT::v16i8:
6133 case MVT::v2f64:
6134 case MVT::v2i64:
6135 case MVT::v1i128:
6136 case MVT::f128:
6137 if (++NumVRsUsed <= NumVRs)
6138 continue;
6139 break;
6140 case MVT::v4f32:
6141 if (++NumVRsUsed <= NumVRs)
6142 continue;
6143 break;
6144 case MVT::f32:
6145 case MVT::f64:
6146 if (++NumFPRsUsed <= NumFPRs)
6147 continue;
6148 break;
6149 }
6150 HasParameterArea = true;
6151 }
6152 }
6153
6154 /* Respect alignment of argument on the stack. */
6155 auto Alignement =
6156 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6157 NumBytes = alignTo(NumBytes, Alignement);
6158
6159 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6160 if (Flags.isInConsecutiveRegsLast())
6161 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6162 }
6163
6164 unsigned NumBytesActuallyUsed = NumBytes;
6165
6166 // In the old ELFv1 ABI,
6167 // the prolog code of the callee may store up to 8 GPR argument registers to
6168 // the stack, allowing va_start to index over them in memory if its varargs.
6169 // Because we cannot tell if this is needed on the caller side, we have to
6170 // conservatively assume that it is needed. As such, make sure we have at
6171 // least enough stack space for the caller to store the 8 GPRs.
6172 // In the ELFv2 ABI, we allocate the parameter area iff a callee
6173 // really requires memory operands, e.g. a vararg function.
6174 if (HasParameterArea)
6175 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6176 else
6177 NumBytes = LinkageSize;
6178
6179 // Tail call needs the stack to be aligned.
6180 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6181 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6182
6183 int SPDiff = 0;
6184
6185 // Calculate by how many bytes the stack has to be adjusted in case of tail
6186 // call optimization.
6187 if (!IsSibCall)
6188 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6189
6190 // To protect arguments on the stack from being clobbered in a tail call,
6191 // force all the loads to happen before doing any other lowering.
6192 if (CFlags.IsTailCall)
6193 Chain = DAG.getStackArgumentTokenFactor(Chain);
6194
6195 // Adjust the stack pointer for the new arguments...
6196 // These operations are automatically eliminated by the prolog/epilog pass
6197 if (!IsSibCall)
6198 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6199 SDValue CallSeqStart = Chain;
6200
6201 // Load the return address and frame pointer so it can be move somewhere else
6202 // later.
6203 SDValue LROp, FPOp;
6204 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6205
6206 // Set up a copy of the stack pointer for use loading and storing any
6207 // arguments that may not fit in the registers available for argument
6208 // passing.
6209 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6210
6211 // Figure out which arguments are going to go in registers, and which in
6212 // memory. Also, if this is a vararg function, floating point operations
6213 // must be stored to our stack, and loaded into integer regs as well, if
6214 // any integer regs are available for argument passing.
6215 unsigned ArgOffset = LinkageSize;
6216
6217 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6218 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6219
6220 SmallVector<SDValue, 8> MemOpChains;
6221 for (unsigned i = 0; i != NumOps; ++i) {
6222 SDValue Arg = OutVals[i];
6223 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6224 EVT ArgVT = Outs[i].VT;
6225 EVT OrigVT = Outs[i].ArgVT;
6226
6227 // PtrOff will be used to store the current argument to the stack if a
6228 // register cannot be found for it.
6229 SDValue PtrOff;
6230
6231 // We re-align the argument offset for each argument, except when using the
6232 // fast calling convention, when we need to make sure we do that only when
6233 // we'll actually use a stack slot.
6234 auto ComputePtrOff = [&]() {
6235 /* Respect alignment of argument on the stack. */
6236 auto Alignment =
6237 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6238 ArgOffset = alignTo(ArgOffset, Alignment);
6239
6240 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6241
6242 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6243 };
6244
6245 if (!IsFastCall) {
6246 ComputePtrOff();
6247
6248 /* Compute GPR index associated with argument offset. */
6249 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6250 GPR_idx = std::min(GPR_idx, NumGPRs);
6251 }
6252
6253 // Promote integers to 64-bit values.
6254 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6255 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6256 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6257 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6258 }
6259
6260 // FIXME memcpy is used way more than necessary. Correctness first.
6261 // Note: "by value" is code for passing a structure by value, not
6262 // basic types.
6263 if (Flags.isByVal()) {
6264 // Note: Size includes alignment padding, so
6265 // struct x { short a; char b; }
6266 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
6267 // These are the proper values we need for right-justifying the
6268 // aggregate in a parameter register.
6269 unsigned Size = Flags.getByValSize();
6270
6271 // An empty aggregate parameter takes up no storage and no
6272 // registers.
6273 if (Size == 0)
6274 continue;
6275
6276 if (IsFastCall)
6277 ComputePtrOff();
6278
6279 // All aggregates smaller than 8 bytes must be passed right-justified.
6280 if (Size==1 || Size==2 || Size==4) {
6281 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6282 if (GPR_idx != NumGPRs) {
6283 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6284 MachinePointerInfo(), VT);
6285 MemOpChains.push_back(Load.getValue(1));
6286 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6287
6288 ArgOffset += PtrByteSize;
6289 continue;
6290 }
6291 }
6292
6293 if (GPR_idx == NumGPRs && Size < 8) {
6294 SDValue AddPtr = PtrOff;
6295 if (!isLittleEndian) {
6296 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6297 PtrOff.getValueType());
6298 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6299 }
6300 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6301 CallSeqStart,
6302 Flags, DAG, dl);
6303 ArgOffset += PtrByteSize;
6304 continue;
6305 }
6306 // Copy the object to parameter save area if it can not be entirely passed
6307 // by registers.
6308 // FIXME: we only need to copy the parts which need to be passed in
6309 // parameter save area. For the parts passed by registers, we don't need
6310 // to copy them to the stack although we need to allocate space for them
6311 // in parameter save area.
6312 if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6313 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6314 CallSeqStart,
6315 Flags, DAG, dl);
6316
6317 // When a register is available, pass a small aggregate right-justified.
6318 if (Size < 8 && GPR_idx != NumGPRs) {
6319 // The easiest way to get this right-justified in a register
6320 // is to copy the structure into the rightmost portion of a
6321 // local variable slot, then load the whole slot into the
6322 // register.
6323 // FIXME: The memcpy seems to produce pretty awful code for
6324 // small aggregates, particularly for packed ones.
6325 // FIXME: It would be preferable to use the slot in the
6326 // parameter save area instead of a new local variable.
6327 SDValue AddPtr = PtrOff;
6328 if (!isLittleEndian) {
6329 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6330 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6331 }
6332 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6333 CallSeqStart,
6334 Flags, DAG, dl);
6335
6336 // Load the slot into the register.
6337 SDValue Load =
6338 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6339 MemOpChains.push_back(Load.getValue(1));
6340 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6341
6342 // Done with this argument.
6343 ArgOffset += PtrByteSize;
6344 continue;
6345 }
6346
6347 // For aggregates larger than PtrByteSize, copy the pieces of the
6348 // object that fit into registers from the parameter save area.
6349 for (unsigned j=0; j<Size; j+=PtrByteSize) {
6350 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6351 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6352 if (GPR_idx != NumGPRs) {
6353 unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8;
6354 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits);
6355 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg,
6356 MachinePointerInfo(), ObjType);
6357
6358 MemOpChains.push_back(Load.getValue(1));
6359 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6360 ArgOffset += PtrByteSize;
6361 } else {
6362 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6363 break;
6364 }
6365 }
6366 continue;
6367 }
6368
6369 switch (Arg.getSimpleValueType().SimpleTy) {
6370 default: llvm_unreachable("Unexpected ValueType for argument!")::llvm::llvm_unreachable_internal("Unexpected ValueType for argument!"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6370)
;
6371 case MVT::i1:
6372 case MVT::i32:
6373 case MVT::i64:
6374 if (Flags.isNest()) {
6375 // The 'nest' parameter, if any, is passed in R11.
6376 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6377 break;
6378 }
6379
6380 // These can be scalar arguments or elements of an integer array type
6381 // passed directly. Clang may use those instead of "byval" aggregate
6382 // types to avoid forcing arguments to memory unnecessarily.
6383 if (GPR_idx != NumGPRs) {
6384 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6385 } else {
6386 if (IsFastCall)
6387 ComputePtrOff();
6388
6389 assert(HasParameterArea &&(static_cast <bool> (HasParameterArea && "Parameter area must exist to pass an argument in memory."
) ? void (0) : __assert_fail ("HasParameterArea && \"Parameter area must exist to pass an argument in memory.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6390, __extension__
__PRETTY_FUNCTION__))
6390 "Parameter area must exist to pass an argument in memory.")(static_cast <bool> (HasParameterArea && "Parameter area must exist to pass an argument in memory."
) ? void (0) : __assert_fail ("HasParameterArea && \"Parameter area must exist to pass an argument in memory.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6390, __extension__
__PRETTY_FUNCTION__))
;
6391 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6392 true, CFlags.IsTailCall, false, MemOpChains,
6393 TailCallArguments, dl);
6394 if (IsFastCall)
6395 ArgOffset += PtrByteSize;
6396 }
6397 if (!IsFastCall)
6398 ArgOffset += PtrByteSize;
6399 break;
6400 case MVT::f32:
6401 case MVT::f64: {
6402 // These can be scalar arguments or elements of a float array type
6403 // passed directly. The latter are used to implement ELFv2 homogenous
6404 // float aggregates.
6405
6406 // Named arguments go into FPRs first, and once they overflow, the
6407 // remaining arguments go into GPRs and then the parameter save area.
6408 // Unnamed arguments for vararg functions always go to GPRs and
6409 // then the parameter save area. For now, put all arguments to vararg
6410 // routines always in both locations (FPR *and* GPR or stack slot).
6411 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6412 bool NeededLoad = false;
6413
6414 // First load the argument into the next available FPR.
6415 if (FPR_idx != NumFPRs)
6416 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6417
6418 // Next, load the argument into GPR or stack slot if needed.
6419 if (!NeedGPROrStack)
6420 ;
6421 else if (GPR_idx != NumGPRs && !IsFastCall) {
6422 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6423 // once we support fp <-> gpr moves.
6424
6425 // In the non-vararg case, this can only ever happen in the
6426 // presence of f32 array types, since otherwise we never run
6427 // out of FPRs before running out of GPRs.
6428 SDValue ArgVal;
6429
6430 // Double values are always passed in a single GPR.
6431 if (Arg.getValueType() != MVT::f32) {
6432 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6433
6434 // Non-array float values are extended and passed in a GPR.
6435 } else if (!Flags.isInConsecutiveRegs()) {
6436 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6437 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6438
6439 // If we have an array of floats, we collect every odd element
6440 // together with its predecessor into one GPR.
6441 } else if (ArgOffset % PtrByteSize != 0) {
6442 SDValue Lo, Hi;
6443 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6444 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6445 if (!isLittleEndian)
6446 std::swap(Lo, Hi);
6447 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6448
6449 // The final element, if even, goes into the first half of a GPR.
6450 } else if (Flags.isInConsecutiveRegsLast()) {
6451 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6452 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6453 if (!isLittleEndian)
6454 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6455 DAG.getConstant(32, dl, MVT::i32));
6456
6457 // Non-final even elements are skipped; they will be handled
6458 // together the with subsequent argument on the next go-around.
6459 } else
6460 ArgVal = SDValue();
6461
6462 if (ArgVal.getNode())
6463 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6464 } else {
6465 if (IsFastCall)
6466 ComputePtrOff();
6467
6468 // Single-precision floating-point values are mapped to the
6469 // second (rightmost) word of the stack doubleword.
6470 if (Arg.getValueType() == MVT::f32 &&
6471 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6472 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6473 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6474 }
6475
6476 assert(HasParameterArea &&(static_cast <bool> (HasParameterArea && "Parameter area must exist to pass an argument in memory."
) ? void (0) : __assert_fail ("HasParameterArea && \"Parameter area must exist to pass an argument in memory.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6477, __extension__
__PRETTY_FUNCTION__))
6477 "Parameter area must exist to pass an argument in memory.")(static_cast <bool> (HasParameterArea && "Parameter area must exist to pass an argument in memory."
) ? void (0) : __assert_fail ("HasParameterArea && \"Parameter area must exist to pass an argument in memory.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6477, __extension__
__PRETTY_FUNCTION__))
;
6478 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6479 true, CFlags.IsTailCall, false, MemOpChains,
6480 TailCallArguments, dl);
6481
6482 NeededLoad = true;
6483 }
6484 // When passing an array of floats, the array occupies consecutive
6485 // space in the argument area; only round up to the next doubleword
6486 // at the end of the array. Otherwise, each float takes 8 bytes.
6487 if (!IsFastCall || NeededLoad) {
6488 ArgOffset += (Arg.getValueType() == MVT::f32 &&
6489 Flags.isInConsecutiveRegs()) ? 4 : 8;
6490 if (Flags.isInConsecutiveRegsLast())
6491 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6492 }
6493 break;
6494 }
6495 case MVT::v4f32:
6496 case MVT::v4i32:
6497 case MVT::v8i16:
6498 case MVT::v16i8:
6499 case MVT::v2f64:
6500 case MVT::v2i64:
6501 case MVT::v1i128:
6502 case MVT::f128:
6503 // These can be scalar arguments or elements of a vector array type
6504 // passed directly. The latter are used to implement ELFv2 homogenous
6505 // vector aggregates.
6506
6507 // For a varargs call, named arguments go into VRs or on the stack as
6508 // usual; unnamed arguments always go to the stack or the corresponding
6509 // GPRs when within range. For now, we always put the value in both
6510 // locations (or even all three).
6511 if (CFlags.IsVarArg) {
6512 assert(HasParameterArea &&(static_cast <bool> (HasParameterArea && "Parameter area must exist if we have a varargs call."
) ? void (0) : __assert_fail ("HasParameterArea && \"Parameter area must exist if we have a varargs call.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6513, __extension__
__PRETTY_FUNCTION__))
6513 "Parameter area must exist if we have a varargs call.")(static_cast <bool> (HasParameterArea && "Parameter area must exist if we have a varargs call."
) ? void (0) : __assert_fail ("HasParameterArea && \"Parameter area must exist if we have a varargs call.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6513, __extension__
__PRETTY_FUNCTION__))
;
6514 // We could elide this store in the case where the object fits
6515 // entirely in R registers. Maybe later.
6516 SDValue Store =
6517 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6518 MemOpChains.push_back(Store);
6519 if (VR_idx != NumVRs) {
6520 SDValue Load =
6521 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6522 MemOpChains.push_back(Load.getValue(1));
6523 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6524 }
6525 ArgOffset += 16;
6526 for (unsigned i=0; i<16; i+=PtrByteSize) {
6527 if (GPR_idx == NumGPRs)
6528 break;
6529 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6530 DAG.getConstant(i, dl, PtrVT));
6531 SDValue Load =
6532 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6533 MemOpChains.push_back(Load.getValue(1));
6534 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6535 }
6536 break;
6537 }
6538
6539 // Non-varargs Altivec params go into VRs or on the stack.
6540 if (VR_idx != NumVRs) {
6541 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6542 } else {
6543 if (IsFastCall)
6544 ComputePtrOff();
6545
6546 assert(HasParameterArea &&(static_cast <bool> (HasParameterArea && "Parameter area must exist to pass an argument in memory."
) ? void (0) : __assert_fail ("HasParameterArea && \"Parameter area must exist to pass an argument in memory.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6547, __extension__
__PRETTY_FUNCTION__))
6547 "Parameter area must exist to pass an argument in memory.")(static_cast <bool> (HasParameterArea && "Parameter area must exist to pass an argument in memory."
) ? void (0) : __assert_fail ("HasParameterArea && \"Parameter area must exist to pass an argument in memory.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6547, __extension__
__PRETTY_FUNCTION__))
;
6548 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6549 true, CFlags.IsTailCall, true, MemOpChains,
6550 TailCallArguments, dl);
6551 if (IsFastCall)
6552 ArgOffset += 16;
6553 }
6554
6555 if (!IsFastCall)
6556 ArgOffset += 16;
6557 break;
6558 }
6559 }
6560
6561 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&(static_cast <bool> ((!HasParameterArea || NumBytesActuallyUsed
== ArgOffset) && "mismatch in size of parameter area"
) ? void (0) : __assert_fail ("(!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && \"mismatch in size of parameter area\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6562, __extension__
__PRETTY_FUNCTION__))
6562 "mismatch in size of parameter area")(static_cast <bool> ((!HasParameterArea || NumBytesActuallyUsed
== ArgOffset) && "mismatch in size of parameter area"
) ? void (0) : __assert_fail ("(!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && \"mismatch in size of parameter area\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6562, __extension__
__PRETTY_FUNCTION__))
;
6563 (void)NumBytesActuallyUsed;
6564
6565 if (!MemOpChains.empty())
6566 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6567
6568 // Check if this is an indirect call (MTCTR/BCTRL).
6569 // See prepareDescriptorIndirectCall and buildCallOperands for more
6570 // information about calls through function pointers in the 64-bit SVR4 ABI.
6571 if (CFlags.IsIndirect) {
6572 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6573 // caller in the TOC save area.
6574 if (isTOCSaveRestoreRequired(Subtarget)) {
6575 assert(!CFlags.IsTailCall && "Indirect tails calls not supported")(static_cast <bool> (!CFlags.IsTailCall && "Indirect tails calls not supported"
) ? void (0) : __assert_fail ("!CFlags.IsTailCall && \"Indirect tails calls not supported\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6575, __extension__
__PRETTY_FUNCTION__))
;
6576 // Load r2 into a virtual register and store it to the TOC save area.
6577 setUsesTOCBasePtr(DAG);
6578 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6579 // TOC save area offset.
6580 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6581 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6582 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6583 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6584 MachinePointerInfo::getStack(
6585 DAG.getMachineFunction(), TOCSaveOffset));
6586 }
6587 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6588 // This does not mean the MTCTR instruction must use R12; it's easier
6589 // to model this as an extra parameter, so do that.
6590 if (isELFv2ABI && !CFlags.IsPatchPoint)
6591 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6592 }
6593
6594 // Build a sequence of copy-to-reg nodes chained together with token chain
6595 // and flag operands which copy the outgoing args into the appropriate regs.
6596 SDValue InGlue;
6597 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6598 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6599 RegsToPass[i].second, InGlue);
6600 InGlue = Chain.getValue(1);
6601 }
6602
6603 if (CFlags.IsTailCall && !IsSibCall)
6604 PrepareTailCall(DAG, InGlue, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6605 TailCallArguments);
6606
6607 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
6608 Callee, SPDiff, NumBytes, Ins, InVals, CB);
6609}
6610
6611// Returns true when the shadow of a general purpose argument register
6612// in the parameter save area is aligned to at least 'RequiredAlign'.
6613static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6614 assert(RequiredAlign.value() <= 16 &&(static_cast <bool> (RequiredAlign.value() <= 16 &&
"Required alignment greater than stack alignment.") ? void (
0) : __assert_fail ("RequiredAlign.value() <= 16 && \"Required alignment greater than stack alignment.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6615, __extension__
__PRETTY_FUNCTION__))
6615 "Required alignment greater than stack alignment.")(static_cast <bool> (RequiredAlign.value() <= 16 &&
"Required alignment greater than stack alignment.") ? void (
0) : __assert_fail ("RequiredAlign.value() <= 16 && \"Required alignment greater than stack alignment.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6615, __extension__
__PRETTY_FUNCTION__))
;
6616 switch (Reg) {
6617 default:
6618 report_fatal_error("called on invalid register.");
6619 case PPC::R5:
6620 case PPC::R9:
6621 case PPC::X3:
6622 case PPC::X5:
6623 case PPC::X7:
6624 case PPC::X9:
6625 // These registers are 16 byte aligned which is the most strict aligment
6626 // we can support.
6627 return true;
6628 case PPC::R3:
6629 case PPC::R7:
6630 case PPC::X4:
6631 case PPC::X6:
6632 case PPC::X8:
6633 case PPC::X10:
6634 // The shadow of these registers in the PSA is 8 byte aligned.
6635 return RequiredAlign <= 8;
6636 case PPC::R4:
6637 case PPC::R6:
6638 case PPC::R8:
6639 case PPC::R10:
6640 return RequiredAlign <= 4;
6641 }
6642}
6643
6644static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6645 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6646 CCState &S) {
6647 AIXCCState &State = static_cast<AIXCCState &>(S);
6648 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6649 State.getMachineFunction().getSubtarget());
6650 const bool IsPPC64 = Subtarget.isPPC64();
6651 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6652 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6653
6654 if (ValVT == MVT::f128)
6655 report_fatal_error("f128 is unimplemented on AIX.");
6656
6657 if (ArgFlags.isNest())
6658 report_fatal_error("Nest arguments are unimplemented.");
6659
6660 static const MCPhysReg GPR_32[] = {// 32-bit registers.
6661 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6662 PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6663 static const MCPhysReg GPR_64[] = {// 64-bit registers.
6664 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6665 PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6666
6667 static const MCPhysReg VR[] = {// Vector registers.
6668 PPC::V2, PPC::V3, PPC::V4, PPC::V5,
6669 PPC::V6, PPC::V7, PPC::V8, PPC::V9,
6670 PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6671
6672 if (ArgFlags.isByVal()) {
6673 if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6674 report_fatal_error("Pass-by-value arguments with alignment greater than "
6675 "register width are not supported.");
6676
6677 const unsigned ByValSize = ArgFlags.getByValSize();
6678
6679 // An empty aggregate parameter takes up no storage and no registers,
6680 // but needs a MemLoc for a stack slot for the formal arguments side.
6681 if (ByValSize == 0) {
6682 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6683 State.getNextStackOffset(), RegVT,
6684 LocInfo));
6685 return false;
6686 }
6687
6688 const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6689 unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6690 for (const unsigned E = Offset + StackSize; Offset < E;
6691 Offset += PtrAlign.value()) {
6692 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6693 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6694 else {
6695 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6696 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6697 LocInfo));
6698 break;
6699 }
6700 }
6701 return false;
6702 }
6703
6704 // Arguments always reserve parameter save area.
6705 switch (ValVT.SimpleTy) {
6706 default:
6707 report_fatal_error("Unhandled value type for argument.");
6708 case MVT::i64:
6709 // i64 arguments should have been split to i32 for PPC32.
6710 assert(IsPPC64 && "PPC32 should have split i64 values.")(static_cast <bool> (IsPPC64 && "PPC32 should have split i64 values."
) ? void (0) : __assert_fail ("IsPPC64 && \"PPC32 should have split i64 values.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6710, __extension__
__PRETTY_FUNCTION__))
;
6711 [[fallthrough]];
6712 case MVT::i1:
6713 case MVT::i32: {
6714 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6715 // AIX integer arguments are always passed in register width.
6716 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6717 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6718 : CCValAssign::LocInfo::ZExt;
6719 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6720 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6721 else
6722 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6723
6724 return false;
6725 }
6726 case MVT::f32:
6727 case MVT::f64: {
6728 // Parameter save area (PSA) is reserved even if the float passes in fpr.
6729 const unsigned StoreSize = LocVT.getStoreSize();
6730 // Floats are always 4-byte aligned in the PSA on AIX.
6731 // This includes f64 in 64-bit mode for ABI compatibility.
6732 const unsigned Offset =
6733 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6734 unsigned FReg = State.AllocateReg(FPR);
6735 if (FReg)
6736 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6737
6738 // Reserve and initialize GPRs or initialize the PSA as required.
6739 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6740 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6741 assert(FReg && "An FPR should be available when a GPR is reserved.")(static_cast <bool> (FReg && "An FPR should be available when a GPR is reserved."
) ? void (0) : __assert_fail ("FReg && \"An FPR should be available when a GPR is reserved.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6741, __extension__
__PRETTY_FUNCTION__))
;
6742 if (State.isVarArg()) {
6743 // Successfully reserved GPRs are only initialized for vararg calls.
6744 // Custom handling is required for:
6745 // f64 in PPC32 needs to be split into 2 GPRs.
6746 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6747 State.addLoc(
6748 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6749 }
6750 } else {
6751 // If there are insufficient GPRs, the PSA needs to be initialized.
6752 // Initialization occurs even if an FPR was initialized for
6753 // compatibility with the AIX XL compiler. The full memory for the
6754 // argument will be initialized even if a prior word is saved in GPR.
6755 // A custom memLoc is used when the argument also passes in FPR so
6756 // that the callee handling can skip over it easily.
6757 State.addLoc(
6758 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6759 LocInfo)
6760 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6761 break;
6762 }
6763 }
6764
6765 return false;
6766 }
6767 case MVT::v4f32:
6768 case MVT::v4i32:
6769 case MVT::v8i16:
6770 case MVT::v16i8:
6771 case MVT::v2i64:
6772 case MVT::v2f64:
6773 case MVT::v1i128: {
6774 const unsigned VecSize = 16;
6775 const Align VecAlign(VecSize);
6776
6777 if (!State.isVarArg()) {
6778 // If there are vector registers remaining we don't consume any stack
6779 // space.
6780 if (unsigned VReg = State.AllocateReg(VR)) {
6781 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6782 return false;
6783 }
6784 // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6785 // might be allocated in the portion of the PSA that is shadowed by the
6786 // GPRs.
6787 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6788 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6789 return false;
6790 }
6791
6792 const unsigned PtrSize = IsPPC64 ? 8 : 4;
6793 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6794
6795 unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6796 // Burn any underaligned registers and their shadowed stack space until
6797 // we reach the required alignment.
6798 while (NextRegIndex != GPRs.size() &&
6799 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6800 // Shadow allocate register and its stack shadow.
6801 unsigned Reg = State.AllocateReg(GPRs);
6802 State.AllocateStack(PtrSize, PtrAlign);
6803 assert(Reg && "Allocating register unexpectedly failed.")(static_cast <bool> (Reg && "Allocating register unexpectedly failed."
) ? void (0) : __assert_fail ("Reg && \"Allocating register unexpectedly failed.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6803, __extension__
__PRETTY_FUNCTION__))
;
6804 (void)Reg;
6805 NextRegIndex = State.getFirstUnallocated(GPRs);
6806 }
6807
6808 // Vectors that are passed as fixed arguments are handled differently.
6809 // They are passed in VRs if any are available (unlike arguments passed
6810 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6811 // functions)
6812 if (State.isFixed(ValNo)) {
6813 if (unsigned VReg = State.AllocateReg(VR)) {
6814 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6815 // Shadow allocate GPRs and stack space even though we pass in a VR.
6816 for (unsigned I = 0; I != VecSize; I += PtrSize)
6817 State.AllocateReg(GPRs);
6818 State.AllocateStack(VecSize, VecAlign);
6819 return false;
6820 }
6821 // No vector registers remain so pass on the stack.
6822 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6823 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6824 return false;
6825 }
6826
6827 // If all GPRS are consumed then we pass the argument fully on the stack.
6828 if (NextRegIndex == GPRs.size()) {
6829 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6830 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6831 return false;
6832 }
6833
6834 // Corner case for 32-bit codegen. We have 2 registers to pass the first
6835 // half of the argument, and then need to pass the remaining half on the
6836 // stack.
6837 if (GPRs[NextRegIndex] == PPC::R9) {
6838 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6839 State.addLoc(
6840 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6841
6842 const unsigned FirstReg = State.AllocateReg(PPC::R9);
6843 const unsigned SecondReg = State.AllocateReg(PPC::R10);
6844 assert(FirstReg && SecondReg &&(static_cast <bool> (FirstReg && SecondReg &&
"Allocating R9 or R10 unexpectedly failed.") ? void (0) : __assert_fail
("FirstReg && SecondReg && \"Allocating R9 or R10 unexpectedly failed.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6845, __extension__
__PRETTY_FUNCTION__))
6845 "Allocating R9 or R10 unexpectedly failed.")(static_cast <bool> (FirstReg && SecondReg &&
"Allocating R9 or R10 unexpectedly failed.") ? void (0) : __assert_fail
("FirstReg && SecondReg && \"Allocating R9 or R10 unexpectedly failed.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6845, __extension__
__PRETTY_FUNCTION__))
;
6846 State.addLoc(
6847 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6848 State.addLoc(
6849 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6850 return false;
6851 }
6852
6853 // We have enough GPRs to fully pass the vector argument, and we have
6854 // already consumed any underaligned registers. Start with the custom
6855 // MemLoc and then the custom RegLocs.
6856 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6857 State.addLoc(
6858 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6859 for (unsigned I = 0; I != VecSize; I += PtrSize) {
6860 const unsigned Reg = State.AllocateReg(GPRs);
6861 assert(Reg && "Failed to allocated register for vararg vector argument")(static_cast <bool> (Reg && "Failed to allocated register for vararg vector argument"
) ? void (0) : __assert_fail ("Reg && \"Failed to allocated register for vararg vector argument\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6861, __extension__
__PRETTY_FUNCTION__))
;
6862 State.addLoc(
6863 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6864 }
6865 return false;
6866 }
6867 }
6868 return true;
6869}
6870
6871// So far, this function is only used by LowerFormalArguments_AIX()
6872static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6873 bool IsPPC64,
6874 bool HasP8Vector,
6875 bool HasVSX) {
6876 assert((IsPPC64 || SVT != MVT::i64) &&(static_cast <bool> ((IsPPC64 || SVT != MVT::i64) &&
"i64 should have been split for 32-bit codegen.") ? void (0)
: __assert_fail ("(IsPPC64 || SVT != MVT::i64) && \"i64 should have been split for 32-bit codegen.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6877, __extension__
__PRETTY_FUNCTION__))
6877 "i64 should have been split for 32-bit codegen.")(static_cast <bool> ((IsPPC64 || SVT != MVT::i64) &&
"i64 should have been split for 32-bit codegen.") ? void (0)
: __assert_fail ("(IsPPC64 || SVT != MVT::i64) && \"i64 should have been split for 32-bit codegen.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6877, __extension__
__PRETTY_FUNCTION__))
;
6878
6879 switch (SVT) {
6880 default:
6881 report_fatal_error("Unexpected value type for formal argument");
6882 case MVT::i1:
6883 case MVT::i32:
6884 case MVT::i64:
6885 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6886 case MVT::f32:
6887 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6888 case MVT::f64:
6889 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6890 case MVT::v4f32:
6891 case MVT::v4i32:
6892 case MVT::v8i16:
6893 case MVT::v16i8:
6894 case MVT::v2i64:
6895 case MVT::v2f64:
6896 case MVT::v1i128:
6897 return &PPC::VRRCRegClass;
6898 }
6899}
6900
6901static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6902 SelectionDAG &DAG, SDValue ArgValue,
6903 MVT LocVT, const SDLoc &dl) {
6904 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger())(static_cast <bool> (ValVT.isScalarInteger() &&
LocVT.isScalarInteger()) ? void (0) : __assert_fail ("ValVT.isScalarInteger() && LocVT.isScalarInteger()"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6904, __extension__
__PRETTY_FUNCTION__))
;
6905 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())(static_cast <bool> (ValVT.getFixedSizeInBits() < LocVT
.getFixedSizeInBits()) ? void (0) : __assert_fail ("ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6905, __extension__
__PRETTY_FUNCTION__))
;
6906
6907 if (Flags.isSExt())
6908 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6909 DAG.getValueType(ValVT));
6910 else if (Flags.isZExt())
6911 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6912 DAG.getValueType(ValVT));
6913
6914 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6915}
6916
6917static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6918 const unsigned LASize = FL->getLinkageSize();
6919
6920 if (PPC::GPRCRegClass.contains(Reg)) {
6921 assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&(static_cast <bool> (Reg >= PPC::R3 && Reg <=
PPC::R10 && "Reg must be a valid argument register!"
) ? void (0) : __assert_fail ("Reg >= PPC::R3 && Reg <= PPC::R10 && \"Reg must be a valid argument register!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6922, __extension__
__PRETTY_FUNCTION__))
6922 "Reg must be a valid argument register!")(static_cast <bool> (Reg >= PPC::R3 && Reg <=
PPC::R10 && "Reg must be a valid argument register!"
) ? void (0) : __assert_fail ("Reg >= PPC::R3 && Reg <= PPC::R10 && \"Reg must be a valid argument register!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6922, __extension__
__PRETTY_FUNCTION__))
;
6923 return LASize + 4 * (Reg - PPC::R3);
6924 }
6925
6926 if (PPC::G8RCRegClass.contains(Reg)) {
6927 assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&(static_cast <bool> (Reg >= PPC::X3 && Reg <=
PPC::X10 && "Reg must be a valid argument register!"
) ? void (0) : __assert_fail ("Reg >= PPC::X3 && Reg <= PPC::X10 && \"Reg must be a valid argument register!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6928, __extension__
__PRETTY_FUNCTION__))
6928 "Reg must be a valid argument register!")(static_cast <bool> (Reg >= PPC::X3 && Reg <=
PPC::X10 && "Reg must be a valid argument register!"
) ? void (0) : __assert_fail ("Reg >= PPC::X3 && Reg <= PPC::X10 && \"Reg must be a valid argument register!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6928, __extension__
__PRETTY_FUNCTION__))
;
6929 return LASize + 8 * (Reg - PPC::X3);
6930 }
6931
6932 llvm_unreachable("Only general purpose registers expected.")::llvm::llvm_unreachable_internal("Only general purpose registers expected."
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6932)
;
6933}
6934
6935// AIX ABI Stack Frame Layout:
6936//
6937// Low Memory +--------------------------------------------+
6938// SP +---> | Back chain | ---+
6939// | +--------------------------------------------+ |
6940// | | Saved Condition Register | |
6941// | +--------------------------------------------+ |
6942// | | Saved Linkage Register | |
6943// | +--------------------------------------------+ | Linkage Area
6944// | | Reserved for compilers | |
6945// | +--------------------------------------------+ |
6946// | | Reserved for binders | |
6947// | +--------------------------------------------+ |
6948// | | Saved TOC pointer | ---+
6949// | +--------------------------------------------+
6950// | | Parameter save area |
6951// | +--------------------------------------------+
6952// | | Alloca space |
6953// | +--------------------------------------------+
6954// | | Local variable space |
6955// | +--------------------------------------------+
6956// | | Float/int conversion temporary |
6957// | +--------------------------------------------+
6958// | | Save area for AltiVec registers |
6959// | +--------------------------------------------+
6960// | | AltiVec alignment padding |
6961// | +--------------------------------------------+
6962// | | Save area for VRSAVE register |
6963// | +--------------------------------------------+
6964// | | Save area for General Purpose registers |
6965// | +--------------------------------------------+
6966// | | Save area for Floating Point registers |
6967// | +--------------------------------------------+
6968// +---- | Back chain |
6969// High Memory +--------------------------------------------+
6970//
6971// Specifications:
6972// AIX 7.2 Assembler Language Reference
6973// Subroutine linkage convention
6974
6975SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6976 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6977 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6978 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6979
6980 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||(static_cast <bool> ((CallConv == CallingConv::C || CallConv
== CallingConv::Cold || CallConv == CallingConv::Fast) &&
"Unexpected calling convention!") ? void (0) : __assert_fail
("(CallConv == CallingConv::C || CallConv == CallingConv::Cold || CallConv == CallingConv::Fast) && \"Unexpected calling convention!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6982, __extension__
__PRETTY_FUNCTION__))
6981 CallConv == CallingConv::Fast) &&(static_cast <bool> ((CallConv == CallingConv::C || CallConv
== CallingConv::Cold || CallConv == CallingConv::Fast) &&
"Unexpected calling convention!") ? void (0) : __assert_fail
("(CallConv == CallingConv::C || CallConv == CallingConv::Cold || CallConv == CallingConv::Fast) && \"Unexpected calling convention!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6982, __extension__
__PRETTY_FUNCTION__))
6982 "Unexpected calling convention!")(static_cast <bool> ((CallConv == CallingConv::C || CallConv
== CallingConv::Cold || CallConv == CallingConv::Fast) &&
"Unexpected calling convention!") ? void (0) : __assert_fail
("(CallConv == CallingConv::C || CallConv == CallingConv::Cold || CallConv == CallingConv::Fast) && \"Unexpected calling convention!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 6982, __extension__
__PRETTY_FUNCTION__))
;
6983
6984 if (getTargetMachine().Options.GuaranteedTailCallOpt)
6985 report_fatal_error("Tail call support is unimplemented on AIX.");
6986
6987 if (useSoftFloat())
6988 report_fatal_error("Soft float support is unimplemented on AIX.");
6989
6990 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
6991
6992 const bool IsPPC64 = Subtarget.isPPC64();
6993 const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6994
6995 // Assign locations to all of the incoming arguments.
6996 SmallVector<CCValAssign, 16> ArgLocs;
6997 MachineFunction &MF = DAG.getMachineFunction();
6998 MachineFrameInfo &MFI = MF.getFrameInfo();
6999 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7000 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7001
7002 const EVT PtrVT = getPointerTy(MF.getDataLayout());
7003 // Reserve space for the linkage area on the stack.
7004 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7005 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7006 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7007
7008 SmallVector<SDValue, 8> MemOps;
7009
7010 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7011 CCValAssign &VA = ArgLocs[I++];
7012 MVT LocVT = VA.getLocVT();
7013 MVT ValVT = VA.getValVT();
7014 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7015 // For compatibility with the AIX XL compiler, the float args in the
7016 // parameter save area are initialized even if the argument is available
7017 // in register. The caller is required to initialize both the register
7018 // and memory, however, the callee can choose to expect it in either.
7019 // The memloc is dismissed here because the argument is retrieved from
7020 // the register.
7021 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
7022 continue;
7023
7024 auto HandleMemLoc = [&]() {
7025 const unsigned LocSize = LocVT.getStoreSize();
7026 const unsigned ValSize = ValVT.getStoreSize();
7027 assert((ValSize <= LocSize) &&(static_cast <bool> ((ValSize <= LocSize) &&
"Object size is larger than size of MemLoc") ? void (0) : __assert_fail
("(ValSize <= LocSize) && \"Object size is larger than size of MemLoc\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7028, __extension__
__PRETTY_FUNCTION__))
7028 "Object size is larger than size of MemLoc")(static_cast <bool> ((ValSize <= LocSize) &&
"Object size is larger than size of MemLoc") ? void (0) : __assert_fail
("(ValSize <= LocSize) && \"Object size is larger than size of MemLoc\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7028, __extension__
__PRETTY_FUNCTION__))
;
7029 int CurArgOffset = VA.getLocMemOffset();
7030 // Objects are right-justified because AIX is big-endian.
7031 if (LocSize > ValSize)
7032 CurArgOffset += LocSize - ValSize;
7033 // Potential tail calls could cause overwriting of argument stack slots.
7034 const bool IsImmutable =
7035 !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7036 (CallConv == CallingConv::Fast));
7037 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7038 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7039 SDValue ArgValue =
7040 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7041 InVals.push_back(ArgValue);
7042 };
7043
7044 // Vector arguments to VaArg functions are passed both on the stack, and
7045 // in any available GPRs. Load the value from the stack and add the GPRs
7046 // as live ins.
7047 if (VA.isMemLoc() && VA.needsCustom()) {
7048 assert(ValVT.isVector() && "Unexpected Custom MemLoc type.")(static_cast <bool> (ValVT.isVector() && "Unexpected Custom MemLoc type."
) ? void (0) : __assert_fail ("ValVT.isVector() && \"Unexpected Custom MemLoc type.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7048, __extension__
__PRETTY_FUNCTION__))
;
7049 assert(isVarArg && "Only use custom memloc for vararg.")(static_cast <bool> (isVarArg && "Only use custom memloc for vararg."
) ? void (0) : __assert_fail ("isVarArg && \"Only use custom memloc for vararg.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7049, __extension__
__PRETTY_FUNCTION__))
;
7050 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
7051 // matching custom RegLocs.
7052 const unsigned OriginalValNo = VA.getValNo();
7053 (void)OriginalValNo;
7054
7055 auto HandleCustomVecRegLoc = [&]() {
7056 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&(static_cast <bool> (I != End && ArgLocs[I].isRegLoc
() && ArgLocs[I].needsCustom() && "Missing custom RegLoc."
) ? void (0) : __assert_fail ("I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && \"Missing custom RegLoc.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7057, __extension__
__PRETTY_FUNCTION__))
7057 "Missing custom RegLoc.")(static_cast <bool> (I != End && ArgLocs[I].isRegLoc
() && ArgLocs[I].needsCustom() && "Missing custom RegLoc."
) ? void (0) : __assert_fail ("I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && \"Missing custom RegLoc.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7057, __extension__
__PRETTY_FUNCTION__))
;
7058 VA = ArgLocs[I++];
7059 assert(VA.getValVT().isVector() &&(static_cast <bool> (VA.getValVT().isVector() &&
"Unexpected Val type for custom RegLoc.") ? void (0) : __assert_fail
("VA.getValVT().isVector() && \"Unexpected Val type for custom RegLoc.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7060, __extension__
__PRETTY_FUNCTION__))
7060 "Unexpected Val type for custom RegLoc.")(static_cast <bool> (VA.getValVT().isVector() &&
"Unexpected Val type for custom RegLoc.") ? void (0) : __assert_fail
("VA.getValVT().isVector() && \"Unexpected Val type for custom RegLoc.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7060, __extension__
__PRETTY_FUNCTION__))
;
7061 assert(VA.getValNo() == OriginalValNo &&(static_cast <bool> (VA.getValNo() == OriginalValNo &&
"ValNo mismatch between custom MemLoc and RegLoc.") ? void (
0) : __assert_fail ("VA.getValNo() == OriginalValNo && \"ValNo mismatch between custom MemLoc and RegLoc.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7062, __extension__
__PRETTY_FUNCTION__))
7062 "ValNo mismatch between custom MemLoc and RegLoc.")(static_cast <bool> (VA.getValNo() == OriginalValNo &&
"ValNo mismatch between custom MemLoc and RegLoc.") ? void (
0) : __assert_fail ("VA.getValNo() == OriginalValNo && \"ValNo mismatch between custom MemLoc and RegLoc.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7062, __extension__
__PRETTY_FUNCTION__))
;
7063 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
7064 MF.addLiveIn(VA.getLocReg(),
7065 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7066 Subtarget.hasVSX()));
7067 };
7068
7069 HandleMemLoc();
7070 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7071 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7072 // R10.
7073 HandleCustomVecRegLoc();
7074 HandleCustomVecRegLoc();
7075
7076 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7077 // we passed the vector in R5, R6, R7 and R8.
7078 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7079 assert(!IsPPC64 &&(static_cast <bool> (!IsPPC64 && "Only 2 custom RegLocs expected for 64-bit codegen."
) ? void (0) : __assert_fail ("!IsPPC64 && \"Only 2 custom RegLocs expected for 64-bit codegen.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7080, __extension__
__PRETTY_FUNCTION__))
7080 "Only 2 custom RegLocs expected for 64-bit codegen.")(static_cast <bool> (!IsPPC64 && "Only 2 custom RegLocs expected for 64-bit codegen."
) ? void (0) : __assert_fail ("!IsPPC64 && \"Only 2 custom RegLocs expected for 64-bit codegen.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7080, __extension__
__PRETTY_FUNCTION__))
;
7081 HandleCustomVecRegLoc();
7082 HandleCustomVecRegLoc();
7083 }
7084
7085 continue;
7086 }
7087
7088 if (VA.isRegLoc()) {
7089 if (VA.getValVT().isScalarInteger())
7090 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7091 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7092 switch (VA.getValVT().SimpleTy) {
7093 default:
7094 report_fatal_error("Unhandled value type for argument.");
7095 case MVT::f32:
7096 FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
7097 break;
7098 case MVT::f64:
7099 FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
7100 break;
7101 }
7102 } else if (VA.getValVT().isVector()) {
7103 switch (VA.getValVT().SimpleTy) {
7104 default:
7105 report_fatal_error("Unhandled value type for argument.");
7106 case MVT::v16i8:
7107 FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
7108 break;
7109 case MVT::v8i16:
7110 FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
7111 break;
7112 case MVT::v4i32:
7113 case MVT::v2i64:
7114 case MVT::v1i128:
7115 FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
7116 break;
7117 case MVT::v4f32:
7118 case MVT::v2f64:
7119 FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
7120 break;
7121 }
7122 }
7123 }
7124
7125 if (Flags.isByVal() && VA.isMemLoc()) {
7126 const unsigned Size =
7127 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7128 PtrByteSize);
7129 const int FI = MF.getFrameInfo().CreateFixedObject(
7130 Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7131 /* IsAliased */ true);
7132 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7133 InVals.push_back(FIN);
7134
7135 continue;
7136 }
7137
7138 if (Flags.isByVal()) {
7139 assert(VA.isRegLoc() && "MemLocs should already be handled.")(static_cast <bool> (VA.isRegLoc() && "MemLocs should already be handled."
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"MemLocs should already be handled.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7139, __extension__
__PRETTY_FUNCTION__))
;
7140
7141 const MCPhysReg ArgReg = VA.getLocReg();
7142 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7143
7144 if (Flags.getNonZeroByValAlign() > PtrByteSize)
7145 report_fatal_error("Over aligned byvals not supported yet.");
7146
7147 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7148 const int FI = MF.getFrameInfo().CreateFixedObject(
7149 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7150 /* IsAliased */ true);
7151 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7152 InVals.push_back(FIN);
7153
7154 // Add live ins for all the RegLocs for the same ByVal.
7155 const TargetRegisterClass *RegClass =
7156 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7157
7158 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7159 unsigned Offset) {
7160 const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7161 // Since the callers side has left justified the aggregate in the
7162 // register, we can simply store the entire register into the stack
7163 // slot.
7164 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7165 // The store to the fixedstack object is needed becuase accessing a
7166 // field of the ByVal will use a gep and load. Ideally we will optimize
7167 // to extracting the value from the register directly, and elide the
7168 // stores when the arguments address is not taken, but that will need to
7169 // be future work.
7170 SDValue Store = DAG.getStore(
7171 CopyFrom.getValue(1), dl, CopyFrom,
7172 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7173 MachinePointerInfo::getFixedStack(MF, FI, Offset));
7174
7175 MemOps.push_back(Store);
7176 };
7177
7178 unsigned Offset = 0;
7179 HandleRegLoc(VA.getLocReg(), Offset);
7180 Offset += PtrByteSize;
7181 for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7182 Offset += PtrByteSize) {
7183 assert(ArgLocs[I].getValNo() == VA.getValNo() &&(static_cast <bool> (ArgLocs[I].getValNo() == VA.getValNo
() && "RegLocs should be for ByVal argument.") ? void
(0) : __assert_fail ("ArgLocs[I].getValNo() == VA.getValNo() && \"RegLocs should be for ByVal argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7184, __extension__
__PRETTY_FUNCTION__))
7184 "RegLocs should be for ByVal argument.")(static_cast <bool> (ArgLocs[I].getValNo() == VA.getValNo
() && "RegLocs should be for ByVal argument.") ? void
(0) : __assert_fail ("ArgLocs[I].getValNo() == VA.getValNo() && \"RegLocs should be for ByVal argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7184, __extension__
__PRETTY_FUNCTION__))
;
7185
7186 const CCValAssign RL = ArgLocs[I++];
7187 HandleRegLoc(RL.getLocReg(), Offset);
7188 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7189 }
7190
7191 if (Offset != StackSize) {
7192 assert(ArgLocs[I].getValNo() == VA.getValNo() &&(static_cast <bool> (ArgLocs[I].getValNo() == VA.getValNo
() && "Expected MemLoc for remaining bytes.") ? void (
0) : __assert_fail ("ArgLocs[I].getValNo() == VA.getValNo() && \"Expected MemLoc for remaining bytes.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7193, __extension__
__PRETTY_FUNCTION__))
7193 "Expected MemLoc for remaining bytes.")(static_cast <bool> (ArgLocs[I].getValNo() == VA.getValNo
() && "Expected MemLoc for remaining bytes.") ? void (
0) : __assert_fail ("ArgLocs[I].getValNo() == VA.getValNo() && \"Expected MemLoc for remaining bytes.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7193, __extension__
__PRETTY_FUNCTION__))
;
7194 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.")(static_cast <bool> (ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."
) ? void (0) : __assert_fail ("ArgLocs[I].isMemLoc() && \"Expected MemLoc for remaining bytes.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7194, __extension__
__PRETTY_FUNCTION__))
;
7195 // Consume the MemLoc.The InVal has already been emitted, so nothing
7196 // more needs to be done.
7197 ++I;
7198 }
7199
7200 continue;
7201 }
7202
7203 if (VA.isRegLoc() && !VA.needsCustom()) {
7204 MVT::SimpleValueType SVT = ValVT.SimpleTy;
7205 Register VReg =
7206 MF.addLiveIn(VA.getLocReg(),
7207 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7208 Subtarget.hasVSX()));
7209 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7210 if (ValVT.isScalarInteger() &&
7211 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7212 ArgValue =
7213 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7214 }
7215 InVals.push_back(ArgValue);
7216 continue;
7217 }
7218 if (VA.isMemLoc()) {
7219 HandleMemLoc();
7220 continue;
7221 }
7222 }
7223
7224 // On AIX a minimum of 8 words is saved to the parameter save area.
7225 const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7226 // Area that is at least reserved in the caller of this function.
7227 unsigned CallerReservedArea =
7228 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7229
7230 // Set the size that is at least reserved in caller of this function. Tail
7231 // call optimized function's reserved stack space needs to be aligned so
7232 // that taking the difference between two stack areas will result in an
7233 // aligned stack.
7234 CallerReservedArea =
7235 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7236 FuncInfo->setMinReservedArea(CallerReservedArea);
7237
7238 if (isVarArg) {
7239 FuncInfo->setVarArgsFrameIndex(
7240 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7241 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7242
7243 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7244 PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7245
7246 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7247 PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7248 const unsigned NumGPArgRegs = std::size(IsPPC64 ? GPR_64 : GPR_32);
7249
7250 // The fixed integer arguments of a variadic function are stored to the
7251 // VarArgsFrameIndex on the stack so that they may be loaded by
7252 // dereferencing the result of va_next.
7253 for (unsigned GPRIndex =
7254 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7255 GPRIndex < NumGPArgRegs; ++GPRIndex) {
7256
7257 const Register VReg =
7258 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7259 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7260
7261 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7262 SDValue Store =
7263 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7264 MemOps.push_back(Store);
7265 // Increment the address for the next argument to store.
7266 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7267 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7268 }
7269 }
7270
7271 if (!MemOps.empty())
7272 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7273
7274 return Chain;
7275}
7276
7277SDValue PPCTargetLowering::LowerCall_AIX(
7278 SDValue Chain, SDValue Callee, CallFlags CFlags,
7279 const SmallVectorImpl<ISD::OutputArg> &Outs,
7280 const SmallVectorImpl<SDValue> &OutVals,
7281 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7282 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7283 const CallBase *CB) const {
7284 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7285 // AIX ABI stack frame layout.
7286
7287 assert((CFlags.CallConv == CallingConv::C ||(static_cast <bool> ((CFlags.CallConv == CallingConv::C
|| CFlags.CallConv == CallingConv::Cold || CFlags.CallConv ==
CallingConv::Fast) && "Unexpected calling convention!"
) ? void (0) : __assert_fail ("(CFlags.CallConv == CallingConv::C || CFlags.CallConv == CallingConv::Cold || CFlags.CallConv == CallingConv::Fast) && \"Unexpected calling convention!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7290, __extension__
__PRETTY_FUNCTION__))
7288 CFlags.CallConv == CallingConv::Cold ||(static_cast <bool> ((CFlags.CallConv == CallingConv::C
|| CFlags.CallConv == CallingConv::Cold || CFlags.CallConv ==
CallingConv::Fast) && "Unexpected calling convention!"
) ? void (0) : __assert_fail ("(CFlags.CallConv == CallingConv::C || CFlags.CallConv == CallingConv::Cold || CFlags.CallConv == CallingConv::Fast) && \"Unexpected calling convention!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7290, __extension__
__PRETTY_FUNCTION__))
7289 CFlags.CallConv == CallingConv::Fast) &&(static_cast <bool> ((CFlags.CallConv == CallingConv::C
|| CFlags.CallConv == CallingConv::Cold || CFlags.CallConv ==
CallingConv::Fast) && "Unexpected calling convention!"
) ? void (0) : __assert_fail ("(CFlags.CallConv == CallingConv::C || CFlags.CallConv == CallingConv::Cold || CFlags.CallConv == CallingConv::Fast) && \"Unexpected calling convention!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7290, __extension__
__PRETTY_FUNCTION__))
7290 "Unexpected calling convention!")(static_cast <bool> ((CFlags.CallConv == CallingConv::C
|| CFlags.CallConv == CallingConv::Cold || CFlags.CallConv ==
CallingConv::Fast) && "Unexpected calling convention!"
) ? void (0) : __assert_fail ("(CFlags.CallConv == CallingConv::C || CFlags.CallConv == CallingConv::Cold || CFlags.CallConv == CallingConv::Fast) && \"Unexpected calling convention!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7290, __extension__
__PRETTY_FUNCTION__))
;
7291
7292 if (CFlags.IsPatchPoint)
7293 report_fatal_error("This call type is unimplemented on AIX.");
7294
7295 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
7296
7297 MachineFunction &MF = DAG.getMachineFunction();
7298 SmallVector<CCValAssign, 16> ArgLocs;
7299 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7300 *DAG.getContext());
7301
7302 // Reserve space for the linkage save area (LSA) on the stack.
7303 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7304 // [SP][CR][LR][2 x reserved][TOC].
7305 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7306 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7307 const bool IsPPC64 = Subtarget.isPPC64();
7308 const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7309 const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7310 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7311 CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7312
7313 // The prolog code of the callee may store up to 8 GPR argument registers to
7314 // the stack, allowing va_start to index over them in memory if the callee
7315 // is variadic.
7316 // Because we cannot tell if this is needed on the caller side, we have to
7317 // conservatively assume that it is needed. As such, make sure we have at
7318 // least enough stack space for the caller to store the 8 GPRs.
7319 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7320 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7321 CCInfo.getNextStackOffset());
7322
7323 // Adjust the stack pointer for the new arguments...
7324 // These operations are automatically eliminated by the prolog/epilog pass.
7325 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7326 SDValue CallSeqStart = Chain;
7327
7328 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7329 SmallVector<SDValue, 8> MemOpChains;
7330
7331 // Set up a copy of the stack pointer for loading and storing any
7332 // arguments that may not fit in the registers available for argument
7333 // passing.
7334 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7335 : DAG.getRegister(PPC::R1, MVT::i32);
7336
7337 for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7338 const unsigned ValNo = ArgLocs[I].getValNo();
7339 SDValue Arg = OutVals[ValNo];
7340 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7341
7342 if (Flags.isByVal()) {
7343 const unsigned ByValSize = Flags.getByValSize();
7344
7345 // Nothing to do for zero-sized ByVals on the caller side.
7346 if (!ByValSize) {
7347 ++I;
7348 continue;
7349 }
7350
7351 auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7352 return DAG.getExtLoad(
7353 ISD::ZEXTLOAD, dl, PtrVT, Chain,
7354 (LoadOffset != 0)
7355 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7356 : Arg,
7357 MachinePointerInfo(), VT);
7358 };
7359
7360 unsigned LoadOffset = 0;
7361
7362 // Initialize registers, which are fully occupied by the by-val argument.
7363 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7364 SDValue Load = GetLoad(PtrVT, LoadOffset);
7365 MemOpChains.push_back(Load.getValue(1));
7366 LoadOffset += PtrByteSize;
7367 const CCValAssign &ByValVA = ArgLocs[I++];
7368 assert(ByValVA.getValNo() == ValNo &&(static_cast <bool> (ByValVA.getValNo() == ValNo &&
"Unexpected location for pass-by-value argument.") ? void (0
) : __assert_fail ("ByValVA.getValNo() == ValNo && \"Unexpected location for pass-by-value argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7369, __extension__
__PRETTY_FUNCTION__))
7369 "Unexpected location for pass-by-value argument.")(static_cast <bool> (ByValVA.getValNo() == ValNo &&
"Unexpected location for pass-by-value argument.") ? void (0
) : __assert_fail ("ByValVA.getValNo() == ValNo && \"Unexpected location for pass-by-value argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7369, __extension__
__PRETTY_FUNCTION__))
;
7370 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7371 }
7372
7373 if (LoadOffset == ByValSize)
7374 continue;
7375
7376 // There must be one more loc to handle the remainder.
7377 assert(ArgLocs[I].getValNo() == ValNo &&(static_cast <bool> (ArgLocs[I].getValNo() == ValNo &&
"Expected additional location for by-value argument.") ? void
(0) : __assert_fail ("ArgLocs[I].getValNo() == ValNo && \"Expected additional location for by-value argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7378, __extension__
__PRETTY_FUNCTION__))
7378 "Expected additional location for by-value argument.")(static_cast <bool> (ArgLocs[I].getValNo() == ValNo &&
"Expected additional location for by-value argument.") ? void
(0) : __assert_fail ("ArgLocs[I].getValNo() == ValNo && \"Expected additional location for by-value argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7378, __extension__
__PRETTY_FUNCTION__))
;
7379
7380 if (ArgLocs[I].isMemLoc()) {
7381 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.")(static_cast <bool> (LoadOffset < ByValSize &&
"Unexpected memloc for by-val arg.") ? void (0) : __assert_fail
("LoadOffset < ByValSize && \"Unexpected memloc for by-val arg.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7381, __extension__
__PRETTY_FUNCTION__))
;
7382 const CCValAssign &ByValVA = ArgLocs[I++];
7383 ISD::ArgFlagsTy MemcpyFlags = Flags;
7384 // Only memcpy the bytes that don't pass in register.
7385 MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7386 Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7387 (LoadOffset != 0)
7388 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7389 : Arg,
7390 DAG.getObjectPtrOffset(dl, StackPtr,
7391 TypeSize::Fixed(ByValVA.getLocMemOffset())),
7392 CallSeqStart, MemcpyFlags, DAG, dl);
7393 continue;
7394 }
7395
7396 // Initialize the final register residue.
7397 // Any residue that occupies the final by-val arg register must be
7398 // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7399 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7400 // 2 and 1 byte loads.
7401 const unsigned ResidueBytes = ByValSize % PtrByteSize;
7402 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&(static_cast <bool> (ResidueBytes != 0 && LoadOffset
+ PtrByteSize > ByValSize && "Unexpected register residue for by-value argument."
) ? void (0) : __assert_fail ("ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && \"Unexpected register residue for by-value argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7403, __extension__
__PRETTY_FUNCTION__))
7403 "Unexpected register residue for by-value argument.")(static_cast <bool> (ResidueBytes != 0 && LoadOffset
+ PtrByteSize > ByValSize && "Unexpected register residue for by-value argument."
) ? void (0) : __assert_fail ("ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && \"Unexpected register residue for by-value argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7403, __extension__
__PRETTY_FUNCTION__))
;
7404 SDValue ResidueVal;
7405 for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7406 const unsigned N = llvm::bit_floor(ResidueBytes - Bytes);
7407 const MVT VT =
7408 N == 1 ? MVT::i8
7409 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7410 SDValue Load = GetLoad(VT, LoadOffset);
7411 MemOpChains.push_back(Load.getValue(1));
7412 LoadOffset += N;
7413 Bytes += N;
7414
7415 // By-val arguments are passed left-justfied in register.
7416 // Every load here needs to be shifted, otherwise a full register load
7417 // should have been used.
7418 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&(static_cast <bool> (PtrVT.getSimpleVT().getSizeInBits(
) > (Bytes * 8) && "Unexpected load emitted during handling of pass-by-value "
"argument.") ? void (0) : __assert_fail ("PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && \"Unexpected load emitted during handling of pass-by-value \" \"argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7420, __extension__
__PRETTY_FUNCTION__))
7419 "Unexpected load emitted during handling of pass-by-value "(static_cast <bool> (PtrVT.getSimpleVT().getSizeInBits(
) > (Bytes * 8) && "Unexpected load emitted during handling of pass-by-value "
"argument.") ? void (0) : __assert_fail ("PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && \"Unexpected load emitted during handling of pass-by-value \" \"argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7420, __extension__
__PRETTY_FUNCTION__))
7420 "argument.")(static_cast <bool> (PtrVT.getSimpleVT().getSizeInBits(
) > (Bytes * 8) && "Unexpected load emitted during handling of pass-by-value "
"argument.") ? void (0) : __assert_fail ("PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && \"Unexpected load emitted during handling of pass-by-value \" \"argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7420, __extension__
__PRETTY_FUNCTION__))
;
7421 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7422 EVT ShiftAmountTy =
7423 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7424 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7425 SDValue ShiftedLoad =
7426 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7427 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7428 ShiftedLoad)
7429 : ShiftedLoad;
7430 }
7431
7432 const CCValAssign &ByValVA = ArgLocs[I++];
7433 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7434 continue;
7435 }
7436
7437 CCValAssign &VA = ArgLocs[I++];
7438 const MVT LocVT = VA.getLocVT();
7439 const MVT ValVT = VA.getValVT();
7440
7441 switch (VA.getLocInfo()) {
7442 default:
7443 report_fatal_error("Unexpected argument extension type.");
7444 case CCValAssign::Full:
7445 break;
7446 case CCValAssign::ZExt:
7447 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7448 break;
7449 case CCValAssign::SExt:
7450 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7451 break;
7452 }
7453
7454 if (VA.isRegLoc() && !VA.needsCustom()) {
7455 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7456 continue;
7457 }
7458
7459 // Vector arguments passed to VarArg functions need custom handling when
7460 // they are passed (at least partially) in GPRs.
7461 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7462 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.")(static_cast <bool> (CFlags.IsVarArg && "Custom MemLocs only used for Vector args."
) ? void (0) : __assert_fail ("CFlags.IsVarArg && \"Custom MemLocs only used for Vector args.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7462, __extension__
__PRETTY_FUNCTION__))
;
7463 // Store value to its stack slot.
7464 SDValue PtrOff =
7465 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7466 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7467 SDValue Store =
7468 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7469 MemOpChains.push_back(Store);
7470 const unsigned OriginalValNo = VA.getValNo();
7471 // Then load the GPRs from the stack
7472 unsigned LoadOffset = 0;
7473 auto HandleCustomVecRegLoc = [&]() {
7474 assert(I != E && "Unexpected end of CCvalAssigns.")(static_cast <bool> (I != E && "Unexpected end of CCvalAssigns."
) ? void (0) : __assert_fail ("I != E && \"Unexpected end of CCvalAssigns.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7474, __extension__
__PRETTY_FUNCTION__))
;
7475 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&(static_cast <bool> (ArgLocs[I].isRegLoc() && ArgLocs
[I].needsCustom() && "Expected custom RegLoc.") ? void
(0) : __assert_fail ("ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && \"Expected custom RegLoc.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7476, __extension__
__PRETTY_FUNCTION__))
7476 "Expected custom RegLoc.")(static_cast <bool> (ArgLocs[I].isRegLoc() && ArgLocs
[I].needsCustom() && "Expected custom RegLoc.") ? void
(0) : __assert_fail ("ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && \"Expected custom RegLoc.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7476, __extension__
__PRETTY_FUNCTION__))
;
7477 CCValAssign RegVA = ArgLocs[I++];
7478 assert(RegVA.getValNo() == OriginalValNo &&(static_cast <bool> (RegVA.getValNo() == OriginalValNo &&
"Custom MemLoc ValNo and custom RegLoc ValNo must match.") ?
void (0) : __assert_fail ("RegVA.getValNo() == OriginalValNo && \"Custom MemLoc ValNo and custom RegLoc ValNo must match.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7479, __extension__
__PRETTY_FUNCTION__))
7479 "Custom MemLoc ValNo and custom RegLoc ValNo must match.")(static_cast <bool> (RegVA.getValNo() == OriginalValNo &&
"Custom MemLoc ValNo and custom RegLoc ValNo must match.") ?
void (0) : __assert_fail ("RegVA.getValNo() == OriginalValNo && \"Custom MemLoc ValNo and custom RegLoc ValNo must match.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7479, __extension__
__PRETTY_FUNCTION__))
;
7480 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7481 DAG.getConstant(LoadOffset, dl, PtrVT));
7482 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7483 MemOpChains.push_back(Load.getValue(1));
7484 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7485 LoadOffset += PtrByteSize;
7486 };
7487
7488 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7489 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7490 // R10.
7491 HandleCustomVecRegLoc();
7492 HandleCustomVecRegLoc();
7493
7494 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7495 ArgLocs[I].getValNo() == OriginalValNo) {
7496 assert(!IsPPC64 &&(static_cast <bool> (!IsPPC64 && "Only 2 custom RegLocs expected for 64-bit codegen."
) ? void (0) : __assert_fail ("!IsPPC64 && \"Only 2 custom RegLocs expected for 64-bit codegen.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7497, __extension__
__PRETTY_FUNCTION__))
7497 "Only 2 custom RegLocs expected for 64-bit codegen.")(static_cast <bool> (!IsPPC64 && "Only 2 custom RegLocs expected for 64-bit codegen."
) ? void (0) : __assert_fail ("!IsPPC64 && \"Only 2 custom RegLocs expected for 64-bit codegen.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7497, __extension__
__PRETTY_FUNCTION__))
;
7498 HandleCustomVecRegLoc();
7499 HandleCustomVecRegLoc();
7500 }
7501
7502 continue;
7503 }
7504
7505 if (VA.isMemLoc()) {
7506 SDValue PtrOff =
7507 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7508 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7509 MemOpChains.push_back(
7510 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7511
7512 continue;
7513 }
7514
7515 if (!ValVT.isFloatingPoint())
7516 report_fatal_error(
7517 "Unexpected register handling for calling convention.");
7518
7519 // Custom handling is used for GPR initializations for vararg float
7520 // arguments.
7521 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&(static_cast <bool> (VA.isRegLoc() && VA.needsCustom
() && CFlags.IsVarArg && LocVT.isInteger() &&
"Custom register handling only expected for VarArg.") ? void
(0) : __assert_fail ("VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && LocVT.isInteger() && \"Custom register handling only expected for VarArg.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7523, __extension__
__PRETTY_FUNCTION__))
7522 LocVT.isInteger() &&(static_cast <bool> (VA.isRegLoc() && VA.needsCustom
() && CFlags.IsVarArg && LocVT.isInteger() &&
"Custom register handling only expected for VarArg.") ? void
(0) : __assert_fail ("VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && LocVT.isInteger() && \"Custom register handling only expected for VarArg.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7523, __extension__
__PRETTY_FUNCTION__))
7523 "Custom register handling only expected for VarArg.")(static_cast <bool> (VA.isRegLoc() && VA.needsCustom
() && CFlags.IsVarArg && LocVT.isInteger() &&
"Custom register handling only expected for VarArg.") ? void
(0) : __assert_fail ("VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && LocVT.isInteger() && \"Custom register handling only expected for VarArg.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7523, __extension__
__PRETTY_FUNCTION__))
;
7524
7525 SDValue ArgAsInt =
7526 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7527
7528 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7529 // f32 in 32-bit GPR
7530 // f64 in 64-bit GPR
7531 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7532 else if (Arg.getValueType().getFixedSizeInBits() <
7533 LocVT.getFixedSizeInBits())
7534 // f32 in 64-bit GPR.
7535 RegsToPass.push_back(std::make_pair(
7536 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7537 else {
7538 // f64 in two 32-bit GPRs
7539 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7540 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&(static_cast <bool> (Arg.getValueType() == MVT::f64 &&
CFlags.IsVarArg && !IsPPC64 && "Unexpected custom register for argument!"
) ? void (0) : __assert_fail ("Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && \"Unexpected custom register for argument!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7541, __extension__
__PRETTY_FUNCTION__))
7541 "Unexpected custom register for argument!")(static_cast <bool> (Arg.getValueType() == MVT::f64 &&
CFlags.IsVarArg && !IsPPC64 && "Unexpected custom register for argument!"
) ? void (0) : __assert_fail ("Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && \"Unexpected custom register for argument!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7541, __extension__
__PRETTY_FUNCTION__))
;
7542 CCValAssign &GPR1 = VA;
7543 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7544 DAG.getConstant(32, dl, MVT::i8));
7545 RegsToPass.push_back(std::make_pair(
7546 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7547
7548 if (I != E) {
7549 // If only 1 GPR was available, there will only be one custom GPR and
7550 // the argument will also pass in memory.
7551 CCValAssign &PeekArg = ArgLocs[I];
7552 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7553 assert(PeekArg.needsCustom() && "A second custom GPR is expected.")(static_cast <bool> (PeekArg.needsCustom() && "A second custom GPR is expected."
) ? void (0) : __assert_fail ("PeekArg.needsCustom() && \"A second custom GPR is expected.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7553, __extension__
__PRETTY_FUNCTION__))
;
7554 CCValAssign &GPR2 = ArgLocs[I++];
7555 RegsToPass.push_back(std::make_pair(
7556 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7557 }
7558 }
7559 }
7560 }
7561
7562 if (!MemOpChains.empty())
7563 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7564
7565 // For indirect calls, we need to save the TOC base to the stack for
7566 // restoration after the call.
7567 if (CFlags.IsIndirect) {
7568 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.")(static_cast <bool> (!CFlags.IsTailCall && "Indirect tail-calls not supported."
) ? void (0) : __assert_fail ("!CFlags.IsTailCall && \"Indirect tail-calls not supported.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7568, __extension__
__PRETTY_FUNCTION__))
;
7569 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7570 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7571 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7572 const unsigned TOCSaveOffset =
7573 Subtarget.getFrameLowering()->getTOCSaveOffset();
7574
7575 setUsesTOCBasePtr(DAG);
7576 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7577 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7578 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7579 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7580 Chain = DAG.getStore(
7581 Val.getValue(1), dl, Val, AddPtr,
7582 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7583 }
7584
7585 // Build a sequence of copy-to-reg nodes chained together with token chain
7586 // and flag operands which copy the outgoing args into the appropriate regs.
7587 SDValue InGlue;
7588 for (auto Reg : RegsToPass) {
7589 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InGlue);
7590 InGlue = Chain.getValue(1);
7591 }
7592
7593 const int SPDiff = 0;
7594 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
7595 Callee, SPDiff, NumBytes, Ins, InVals, CB);
7596}
7597
7598bool
7599PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7600 MachineFunction &MF, bool isVarArg,
7601 const SmallVectorImpl<ISD::OutputArg> &Outs,
7602 LLVMContext &Context) const {
7603 SmallVector<CCValAssign, 16> RVLocs;
7604 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7605 return CCInfo.CheckReturn(
7606 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7607 ? RetCC_PPC_Cold
7608 : RetCC_PPC);
7609}
7610
7611SDValue
7612PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7613 bool isVarArg,
7614 const SmallVectorImpl<ISD::OutputArg> &Outs,
7615 const SmallVectorImpl<SDValue> &OutVals,
7616 const SDLoc &dl, SelectionDAG &DAG) const {
7617 SmallVector<CCValAssign, 16> RVLocs;
7618 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7619 *DAG.getContext());
7620 CCInfo.AnalyzeReturn(Outs,
7621 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7622 ? RetCC_PPC_Cold
7623 : RetCC_PPC);
7624
7625 SDValue Glue;
7626 SmallVector<SDValue, 4> RetOps(1, Chain);
7627
7628 // Copy the result values into the output registers.
7629 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7630 CCValAssign &VA = RVLocs[i];
7631 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", 7631, __extension__
__PRETTY_FUNCTION__))
;
7632
7633 SDValue Arg = OutVals[RealResIdx];
7634
7635 switch (VA.getLocInfo()) {
7636 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 7636)
;
7637 case CCValAssign::Full: break;
7638 case CCValAssign::AExt:
7639 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7640 break;
7641 case CCValAssign::ZExt:
7642 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7643 break;
7644 case CCValAssign::SExt:
7645 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7646 break;
7647 }
7648 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7649 bool isLittleEndian = Subtarget.isLittleEndian();
7650 // Legalize ret f64 -> ret 2 x i32.
7651 SDValue SVal =
7652 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7653 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7654 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Glue);
7655 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7656 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7657 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7658 Glue = Chain.getValue(1);
7659 VA = RVLocs[++i]; // skip ahead to next loc
7660 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Glue);
7661 } else
7662 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
7663 Glue = Chain.getValue(1);
7664 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7665 }
7666
7667 RetOps[0] = Chain; // Update chain.
7668
7669 // Add the glue if we have it.
7670 if (Glue.getNode())
7671 RetOps.push_back(Glue);
7672
7673 return DAG.getNode(PPCISD::RET_GLUE, dl, MVT::Other, RetOps);
7674}
7675
7676SDValue
7677PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7678 SelectionDAG &DAG) const {
7679 SDLoc dl(Op);
7680
7681 // Get the correct type for integers.
7682 EVT IntVT = Op.getValueType();
7683
7684 // Get the inputs.
7685 SDValue Chain = Op.getOperand(0);
7686 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7687 // Build a DYNAREAOFFSET node.
7688 SDValue Ops[2] = {Chain, FPSIdx};
7689 SDVTList VTs = DAG.getVTList(IntVT);
7690 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7691}
7692
7693SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7694 SelectionDAG &DAG) const {
7695 // When we pop the dynamic allocation we need to restore the SP link.
7696 SDLoc dl(Op);
7697
7698 // Get the correct type for pointers.
7699 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7700
7701 // Construct the stack pointer operand.
7702 bool isPPC64 = Subtarget.isPPC64();
7703 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7704 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7705
7706 // Get the operands for the STACKRESTORE.
7707 SDValue Chain = Op.getOperand(0);
7708 SDValue SaveSP = Op.getOperand(1);
7709
7710 // Load the old link SP.
7711 SDValue LoadLinkSP =
7712 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7713
7714 // Restore the stack pointer.
7715 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7716
7717 // Store the old link SP.
7718 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7719}
7720
7721SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7722 MachineFunction &MF = DAG.getMachineFunction();
7723 bool isPPC64 = Subtarget.isPPC64();
7724 EVT PtrVT = getPointerTy(MF.getDataLayout());
7725
7726 // Get current frame pointer save index. The users of this index will be
7727 // primarily DYNALLOC instructions.
7728 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7729 int RASI = FI->getReturnAddrSaveIndex();
7730
7731 // If the frame pointer save index hasn't been defined yet.
7732 if (!RASI) {
7733 // Find out what the fix offset of the frame pointer save area.
7734 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7735 // Allocate the frame index for frame pointer save area.
7736 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7737 // Save the result.
7738 FI->setReturnAddrSaveIndex(RASI);
7739 }
7740 return DAG.getFrameIndex(RASI, PtrVT);
7741}
7742
7743SDValue
7744PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7745 MachineFunction &MF = DAG.getMachineFunction();
7746 bool isPPC64 = Subtarget.isPPC64();
7747 EVT PtrVT = getPointerTy(MF.getDataLayout());
7748
7749 // Get current frame pointer save index. The users of this index will be
7750 // primarily DYNALLOC instructions.
7751 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7752 int FPSI = FI->getFramePointerSaveIndex();
7753
7754 // If the frame pointer save index hasn't been defined yet.
7755 if (!FPSI) {
7756 // Find out what the fix offset of the frame pointer save area.
7757 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7758 // Allocate the frame index for frame pointer save area.
7759 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7760 // Save the result.
7761 FI->setFramePointerSaveIndex(FPSI);
7762 }
7763 return DAG.getFrameIndex(FPSI, PtrVT);
7764}
7765
7766SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7767 SelectionDAG &DAG) const {
7768 MachineFunction &MF = DAG.getMachineFunction();
7769 // Get the inputs.
7770 SDValue Chain = Op.getOperand(0);
7771 SDValue Size = Op.getOperand(1);
7772 SDLoc dl(Op);
7773
7774 // Get the correct type for pointers.
7775 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7776 // Negate the size.
7777 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7778 DAG.getConstant(0, dl, PtrVT), Size);
7779 // Construct a node for the frame pointer save index.
7780 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7781 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7782 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7783 if (hasInlineStackProbe(MF))
7784 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7785 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7786}
7787
7788SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7789 SelectionDAG &DAG) const {
7790 MachineFunction &MF = DAG.getMachineFunction();
7791
7792 bool isPPC64 = Subtarget.isPPC64();
7793 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7794
7795 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7796 return DAG.getFrameIndex(FI, PtrVT);
7797}
7798
7799SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7800 SelectionDAG &DAG) const {
7801 SDLoc DL(Op);
7802 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7803 DAG.getVTList(MVT::i32, MVT::Other),
7804 Op.getOperand(0), Op.getOperand(1));
7805}
7806
7807SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7808 SelectionDAG &DAG) const {
7809 SDLoc DL(Op);
7810 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7811 Op.getOperand(0), Op.getOperand(1));
7812}
7813
7814SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7815 if (Op.getValueType().isVector())
7816 return LowerVectorLoad(Op, DAG);
7817
7818 assert(Op.getValueType() == MVT::i1 &&(static_cast <bool> (Op.getValueType() == MVT::i1 &&
"Custom lowering only for i1 loads") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i1 && \"Custom lowering only for i1 loads\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7819, __extension__
__PRETTY_FUNCTION__))
7819 "Custom lowering only for i1 loads")(static_cast <bool> (Op.getValueType() == MVT::i1 &&
"Custom lowering only for i1 loads") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i1 && \"Custom lowering only for i1 loads\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7819, __extension__
__PRETTY_FUNCTION__))
;
7820
7821 // First, load 8 bits into 32 bits, then truncate to 1 bit.
7822
7823 SDLoc dl(Op);
7824 LoadSDNode *LD = cast<LoadSDNode>(Op);
7825
7826 SDValue Chain = LD->getChain();
7827 SDValue BasePtr = LD->getBasePtr();
7828 MachineMemOperand *MMO = LD->getMemOperand();
7829
7830 SDValue NewLD =
7831 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7832 BasePtr, MVT::i8, MMO);
7833 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7834
7835 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7836 return DAG.getMergeValues(Ops, dl);
7837}
7838
7839SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7840 if (Op.getOperand(1).getValueType().isVector())
7841 return LowerVectorStore(Op, DAG);
7842
7843 assert(Op.getOperand(1).getValueType() == MVT::i1 &&(static_cast <bool> (Op.getOperand(1).getValueType() ==
MVT::i1 && "Custom lowering only for i1 stores") ? void
(0) : __assert_fail ("Op.getOperand(1).getValueType() == MVT::i1 && \"Custom lowering only for i1 stores\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7844, __extension__
__PRETTY_FUNCTION__))
7844 "Custom lowering only for i1 stores")(static_cast <bool> (Op.getOperand(1).getValueType() ==
MVT::i1 && "Custom lowering only for i1 stores") ? void
(0) : __assert_fail ("Op.getOperand(1).getValueType() == MVT::i1 && \"Custom lowering only for i1 stores\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7844, __extension__
__PRETTY_FUNCTION__))
;
7845
7846 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7847
7848 SDLoc dl(Op);
7849 StoreSDNode *ST = cast<StoreSDNode>(Op);
7850
7851 SDValue Chain = ST->getChain();
7852 SDValue BasePtr = ST->getBasePtr();
7853 SDValue Value = ST->getValue();
7854 MachineMemOperand *MMO = ST->getMemOperand();
7855
7856 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7857 Value);
7858 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7859}
7860
7861// FIXME: Remove this once the ANDI glue bug is fixed:
7862SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7863 assert(Op.getValueType() == MVT::i1 &&(static_cast <bool> (Op.getValueType() == MVT::i1 &&
"Custom lowering only for i1 results") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i1 && \"Custom lowering only for i1 results\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7864, __extension__
__PRETTY_FUNCTION__))
7864 "Custom lowering only for i1 results")(static_cast <bool> (Op.getValueType() == MVT::i1 &&
"Custom lowering only for i1 results") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i1 && \"Custom lowering only for i1 results\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7864, __extension__
__PRETTY_FUNCTION__))
;
7865
7866 SDLoc DL(Op);
7867 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7868}
7869
7870SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7871 SelectionDAG &DAG) const {
7872
7873 // Implements a vector truncate that fits in a vector register as a shuffle.
7874 // We want to legalize vector truncates down to where the source fits in
7875 // a vector register (and target is therefore smaller than vector register
7876 // size). At that point legalization will try to custom lower the sub-legal
7877 // result and get here - where we can contain the truncate as a single target
7878 // operation.
7879
7880 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7881 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7882 //
7883 // We will implement it for big-endian ordering as this (where x denotes
7884 // undefined):
7885 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7886 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7887 //
7888 // The same operation in little-endian ordering will be:
7889 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7890 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7891
7892 EVT TrgVT = Op.getValueType();
7893 assert(TrgVT.isVector() && "Vector type expected.")(static_cast <bool> (TrgVT.isVector() && "Vector type expected."
) ? void (0) : __assert_fail ("TrgVT.isVector() && \"Vector type expected.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 7893, __extension__
__PRETTY_FUNCTION__))
;
7894 unsigned TrgNumElts = TrgVT.getVectorNumElements();
7895 EVT EltVT = TrgVT.getVectorElementType();
7896 if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7897 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7898 !llvm::has_single_bit<uint32_t>(EltVT.getSizeInBits()))
7899 return SDValue();
7900
7901 SDValue N1 = Op.getOperand(0);
7902 EVT SrcVT = N1.getValueType();
7903 unsigned SrcSize = SrcVT.getSizeInBits();
7904 if (SrcSize > 256 || !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7905 !llvm::has_single_bit<uint32_t>(
7906 SrcVT.getVectorElementType().getSizeInBits()))
7907 return SDValue();
7908 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7909 return SDValue();
7910
7911 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7912 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7913
7914 SDLoc DL(Op);
7915 SDValue Op1, Op2;
7916 if (SrcSize == 256) {
7917 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7918 EVT SplitVT =
7919 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7920 unsigned SplitNumElts = SplitVT.getVectorNumElements();
7921 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7922 DAG.getConstant(0, DL, VecIdxTy));
7923 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7924 DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7925 }
7926 else {
7927 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7928 Op2 = DAG.getUNDEF(WideVT);
7929 }
7930
7931 // First list the elements we want to keep.
7932 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7933 SmallVector<int, 16> ShuffV;
7934 if (Subtarget.isLittleEndian())
7935 for (unsigned i = 0; i < TrgNumElts; ++i)
7936 ShuffV.push_back(i * SizeMult);
7937 else
7938 for (unsigned i = 1; i <= TrgNumElts; ++i)
7939 ShuffV.push_back(i * SizeMult - 1);
7940
7941 // Populate the remaining elements with undefs.
7942 for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7943 // ShuffV.push_back(i + WideNumElts);
7944 ShuffV.push_back(WideNumElts + 1);
7945
7946 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7947 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7948 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7949}
7950
7951/// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7952/// possible.
7953SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7954 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7955 EVT ResVT = Op.getValueType();
7956 EVT CmpVT = Op.getOperand(0).getValueType();
7957 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7958 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
7959 SDLoc dl(Op);
7960
7961 // Without power9-vector, we don't have native instruction for f128 comparison.
7962 // Following transformation to libcall is needed for setcc:
7963 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7964 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7965 SDValue Z = DAG.getSetCC(
7966 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7967 LHS, RHS, CC);
7968 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7969 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7970 }
7971
7972 // Not FP, or using SPE? Not a fsel.
7973 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7974 Subtarget.hasSPE())
7975 return Op;
7976
7977 SDNodeFlags Flags = Op.getNode()->getFlags();
7978
7979 // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
7980 // presence of infinities.
7981 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7982 switch (CC) {
7983 default:
7984 break;
7985 case ISD::SETOGT:
7986 case ISD::SETGT:
7987 return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
7988 case ISD::SETOLT:
7989 case ISD::SETLT:
7990 return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
7991 }
7992 }
7993
7994 // We might be able to do better than this under some circumstances, but in
7995 // general, fsel-based lowering of select is a finite-math-only optimization.
7996 // For more information, see section F.3 of the 2.06 ISA specification.
7997 // With ISA 3.0
7998 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7999 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
8000 return Op;
8001
8002 // If the RHS of the comparison is a 0.0, we don't need to do the
8003 // subtraction at all.
8004 SDValue Sel1;
8005 if (isFloatingPointZero(RHS))
8006 switch (CC) {
8007 default: break; // SETUO etc aren't handled by fsel.
8008 case ISD::SETNE:
8009 std::swap(TV, FV);
8010 [[fallthrough]];
8011 case ISD::SETEQ:
8012 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8013 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8014 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8015 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
8016 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8017 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8018 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8019 case ISD::SETULT:
8020 case ISD::SETLT:
8021 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
8022 [[fallthrough]];
8023 case ISD::SETOGE:
8024 case ISD::SETGE:
8025 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8026 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8027 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8028 case ISD::SETUGT:
8029 case ISD::SETGT:
8030 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
8031 [[fallthrough]];
8032 case ISD::SETOLE:
8033 case ISD::SETLE:
8034 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8035 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8036 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8037 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8038 }
8039
8040 SDValue Cmp;
8041 switch (CC) {
8042 default: break; // SETUO etc aren't handled by fsel.
8043 case ISD::SETNE:
8044 std::swap(TV, FV);
8045 [[fallthrough]];
8046 case ISD::SETEQ:
8047 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8048 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8049 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8050 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8051 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
8052 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8053 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8054 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8055 case ISD::SETULT:
8056 case ISD::SETLT:
8057 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8058 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8059 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8060 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8061 case ISD::SETOGE:
8062 case ISD::SETGE:
8063 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8064 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8065 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8066 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8067 case ISD::SETUGT:
8068 case ISD::SETGT:
8069 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8070 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8071 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8072 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8073 case ISD::SETOLE:
8074 case ISD::SETLE:
8075 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8076 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8077 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8078 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8079 }
8080 return Op;
8081}
8082
8083static unsigned getPPCStrictOpcode(unsigned Opc) {
8084 switch (Opc) {
8085 default:
8086 llvm_unreachable("No strict version of this opcode!")::llvm::llvm_unreachable_internal("No strict version of this opcode!"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8086)
;
8087 case PPCISD::FCTIDZ:
8088 return PPCISD::STRICT_FCTIDZ;
8089 case PPCISD::FCTIWZ:
8090 return PPCISD::STRICT_FCTIWZ;
8091 case PPCISD::FCTIDUZ:
8092 return PPCISD::STRICT_FCTIDUZ;
8093 case PPCISD::FCTIWUZ:
8094 return PPCISD::STRICT_FCTIWUZ;
8095 case PPCISD::FCFID:
8096 return PPCISD::STRICT_FCFID;
8097 case PPCISD::FCFIDU:
8098 return PPCISD::STRICT_FCFIDU;
8099 case PPCISD::FCFIDS:
8100 return PPCISD::STRICT_FCFIDS;
8101 case PPCISD::FCFIDUS:
8102 return PPCISD::STRICT_FCFIDUS;
8103 }
8104}
8105
8106static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8107 const PPCSubtarget &Subtarget) {
8108 SDLoc dl(Op);
8109 bool IsStrict = Op->isStrictFPOpcode();
8110 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8111 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8112
8113 // TODO: Any other flags to propagate?
8114 SDNodeFlags Flags;
8115 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8116
8117 // For strict nodes, source is the second operand.
8118 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8119 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8120 assert(Src.getValueType().isFloatingPoint())(static_cast <bool> (Src.getValueType().isFloatingPoint
()) ? void (0) : __assert_fail ("Src.getValueType().isFloatingPoint()"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8120, __extension__
__PRETTY_FUNCTION__))
;
8121 if (Src.getValueType() == MVT::f32) {
8122 if (IsStrict) {
8123 Src =
8124 DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8125 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8126 Chain = Src.getValue(1);
8127 } else
8128 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8129 }
8130 SDValue Conv;
8131 unsigned Opc = ISD::DELETED_NODE;
8132 switch (Op.getSimpleValueType().SimpleTy) {
8133 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!")::llvm::llvm_unreachable_internal("Unhandled FP_TO_INT type in custom expander!"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8133)
;
8134 case MVT::i32:
8135 Opc = IsSigned ? PPCISD::FCTIWZ
8136 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8137 break;
8138 case MVT::i64:
8139 assert((IsSigned || Subtarget.hasFPCVT()) &&(static_cast <bool> ((IsSigned || Subtarget.hasFPCVT())
&& "i64 FP_TO_UINT is supported only with FPCVT") ? void
(0) : __assert_fail ("(IsSigned || Subtarget.hasFPCVT()) && \"i64 FP_TO_UINT is supported only with FPCVT\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8140, __extension__
__PRETTY_FUNCTION__))
8140 "i64 FP_TO_UINT is supported only with FPCVT")(static_cast <bool> ((IsSigned || Subtarget.hasFPCVT())
&& "i64 FP_TO_UINT is supported only with FPCVT") ? void
(0) : __assert_fail ("(IsSigned || Subtarget.hasFPCVT()) && \"i64 FP_TO_UINT is supported only with FPCVT\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8140, __extension__
__PRETTY_FUNCTION__))
;
8141 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8142 }
8143 if (IsStrict) {
8144 Opc = getPPCStrictOpcode(Opc);
8145 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8146 {Chain, Src}, Flags);
8147 } else {
8148 Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8149 }
8150 return Conv;
8151}
8152
8153void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8154 SelectionDAG &DAG,
8155 const SDLoc &dl) const {
8156 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8157 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8158 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8159 bool IsStrict = Op->isStrictFPOpcode();
8160
8161 // Convert the FP value to an int value through memory.
8162 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8163 (IsSigned || Subtarget.hasFPCVT());
8164 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8165 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8166 MachinePointerInfo MPI =
8167 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8168
8169 // Emit a store to the stack slot.
8170 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8171 Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8172 if (i32Stack) {
8173 MachineFunction &MF = DAG.getMachineFunction();
8174 Alignment = Align(4);
8175 MachineMemOperand *MMO =
8176 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8177 SDValue Ops[] = { Chain, Tmp, FIPtr };
8178 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8179 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8180 } else
8181 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8182
8183 // Result is a load from the stack slot. If loading 4 bytes, make sure to
8184 // add in a bias on big endian.
8185 if (Op.getValueType() == MVT::i32 && !i32Stack) {
8186 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8187 DAG.getConstant(4, dl, FIPtr.getValueType()));
8188 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8189 }
8190
8191 RLI.Chain = Chain;
8192 RLI.Ptr = FIPtr;
8193 RLI.MPI = MPI;
8194 RLI.Alignment = Alignment;
8195}
8196
8197/// Custom lowers floating point to integer conversions to use
8198/// the direct move instructions available in ISA 2.07 to avoid the
8199/// need for load/store combinations.
8200SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8201 SelectionDAG &DAG,
8202 const SDLoc &dl) const {
8203 SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8204 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8205 if (Op->isStrictFPOpcode())
8206 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8207 else
8208 return Mov;
8209}
8210
8211SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8212 const SDLoc &dl) const {
8213 bool IsStrict = Op->isStrictFPOpcode();
8214 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8215 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8216 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8217 EVT SrcVT = Src.getValueType();
8218 EVT DstVT = Op.getValueType();
8219
8220 // FP to INT conversions are legal for f128.
8221 if (SrcVT == MVT::f128)
8222 return Subtarget.hasP9Vector() ? Op : SDValue();
8223
8224 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8225 // PPC (the libcall is not available).
8226 if (SrcVT == MVT::ppcf128) {
8227 if (DstVT == MVT::i32) {
8228 // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8229 // set other fast-math flags to FP operations in both strict and
8230 // non-strict cases. (FP_TO_SINT, FSUB)
8231 SDNodeFlags Flags;
8232 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8233
8234 if (IsSigned) {
8235 SDValue Lo, Hi;
8236 std::tie(Lo, Hi) = DAG.SplitScalar(Src, dl, MVT::f64, MVT::f64);
8237
8238 // Add the two halves of the long double in round-to-zero mode, and use
8239 // a smaller FP_TO_SINT.
8240 if (IsStrict) {
8241 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8242 DAG.getVTList(MVT::f64, MVT::Other),
8243 {Op.getOperand(0), Lo, Hi}, Flags);
8244 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8245 DAG.getVTList(MVT::i32, MVT::Other),
8246 {Res.getValue(1), Res}, Flags);
8247 } else {
8248 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8249 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8250 }
8251 } else {
8252 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8253 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8254 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8255 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8256 if (IsStrict) {
8257 // Sel = Src < 0x80000000
8258 // FltOfs = select Sel, 0.0, 0x80000000
8259 // IntOfs = select Sel, 0, 0x80000000
8260 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8261 SDValue Chain = Op.getOperand(0);
8262 EVT SetCCVT =
8263 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8264 EVT DstSetCCVT =
8265 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8266 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8267 Chain, true);
8268 Chain = Sel.getValue(1);
8269
8270 SDValue FltOfs = DAG.getSelect(
8271 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8272 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8273
8274 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8275 DAG.getVTList(SrcVT, MVT::Other),
8276 {Chain, Src, FltOfs}, Flags);
8277 Chain = Val.getValue(1);
8278 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8279 DAG.getVTList(DstVT, MVT::Other),
8280 {Chain, Val}, Flags);
8281 Chain = SInt.getValue(1);
8282 SDValue IntOfs = DAG.getSelect(
8283 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8284 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8285 return DAG.getMergeValues({Result, Chain}, dl);
8286 } else {
8287 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8288 // FIXME: generated code sucks.
8289 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8290 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8291 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8292 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8293 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8294 }
8295 }
8296 }
8297
8298 return SDValue();
8299 }
8300
8301 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8302 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8303
8304 ReuseLoadInfo RLI;
8305 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8306
8307 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8308 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8309}
8310
8311// We're trying to insert a regular store, S, and then a load, L. If the
8312// incoming value, O, is a load, we might just be able to have our load use the
8313// address used by O. However, we don't know if anything else will store to
8314// that address before we can load from it. To prevent this situation, we need
8315// to insert our load, L, into the chain as a peer of O. To do this, we give L
8316// the same chain operand as O, we create a token factor from the chain results
8317// of O and L, and we replace all uses of O's chain result with that token
8318// factor (see spliceIntoChain below for this last part).
8319bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8320 ReuseLoadInfo &RLI,
8321 SelectionDAG &DAG,
8322 ISD::LoadExtType ET) const {
8323 // Conservatively skip reusing for constrained FP nodes.
8324 if (Op->isStrictFPOpcode())
8325 return false;
8326
8327 SDLoc dl(Op);
8328 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8329 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8330 if (ET == ISD::NON_EXTLOAD &&
8331 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8332 isOperationLegalOrCustom(Op.getOpcode(),
8333 Op.getOperand(0).getValueType())) {
8334
8335 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8336 return true;
8337 }
8338
8339 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8340 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8341 LD->isNonTemporal())
8342 return false;
8343 if (LD->getMemoryVT() != MemVT)
8344 return false;
8345
8346 // If the result of the load is an illegal type, then we can't build a
8347 // valid chain for reuse since the legalised loads and token factor node that
8348 // ties the legalised loads together uses a different output chain then the
8349 // illegal load.
8350 if (!isTypeLegal(LD->getValueType(0)))
8351 return false;
8352
8353 RLI.Ptr = LD->getBasePtr();
8354 if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8355 assert(LD->getAddressingMode() == ISD::PRE_INC &&(static_cast <bool> (LD->getAddressingMode() == ISD::
PRE_INC && "Non-pre-inc AM on PPC?") ? void (0) : __assert_fail
("LD->getAddressingMode() == ISD::PRE_INC && \"Non-pre-inc AM on PPC?\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8356, __extension__
__PRETTY_FUNCTION__))
8356 "Non-pre-inc AM on PPC?")(static_cast <bool> (LD->getAddressingMode() == ISD::
PRE_INC && "Non-pre-inc AM on PPC?") ? void (0) : __assert_fail
("LD->getAddressingMode() == ISD::PRE_INC && \"Non-pre-inc AM on PPC?\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8356, __extension__
__PRETTY_FUNCTION__))
;
8357 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8358 LD->getOffset());
8359 }
8360
8361 RLI.Chain = LD->getChain();
8362 RLI.MPI = LD->getPointerInfo();
8363 RLI.IsDereferenceable = LD->isDereferenceable();
8364 RLI.IsInvariant = LD->isInvariant();
8365 RLI.Alignment = LD->getAlign();
8366 RLI.AAInfo = LD->getAAInfo();
8367 RLI.Ranges = LD->getRanges();
8368
8369 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8370 return true;
8371}
8372
8373// Given the head of the old chain, ResChain, insert a token factor containing
8374// it and NewResChain, and make users of ResChain now be users of that token
8375// factor.
8376// TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8377void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8378 SDValue NewResChain,
8379 SelectionDAG &DAG) const {
8380 if (!ResChain)
8381 return;
8382
8383 SDLoc dl(NewResChain);
8384
8385 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8386 NewResChain, DAG.getUNDEF(MVT::Other));
8387 assert(TF.getNode() != NewResChain.getNode() &&(static_cast <bool> (TF.getNode() != NewResChain.getNode
() && "A new TF really is required here") ? void (0) :
__assert_fail ("TF.getNode() != NewResChain.getNode() && \"A new TF really is required here\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8388, __extension__
__PRETTY_FUNCTION__))
8388 "A new TF really is required here")(static_cast <bool> (TF.getNode() != NewResChain.getNode
() && "A new TF really is required here") ? void (0) :
__assert_fail ("TF.getNode() != NewResChain.getNode() && \"A new TF really is required here\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8388, __extension__
__PRETTY_FUNCTION__))
;
8389
8390 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8391 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8392}
8393
8394/// Analyze profitability of direct move
8395/// prefer float load to int load plus direct move
8396/// when there is no integer use of int load
8397bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8398 SDNode *Origin = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0).getNode();
8399 if (Origin->getOpcode() != ISD::LOAD)
8400 return true;
8401
8402 // If there is no LXSIBZX/LXSIHZX, like Power8,
8403 // prefer direct move if the memory size is 1 or 2 bytes.
8404 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8405 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8406 return true;
8407
8408 for (SDNode::use_iterator UI = Origin->use_begin(),
8409 UE = Origin->use_end();
8410 UI != UE; ++UI) {
8411
8412 // Only look at the users of the loaded value.
8413 if (UI.getUse().get().getResNo() != 0)
8414 continue;
8415
8416 if (UI->getOpcode() != ISD::SINT_TO_FP &&
8417 UI->getOpcode() != ISD::UINT_TO_FP &&
8418 UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8419 UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8420 return true;
8421 }
8422
8423 return false;
8424}
8425
8426static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8427 const PPCSubtarget &Subtarget,
8428 SDValue Chain = SDValue()) {
8429 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8430 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8431 SDLoc dl(Op);
8432
8433 // TODO: Any other flags to propagate?
8434 SDNodeFlags Flags;
8435 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8436
8437 // If we have FCFIDS, then use it when converting to single-precision.
8438 // Otherwise, convert to double-precision and then round.
8439 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8440 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8441 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8442 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8443 if (Op->isStrictFPOpcode()) {
8444 if (!Chain)
8445 Chain = Op.getOperand(0);
8446 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8447 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8448 } else
8449 return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8450}
8451
8452/// Custom lowers integer to floating point conversions to use
8453/// the direct move instructions available in ISA 2.07 to avoid the
8454/// need for load/store combinations.
8455SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8456 SelectionDAG &DAG,
8457 const SDLoc &dl) const {
8458 assert((Op.getValueType() == MVT::f32 ||(static_cast <bool> ((Op.getValueType() == MVT::f32 || Op
.getValueType() == MVT::f64) && "Invalid floating point type as target of conversion"
) ? void (0) : __assert_fail ("(Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) && \"Invalid floating point type as target of conversion\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8460, __extension__
__PRETTY_FUNCTION__))
8459 Op.getValueType() == MVT::f64) &&(static_cast <bool> ((Op.getValueType() == MVT::f32 || Op
.getValueType() == MVT::f64) && "Invalid floating point type as target of conversion"
) ? void (0) : __assert_fail ("(Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) && \"Invalid floating point type as target of conversion\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8460, __extension__
__PRETTY_FUNCTION__))
8460 "Invalid floating point type as target of conversion")(static_cast <bool> ((Op.getValueType() == MVT::f32 || Op
.getValueType() == MVT::f64) && "Invalid floating point type as target of conversion"
) ? void (0) : __assert_fail ("(Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) && \"Invalid floating point type as target of conversion\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8460, __extension__
__PRETTY_FUNCTION__))
;
8461 assert(Subtarget.hasFPCVT() &&(static_cast <bool> (Subtarget.hasFPCVT() && "Int to FP conversions with direct moves require FPCVT"
) ? void (0) : __assert_fail ("Subtarget.hasFPCVT() && \"Int to FP conversions with direct moves require FPCVT\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8462, __extension__
__PRETTY_FUNCTION__))
8462 "Int to FP conversions with direct moves require FPCVT")(static_cast <bool> (Subtarget.hasFPCVT() && "Int to FP conversions with direct moves require FPCVT"
) ? void (0) : __assert_fail ("Subtarget.hasFPCVT() && \"Int to FP conversions with direct moves require FPCVT\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8462, __extension__
__PRETTY_FUNCTION__))
;
8463 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8464 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8465 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8466 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8467 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8468 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8469 return convertIntToFP(Op, Mov, DAG, Subtarget);
8470}
8471
8472static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8473
8474 EVT VecVT = Vec.getValueType();
8475 assert(VecVT.isVector() && "Expected a vector type.")(static_cast <bool> (VecVT.isVector() && "Expected a vector type."
) ? void (0) : __assert_fail ("VecVT.isVector() && \"Expected a vector type.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8475, __extension__
__PRETTY_FUNCTION__))
;
8476 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.")(static_cast <bool> (VecVT.getSizeInBits() < 128 &&
"Vector is already full width.") ? void (0) : __assert_fail (
"VecVT.getSizeInBits() < 128 && \"Vector is already full width.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8476, __extension__
__PRETTY_FUNCTION__))
;
8477
8478 EVT EltVT = VecVT.getVectorElementType();
8479 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8480 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8481
8482 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8483 SmallVector<SDValue, 16> Ops(NumConcat);
8484 Ops[0] = Vec;
8485 SDValue UndefVec = DAG.getUNDEF(VecVT);
8486 for (unsigned i = 1; i < NumConcat; ++i)
8487 Ops[i] = UndefVec;
8488
8489 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8490}
8491
8492SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8493 const SDLoc &dl) const {
8494 bool IsStrict = Op->isStrictFPOpcode();
8495 unsigned Opc = Op.getOpcode();
8496 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8497 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||(static_cast <bool> ((Opc == ISD::UINT_TO_FP || Opc == ISD
::SINT_TO_FP || Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::
STRICT_SINT_TO_FP) && "Unexpected conversion type") ?
void (0) : __assert_fail ("(Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && \"Unexpected conversion type\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8499, __extension__
__PRETTY_FUNCTION__))
8498 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&(static_cast <bool> ((Opc == ISD::UINT_TO_FP || Opc == ISD
::SINT_TO_FP || Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::
STRICT_SINT_TO_FP) && "Unexpected conversion type") ?
void (0) : __assert_fail ("(Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && \"Unexpected conversion type\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8499, __extension__
__PRETTY_FUNCTION__))
8499 "Unexpected conversion type")(static_cast <bool> ((Opc == ISD::UINT_TO_FP || Opc == ISD
::SINT_TO_FP || Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::
STRICT_SINT_TO_FP) && "Unexpected conversion type") ?
void (0) : __assert_fail ("(Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && \"Unexpected conversion type\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8499, __extension__
__PRETTY_FUNCTION__))
;
8500 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&(static_cast <bool> ((Op.getValueType() == MVT::v2f64 ||
Op.getValueType() == MVT::v4f32) && "Supports conversions to v2f64/v4f32 only."
) ? void (0) : __assert_fail ("(Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && \"Supports conversions to v2f64/v4f32 only.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8501, __extension__
__PRETTY_FUNCTION__))
8501 "Supports conversions to v2f64/v4f32 only.")(static_cast <bool> ((Op.getValueType() == MVT::v2f64 ||
Op.getValueType() == MVT::v4f32) && "Supports conversions to v2f64/v4f32 only."
) ? void (0) : __assert_fail ("(Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && \"Supports conversions to v2f64/v4f32 only.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8501, __extension__
__PRETTY_FUNCTION__))
;
8502
8503 // TODO: Any other flags to propagate?
8504 SDNodeFlags Flags;
8505 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8506
8507 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8508 bool FourEltRes = Op.getValueType() == MVT::v4f32;
8509
8510 SDValue Wide = widenVec(DAG, Src, dl);
8511 EVT WideVT = Wide.getValueType();
8512 unsigned WideNumElts = WideVT.getVectorNumElements();
8513 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8514
8515 SmallVector<int, 16> ShuffV;
8516 for (unsigned i = 0; i < WideNumElts; ++i)
8517 ShuffV.push_back(i + WideNumElts);
8518
8519 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8520 int SaveElts = FourEltRes ? 4 : 2;
8521 if (Subtarget.isLittleEndian())
8522 for (int i = 0; i < SaveElts; i++)
8523 ShuffV[i * Stride] = i;
8524 else
8525 for (int i = 1; i <= SaveElts; i++)
8526 ShuffV[i * Stride - 1] = i - 1;
8527
8528 SDValue ShuffleSrc2 =
8529 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8530 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8531
8532 SDValue Extend;
8533 if (SignedConv) {
8534 Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8535 EVT ExtVT = Src.getValueType();
8536 if (Subtarget.hasP9Altivec())
8537 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8538 IntermediateVT.getVectorNumElements());
8539
8540 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8541 DAG.getValueType(ExtVT));
8542 } else
8543 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8544
8545 if (IsStrict)
8546 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8547 {Op.getOperand(0), Extend}, Flags);
8548
8549 return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8550}
8551
8552SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8553 SelectionDAG &DAG) const {
8554 SDLoc dl(Op);
8555 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8556 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8557 bool IsStrict = Op->isStrictFPOpcode();
8558 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8559 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8560
8561 // TODO: Any other flags to propagate?
8562 SDNodeFlags Flags;
8563 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8564
8565 EVT InVT = Src.getValueType();
8566 EVT OutVT = Op.getValueType();
8567 if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8568 isOperationCustom(Op.getOpcode(), InVT))
8569 return LowerINT_TO_FPVector(Op, DAG, dl);
8570
8571 // Conversions to f128 are legal.
8572 if (Op.getValueType() == MVT::f128)
8573 return Subtarget.hasP9Vector() ? Op : SDValue();
8574
8575 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8576 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8577 return SDValue();
8578
8579 if (Src.getValueType() == MVT::i1) {
8580 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8581 DAG.getConstantFP(1.0, dl, Op.getValueType()),
8582 DAG.getConstantFP(0.0, dl, Op.getValueType()));
8583 if (IsStrict)
8584 return DAG.getMergeValues({Sel, Chain}, dl);
8585 else
8586 return Sel;
8587 }
8588
8589 // If we have direct moves, we can do all the conversion, skip the store/load
8590 // however, without FPCVT we can't do most conversions.
8591 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8592 Subtarget.isPPC64() && Subtarget.hasFPCVT())
8593 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8594
8595 assert((IsSigned || Subtarget.hasFPCVT()) &&(static_cast <bool> ((IsSigned || Subtarget.hasFPCVT())
&& "UINT_TO_FP is supported only with FPCVT") ? void
(0) : __assert_fail ("(IsSigned || Subtarget.hasFPCVT()) && \"UINT_TO_FP is supported only with FPCVT\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8596, __extension__
__PRETTY_FUNCTION__))
8596 "UINT_TO_FP is supported only with FPCVT")(static_cast <bool> ((IsSigned || Subtarget.hasFPCVT())
&& "UINT_TO_FP is supported only with FPCVT") ? void
(0) : __assert_fail ("(IsSigned || Subtarget.hasFPCVT()) && \"UINT_TO_FP is supported only with FPCVT\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8596, __extension__
__PRETTY_FUNCTION__))
;
8597
8598 if (Src.getValueType() == MVT::i64) {
8599 SDValue SINT = Src;
8600 // When converting to single-precision, we actually need to convert
8601 // to double-precision first and then round to single-precision.
8602 // To avoid double-rounding effects during that operation, we have
8603 // to prepare the input operand. Bits that might be truncated when
8604 // converting to double-precision are replaced by a bit that won't
8605 // be lost at this stage, but is below the single-precision rounding
8606 // position.
8607 //
8608 // However, if -enable-unsafe-fp-math is in effect, accept double
8609 // rounding to avoid the extra overhead.
8610 if (Op.getValueType() == MVT::f32 &&
8611 !Subtarget.hasFPCVT() &&
8612 !DAG.getTarget().Options.UnsafeFPMath) {
8613
8614 // Twiddle input to make sure the low 11 bits are zero. (If this
8615 // is the case, we are guaranteed the value will fit into the 53 bit
8616 // mantissa of an IEEE double-precision value without rounding.)
8617 // If any of those low 11 bits were not zero originally, make sure
8618 // bit 12 (value 2048) is set instead, so that the final rounding
8619 // to single-precision gets the correct result.
8620 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8621 SINT, DAG.getConstant(2047, dl, MVT::i64));
8622 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8623 Round, DAG.getConstant(2047, dl, MVT::i64));
8624 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8625 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8626 Round, DAG.getConstant(-2048, dl, MVT::i64));
8627
8628 // However, we cannot use that value unconditionally: if the magnitude
8629 // of the input value is small, the bit-twiddling we did above might
8630 // end up visibly changing the output. Fortunately, in that case, we
8631 // don't need to twiddle bits since the original input will convert
8632 // exactly to double-precision floating-point already. Therefore,
8633 // construct a conditional to use the original value if the top 11
8634 // bits are all sign-bit copies, and use the rounded value computed
8635 // above otherwise.
8636 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8637 SINT, DAG.getConstant(53, dl, MVT::i32));
8638 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8639 Cond, DAG.getConstant(1, dl, MVT::i64));
8640 Cond = DAG.getSetCC(
8641 dl,
8642 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8643 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8644
8645 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8646 }
8647
8648 ReuseLoadInfo RLI;
8649 SDValue Bits;
8650
8651 MachineFunction &MF = DAG.getMachineFunction();
8652 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8653 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8654 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8655 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8656 } else if (Subtarget.hasLFIWAX() &&
8657 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8658 MachineMemOperand *MMO =
8659 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8660 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8661 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8662 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8663 DAG.getVTList(MVT::f64, MVT::Other),
8664 Ops, MVT::i32, MMO);
8665 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8666 } else if (Subtarget.hasFPCVT() &&
8667 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8668 MachineMemOperand *MMO =
8669 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8670 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8671 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8672 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8673 DAG.getVTList(MVT::f64, MVT::Other),
8674 Ops, MVT::i32, MMO);
8675 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8676 } else if (((Subtarget.hasLFIWAX() &&
8677 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8678 (Subtarget.hasFPCVT() &&
8679 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8680 SINT.getOperand(0).getValueType() == MVT::i32) {
8681 MachineFrameInfo &MFI = MF.getFrameInfo();
8682 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8683
8684 int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8685 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8686
8687 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8688 MachinePointerInfo::getFixedStack(
8689 DAG.getMachineFunction(), FrameIdx));
8690 Chain = Store;
8691
8692 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&(static_cast <bool> (cast<StoreSDNode>(Store)->
getMemoryVT() == MVT::i32 && "Expected an i32 store")
? void (0) : __assert_fail ("cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && \"Expected an i32 store\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8693, __extension__
__PRETTY_FUNCTION__))
8693 "Expected an i32 store")(static_cast <bool> (cast<StoreSDNode>(Store)->
getMemoryVT() == MVT::i32 && "Expected an i32 store")
? void (0) : __assert_fail ("cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && \"Expected an i32 store\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8693, __extension__
__PRETTY_FUNCTION__))
;
8694
8695 RLI.Ptr = FIdx;
8696 RLI.Chain = Chain;
8697 RLI.MPI =
8698 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8699 RLI.Alignment = Align(4);
8700
8701 MachineMemOperand *MMO =
8702 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8703 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8704 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8705 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8706 PPCISD::LFIWZX : PPCISD::LFIWAX,
8707 dl, DAG.getVTList(MVT::f64, MVT::Other),
8708 Ops, MVT::i32, MMO);
8709 Chain = Bits.getValue(1);
8710 } else
8711 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8712
8713 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8714 if (IsStrict)
8715 Chain = FP.getValue(1);
8716
8717 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8718 if (IsStrict)
8719 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8720 DAG.getVTList(MVT::f32, MVT::Other),
8721 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8722 else
8723 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8724 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
8725 }
8726 return FP;
8727 }
8728
8729 assert(Src.getValueType() == MVT::i32 &&(static_cast <bool> (Src.getValueType() == MVT::i32 &&
"Unhandled INT_TO_FP type in custom expander!") ? void (0) :
__assert_fail ("Src.getValueType() == MVT::i32 && \"Unhandled INT_TO_FP type in custom expander!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8730, __extension__
__PRETTY_FUNCTION__))
8730 "Unhandled INT_TO_FP type in custom expander!")(static_cast <bool> (Src.getValueType() == MVT::i32 &&
"Unhandled INT_TO_FP type in custom expander!") ? void (0) :
__assert_fail ("Src.getValueType() == MVT::i32 && \"Unhandled INT_TO_FP type in custom expander!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8730, __extension__
__PRETTY_FUNCTION__))
;
8731 // Since we only generate this in 64-bit mode, we can take advantage of
8732 // 64-bit registers. In particular, sign extend the input value into the
8733 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8734 // then lfd it and fcfid it.
8735 MachineFunction &MF = DAG.getMachineFunction();
8736 MachineFrameInfo &MFI = MF.getFrameInfo();
8737 EVT PtrVT = getPointerTy(MF.getDataLayout());
8738
8739 SDValue Ld;
8740 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8741 ReuseLoadInfo RLI;
8742 bool ReusingLoad;
8743 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8744 int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8745 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8746
8747 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8748 MachinePointerInfo::getFixedStack(
8749 DAG.getMachineFunction(), FrameIdx));
8750 Chain = Store;
8751
8752 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&(static_cast <bool> (cast<StoreSDNode>(Store)->
getMemoryVT() == MVT::i32 && "Expected an i32 store")
? void (0) : __assert_fail ("cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && \"Expected an i32 store\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8753, __extension__
__PRETTY_FUNCTION__))
8753 "Expected an i32 store")(static_cast <bool> (cast<StoreSDNode>(Store)->
getMemoryVT() == MVT::i32 && "Expected an i32 store")
? void (0) : __assert_fail ("cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && \"Expected an i32 store\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8753, __extension__
__PRETTY_FUNCTION__))
;
8754
8755 RLI.Ptr = FIdx;
8756 RLI.Chain = Chain;
8757 RLI.MPI =
8758 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8759 RLI.Alignment = Align(4);
8760 }
8761
8762 MachineMemOperand *MMO =
8763 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8764 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8765 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8766 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8767 DAG.getVTList(MVT::f64, MVT::Other), Ops,
8768 MVT::i32, MMO);
8769 Chain = Ld.getValue(1);
8770 if (ReusingLoad)
8771 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8772 } else {
8773 assert(Subtarget.isPPC64() &&(static_cast <bool> (Subtarget.isPPC64() && "i32->FP without LFIWAX supported only on PPC64"
) ? void (0) : __assert_fail ("Subtarget.isPPC64() && \"i32->FP without LFIWAX supported only on PPC64\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8774, __extension__
__PRETTY_FUNCTION__))
8774 "i32->FP without LFIWAX supported only on PPC64")(static_cast <bool> (Subtarget.isPPC64() && "i32->FP without LFIWAX supported only on PPC64"
) ? void (0) : __assert_fail ("Subtarget.isPPC64() && \"i32->FP without LFIWAX supported only on PPC64\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8774, __extension__
__PRETTY_FUNCTION__))
;
8775
8776 int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8777 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8778
8779 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8780
8781 // STD the extended value into the stack slot.
8782 SDValue Store = DAG.getStore(
8783 Chain, dl, Ext64, FIdx,
8784 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8785 Chain = Store;
8786
8787 // Load the value as a double.
8788 Ld = DAG.getLoad(
8789 MVT::f64, dl, Chain, FIdx,
8790 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8791 Chain = Ld.getValue(1);
8792 }
8793
8794 // FCFID it and return it.
8795 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8796 if (IsStrict)
8797 Chain = FP.getValue(1);
8798 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8799 if (IsStrict)
8800 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8801 DAG.getVTList(MVT::f32, MVT::Other),
8802 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8803 else
8804 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8805 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
8806 }
8807 return FP;
8808}
8809
8810SDValue PPCTargetLowering::LowerGET_ROUNDING(SDValue Op,
8811 SelectionDAG &DAG) const {
8812 SDLoc dl(Op);
8813 /*
8814 The rounding mode is in bits 30:31 of FPSR, and has the following
8815 settings:
8816 00 Round to nearest
8817 01 Round to 0
8818 10 Round to +inf
8819 11 Round to -inf
8820
8821 GET_ROUNDING, on the other hand, expects the following:
8822 -1 Undefined
8823 0 Round to 0
8824 1 Round to nearest
8825 2 Round to +inf
8826 3 Round to -inf
8827
8828 To perform the conversion, we do:
8829 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8830 */
8831
8832 MachineFunction &MF = DAG.getMachineFunction();
8833 EVT VT = Op.getValueType();
8834 EVT PtrVT = getPointerTy(MF.getDataLayout());
8835
8836 // Save FP Control Word to register
8837 SDValue Chain = Op.getOperand(0);
8838 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8839 Chain = MFFS.getValue(1);
8840
8841 SDValue CWD;
8842 if (isTypeLegal(MVT::i64)) {
8843 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8844 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8845 } else {
8846 // Save FP register to stack slot
8847 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8848 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8849 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8850
8851 // Load FP Control Word from low 32 bits of stack slot.
8852 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&(static_cast <bool> (hasBigEndianPartOrdering(MVT::i64,
MF.getDataLayout()) && "Stack slot adjustment is valid only on big endian subtargets!"
) ? void (0) : __assert_fail ("hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && \"Stack slot adjustment is valid only on big endian subtargets!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8853, __extension__
__PRETTY_FUNCTION__))
8853 "Stack slot adjustment is valid only on big endian subtargets!")(static_cast <bool> (hasBigEndianPartOrdering(MVT::i64,
MF.getDataLayout()) && "Stack slot adjustment is valid only on big endian subtargets!"
) ? void (0) : __assert_fail ("hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && \"Stack slot adjustment is valid only on big endian subtargets!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8853, __extension__
__PRETTY_FUNCTION__))
;
8854 SDValue Four = DAG.getConstant(4, dl, PtrVT);
8855 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8856 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8857 Chain = CWD.getValue(1);
8858 }
8859
8860 // Transform as necessary
8861 SDValue CWD1 =
8862 DAG.getNode(ISD::AND, dl, MVT::i32,
8863 CWD, DAG.getConstant(3, dl, MVT::i32));
8864 SDValue CWD2 =
8865 DAG.getNode(ISD::SRL, dl, MVT::i32,
8866 DAG.getNode(ISD::AND, dl, MVT::i32,
8867 DAG.getNode(ISD::XOR, dl, MVT::i32,
8868 CWD, DAG.getConstant(3, dl, MVT::i32)),
8869 DAG.getConstant(3, dl, MVT::i32)),
8870 DAG.getConstant(1, dl, MVT::i32));
8871
8872 SDValue RetVal =
8873 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8874
8875 RetVal =
8876 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8877 dl, VT, RetVal);
8878
8879 return DAG.getMergeValues({RetVal, Chain}, dl);
8880}
8881
8882SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8883 EVT VT = Op.getValueType();
8884 unsigned BitWidth = VT.getSizeInBits();
8885 SDLoc dl(Op);
8886 assert(Op.getNumOperands() == 3 &&(static_cast <bool> (Op.getNumOperands() == 3 &&
VT == Op.getOperand(1).getValueType() && "Unexpected SHL!"
) ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && \"Unexpected SHL!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8888, __extension__
__PRETTY_FUNCTION__))
8887 VT == Op.getOperand(1).getValueType() &&(static_cast <bool> (Op.getNumOperands() == 3 &&
VT == Op.getOperand(1).getValueType() && "Unexpected SHL!"
) ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && \"Unexpected SHL!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8888, __extension__
__PRETTY_FUNCTION__))
8888 "Unexpected SHL!")(static_cast <bool> (Op.getNumOperands() == 3 &&
VT == Op.getOperand(1).getValueType() && "Unexpected SHL!"
) ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && \"Unexpected SHL!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8888, __extension__
__PRETTY_FUNCTION__))
;
8889
8890 // Expand into a bunch of logical ops. Note that these ops
8891 // depend on the PPC behavior for oversized shift amounts.
8892 SDValue Lo = Op.getOperand(0);
8893 SDValue Hi = Op.getOperand(1);
8894 SDValue Amt = Op.getOperand(2);
8895 EVT AmtVT = Amt.getValueType();
8896
8897 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8898 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8899 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8900 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8901 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8902 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8903 DAG.getConstant(-BitWidth, dl, AmtVT));
8904 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8905 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8906 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8907 SDValue OutOps[] = { OutLo, OutHi };
8908 return DAG.getMergeValues(OutOps, dl);
8909}
8910
8911SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8912 EVT VT = Op.getValueType();
8913 SDLoc dl(Op);
8914 unsigned BitWidth = VT.getSizeInBits();
8915 assert(Op.getNumOperands() == 3 &&(static_cast <bool> (Op.getNumOperands() == 3 &&
VT == Op.getOperand(1).getValueType() && "Unexpected SRL!"
) ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && \"Unexpected SRL!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8917, __extension__
__PRETTY_FUNCTION__))
8916 VT == Op.getOperand(1).getValueType() &&(static_cast <bool> (Op.getNumOperands() == 3 &&
VT == Op.getOperand(1).getValueType() && "Unexpected SRL!"
) ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && \"Unexpected SRL!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8917, __extension__
__PRETTY_FUNCTION__))
8917 "Unexpected SRL!")(static_cast <bool> (Op.getNumOperands() == 3 &&
VT == Op.getOperand(1).getValueType() && "Unexpected SRL!"
) ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && \"Unexpected SRL!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8917, __extension__
__PRETTY_FUNCTION__))
;
8918
8919 // Expand into a bunch of logical ops. Note that these ops
8920 // depend on the PPC behavior for oversized shift amounts.
8921 SDValue Lo = Op.getOperand(0);
8922 SDValue Hi = Op.getOperand(1);
8923 SDValue Amt = Op.getOperand(2);
8924 EVT AmtVT = Amt.getValueType();
8925
8926 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8927 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8928 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8929 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8930 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8931 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8932 DAG.getConstant(-BitWidth, dl, AmtVT));
8933 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8934 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8935 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8936 SDValue OutOps[] = { OutLo, OutHi };
8937 return DAG.getMergeValues(OutOps, dl);
8938}
8939
8940SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8941 SDLoc dl(Op);
8942 EVT VT = Op.getValueType();
8943 unsigned BitWidth = VT.getSizeInBits();
8944 assert(Op.getNumOperands() == 3 &&(static_cast <bool> (Op.getNumOperands() == 3 &&
VT == Op.getOperand(1).getValueType() && "Unexpected SRA!"
) ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && \"Unexpected SRA!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8946, __extension__
__PRETTY_FUNCTION__))
8945 VT == Op.getOperand(1).getValueType() &&(static_cast <bool> (Op.getNumOperands() == 3 &&
VT == Op.getOperand(1).getValueType() && "Unexpected SRA!"
) ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && \"Unexpected SRA!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8946, __extension__
__PRETTY_FUNCTION__))
8946 "Unexpected SRA!")(static_cast <bool> (Op.getNumOperands() == 3 &&
VT == Op.getOperand(1).getValueType() && "Unexpected SRA!"
) ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && \"Unexpected SRA!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 8946, __extension__
__PRETTY_FUNCTION__))
;
8947
8948 // Expand into a bunch of logical ops, followed by a select_cc.
8949 SDValue Lo = Op.getOperand(0);
8950 SDValue Hi = Op.getOperand(1);
8951 SDValue Amt = Op.getOperand(2);
8952 EVT AmtVT = Amt.getValueType();
8953
8954 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8955 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8956 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8957 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8958 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8959 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8960 DAG.getConstant(-BitWidth, dl, AmtVT));
8961 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8962 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8963 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8964 Tmp4, Tmp6, ISD::SETLE);
8965 SDValue OutOps[] = { OutLo, OutHi };
8966 return DAG.getMergeValues(OutOps, dl);
8967}
8968
8969SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8970 SelectionDAG &DAG) const {
8971 SDLoc dl(Op);
8972 EVT VT = Op.getValueType();
8973 unsigned BitWidth = VT.getSizeInBits();
8974
8975 bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8976 SDValue X = Op.getOperand(0);
8977 SDValue Y = Op.getOperand(1);
8978 SDValue Z = Op.getOperand(2);
8979 EVT AmtVT = Z.getValueType();
8980
8981 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8982 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8983 // This is simpler than TargetLowering::expandFunnelShift because we can rely
8984 // on PowerPC shift by BW being well defined.
8985 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8986 DAG.getConstant(BitWidth - 1, dl, AmtVT));
8987 SDValue SubZ =
8988 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8989 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8990 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8991 return DAG.getNode(ISD::OR, dl, VT, X, Y);
8992}
8993
8994//===----------------------------------------------------------------------===//
8995// Vector related lowering.
8996//
8997
8998/// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8999/// element size of SplatSize. Cast the result to VT.
9000static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
9001 SelectionDAG &DAG, const SDLoc &dl) {
9002 static const MVT VTys[] = { // canonical VT to use for each size.
9003 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
9004 };
9005
9006 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
9007
9008 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
9009 if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
9010 SplatSize = 1;
9011 Val = 0xFF;
9012 }
9013
9014 EVT CanonicalVT = VTys[SplatSize-1];
9015
9016 // Build a canonical splat for this value.
9017 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
9018}
9019
9020/// BuildIntrinsicOp - Return a unary operator intrinsic node with the
9021/// specified intrinsic ID.
9022static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
9023 const SDLoc &dl, EVT DestVT = MVT::Other) {
9024 if (DestVT == MVT::Other) DestVT = Op.getValueType();
9025 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9026 DAG.getConstant(IID, dl, MVT::i32), Op);
9027}
9028
9029/// BuildIntrinsicOp - Return a binary operator intrinsic node with the
9030/// specified intrinsic ID.
9031static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
9032 SelectionDAG &DAG, const SDLoc &dl,
9033 EVT DestVT = MVT::Other) {
9034 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9035 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9036 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9037}
9038
9039/// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9040/// specified intrinsic ID.
9041static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9042 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9043 EVT DestVT = MVT::Other) {
9044 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9045 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9046 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9047}
9048
9049/// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9050/// amount. The result has the specified value type.
9051static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9052 SelectionDAG &DAG, const SDLoc &dl) {
9053 // Force LHS/RHS to be the right type.
9054 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9055 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9056
9057 int Ops[16];
9058 for (unsigned i = 0; i != 16; ++i)
9059 Ops[i] = i + Amt;
9060 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9061 return DAG.getNode(ISD::BITCAST, dl, VT, T);
9062}
9063
9064/// Do we have an efficient pattern in a .td file for this node?
9065///
9066/// \param V - pointer to the BuildVectorSDNode being matched
9067/// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9068///
9069/// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9070/// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9071/// the opposite is true (expansion is beneficial) are:
9072/// - The node builds a vector out of integers that are not 32 or 64-bits
9073/// - The node builds a vector out of constants
9074/// - The node is a "load-and-splat"
9075/// In all other cases, we will choose to keep the BUILD_VECTOR.
9076static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9077 bool HasDirectMove,
9078 bool HasP8Vector) {
9079 EVT VecVT = V->getValueType(0);
9080 bool RightType = VecVT == MVT::v2f64 ||
9081 (HasP8Vector && VecVT == MVT::v4f32) ||
9082 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9083 if (!RightType)
9084 return false;
9085
9086 bool IsSplat = true;
9087 bool IsLoad = false;
9088 SDValue Op0 = V->getOperand(0);
9089
9090 // This function is called in a block that confirms the node is not a constant
9091 // splat. So a constant BUILD_VECTOR here means the vector is built out of
9092 // different constants.
9093 if (V->isConstant())
9094 return false;
9095 for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9096 if (V->getOperand(i).isUndef())
9097 return false;
9098 // We want to expand nodes that represent load-and-splat even if the
9099 // loaded value is a floating point truncation or conversion to int.
9100 if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9101 (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9102 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9103 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9104 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9105 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9106 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9107 IsLoad = true;
9108 // If the operands are different or the input is not a load and has more
9109 // uses than just this BV node, then it isn't a splat.
9110 if (V->getOperand(i) != Op0 ||
9111 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9112 IsSplat = false;
9113 }
9114 return !(IsSplat && IsLoad);
9115}
9116
9117// Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9118SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9119
9120 SDLoc dl(Op);
9121 SDValue Op0 = Op->getOperand(0);
9122
9123 if ((Op.getValueType() != MVT::f128) ||
9124 (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9125 (Op0.getOperand(0).getValueType() != MVT::i64) ||
9126 (Op0.getOperand(1).getValueType() != MVT::i64))
9127 return SDValue();
9128
9129 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9130 Op0.getOperand(1));
9131}
9132
9133static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9134 const SDValue *InputLoad = &Op;
9135 while (InputLoad->getOpcode() == ISD::BITCAST)
9136 InputLoad = &InputLoad->getOperand(0);
9137 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
4
Taking false branch
9138 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9139 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9140 InputLoad = &InputLoad->getOperand(0);
9141 }
9142 if (InputLoad->getOpcode() != ISD::LOAD)
5
Taking true branch
9143 return nullptr;
6
Returning null pointer, which participates in a condition later
9144 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9145 return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9146}
9147
9148// Convert the argument APFloat to a single precision APFloat if there is no
9149// loss in information during the conversion to single precision APFloat and the
9150// resulting number is not a denormal number. Return true if successful.
9151bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9152 APFloat APFloatToConvert = ArgAPFloat;
9153 bool LosesInfo = true;
9154 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9155 &LosesInfo);
9156 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9157 if (Success)
9158 ArgAPFloat = APFloatToConvert;
9159 return Success;
9160}
9161
9162// Bitcast the argument APInt to a double and convert it to a single precision
9163// APFloat, bitcast the APFloat to an APInt and assign it to the original
9164// argument if there is no loss in information during the conversion from
9165// double to single precision APFloat and the resulting number is not a denormal
9166// number. Return true if successful.
9167bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9168 double DpValue = ArgAPInt.bitsToDouble();
9169 APFloat APFloatDp(DpValue);
9170 bool Success = convertToNonDenormSingle(APFloatDp);
9171 if (Success)
9172 ArgAPInt = APFloatDp.bitcastToAPInt();
9173 return Success;
9174}
9175
9176// Nondestructive check for convertTonNonDenormSingle.
9177bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9178 // Only convert if it loses info, since XXSPLTIDP should
9179 // handle the other case.
9180 APFloat APFloatToConvert = ArgAPFloat;
9181 bool LosesInfo = true;
9182 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9183 &LosesInfo);
9184
9185 return (!LosesInfo && !APFloatToConvert.isDenormal());
9186}
9187
9188static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9189 unsigned &Opcode) {
9190 LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9191 if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9192 return false;
9193
9194 EVT Ty = Op->getValueType(0);
9195 // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9196 // as we cannot handle extending loads for these types.
9197 if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9198 ISD::isNON_EXTLoad(InputNode))
9199 return true;
9200
9201 EVT MemVT = InputNode->getMemoryVT();
9202 // For v8i16 and v16i8 types, extending loads can be handled as long as the
9203 // memory VT is the same vector element VT type.
9204 // The loads feeding into the v8i16 and v16i8 types will be extending because
9205 // scalar i8/i16 are not legal types.
9206 if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9207 (MemVT == Ty.getVectorElementType()))
9208 return true;
9209
9210 if (Ty == MVT::v2i64) {
9211 // Check the extend type, when the input type is i32, and the output vector
9212 // type is v2i64.
9213 if (MemVT == MVT::i32) {
9214 if (ISD::isZEXTLoad(InputNode))
9215 Opcode = PPCISD::ZEXT_LD_SPLAT;
9216 if (ISD::isSEXTLoad(InputNode))
9217 Opcode = PPCISD::SEXT_LD_SPLAT;
9218 }
9219 return true;
9220 }
9221 return false;
9222}
9223
9224// If this is a case we can't handle, return null and let the default
9225// expansion code take care of it. If we CAN select this case, and if it
9226// selects to a single instruction, return Op. Otherwise, if we can codegen
9227// this case more efficiently than a constant pool load, lower it to the
9228// sequence of ops that should be used.
9229SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9230 SelectionDAG &DAG) const {
9231 SDLoc dl(Op);
9232 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9233 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR")(static_cast <bool> (BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"
) ? void (0) : __assert_fail ("BVN && \"Expected a BuildVectorSDNode in LowerBUILD_VECTOR\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9233, __extension__
__PRETTY_FUNCTION__))
;
9234
9235 // Check if this is a splat of a constant value.
9236 APInt APSplatBits, APSplatUndef;
9237 unsigned SplatBitSize;
9238 bool HasAnyUndefs;
9239 bool BVNIsConstantSplat =
9240 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9241 HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9242
9243 // If it is a splat of a double, check if we can shrink it to a 32 bit
9244 // non-denormal float which when converted back to double gives us the same
9245 // double. This is to exploit the XXSPLTIDP instruction.
9246 // If we lose precision, we use XXSPLTI32DX.
9247 if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9248 Subtarget.hasPrefixInstrs()) {
9249 // Check the type first to short-circuit so we don't modify APSplatBits if
9250 // this block isn't executed.
9251 if ((Op->getValueType(0) == MVT::v2f64) &&
9252 convertToNonDenormSingle(APSplatBits)) {
9253 SDValue SplatNode = DAG.getNode(
9254 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9255 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9256 return DAG.getBitcast(Op.getValueType(), SplatNode);
9257 } else {
9258 // We may lose precision, so we have to use XXSPLTI32DX.
9259
9260 uint32_t Hi =
9261 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9262 uint32_t Lo =
9263 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9264 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9265
9266 if (!Hi || !Lo)
9267 // If either load is 0, then we should generate XXLXOR to set to 0.
9268 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9269
9270 if (Hi)
9271 SplatNode = DAG.getNode(
9272 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9273 DAG.getTargetConstant(0, dl, MVT::i32),
9274 DAG.getTargetConstant(Hi, dl, MVT::i32));
9275
9276 if (Lo)
9277 SplatNode =
9278 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9279 DAG.getTargetConstant(1, dl, MVT::i32),
9280 DAG.getTargetConstant(Lo, dl, MVT::i32));
9281
9282 return DAG.getBitcast(Op.getValueType(), SplatNode);
9283 }
9284 }
9285
9286 if (!BVNIsConstantSplat || SplatBitSize > 32) {
9287 unsigned NewOpcode = PPCISD::LD_SPLAT;
9288
9289 // Handle load-and-splat patterns as we have instructions that will do this
9290 // in one go.
9291 if (DAG.isSplatValue(Op, true) &&
9292 isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9293 const SDValue *InputLoad = &Op.getOperand(0);
9294 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9295
9296 // If the input load is an extending load, it will be an i32 -> i64
9297 // extending load and isValidSplatLoad() will update NewOpcode.
9298 unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9299 unsigned ElementSize =
9300 MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9301
9302 assert(((ElementSize == 2 * MemorySize)(static_cast <bool> (((ElementSize == 2 * MemorySize) ?
(NewOpcode == PPCISD::ZEXT_LD_SPLAT || NewOpcode == PPCISD::
SEXT_LD_SPLAT) : (NewOpcode == PPCISD::LD_SPLAT)) && "Unmatched element size and opcode!\n"
) ? void (0) : __assert_fail ("((ElementSize == 2 * MemorySize) ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || NewOpcode == PPCISD::SEXT_LD_SPLAT) : (NewOpcode == PPCISD::LD_SPLAT)) && \"Unmatched element size and opcode!\\n\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9306, __extension__
__PRETTY_FUNCTION__))
9303 ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||(static_cast <bool> (((ElementSize == 2 * MemorySize) ?
(NewOpcode == PPCISD::ZEXT_LD_SPLAT || NewOpcode == PPCISD::
SEXT_LD_SPLAT) : (NewOpcode == PPCISD::LD_SPLAT)) && "Unmatched element size and opcode!\n"
) ? void (0) : __assert_fail ("((ElementSize == 2 * MemorySize) ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || NewOpcode == PPCISD::SEXT_LD_SPLAT) : (NewOpcode == PPCISD::LD_SPLAT)) && \"Unmatched element size and opcode!\\n\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9306, __extension__
__PRETTY_FUNCTION__))
9304 NewOpcode == PPCISD::SEXT_LD_SPLAT)(static_cast <bool> (((ElementSize == 2 * MemorySize) ?
(NewOpcode == PPCISD::ZEXT_LD_SPLAT || NewOpcode == PPCISD::
SEXT_LD_SPLAT) : (NewOpcode == PPCISD::LD_SPLAT)) && "Unmatched element size and opcode!\n"
) ? void (0) : __assert_fail ("((ElementSize == 2 * MemorySize) ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || NewOpcode == PPCISD::SEXT_LD_SPLAT) : (NewOpcode == PPCISD::LD_SPLAT)) && \"Unmatched element size and opcode!\\n\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9306, __extension__
__PRETTY_FUNCTION__))
9305 : (NewOpcode == PPCISD::LD_SPLAT)) &&(static_cast <bool> (((ElementSize == 2 * MemorySize) ?
(NewOpcode == PPCISD::ZEXT_LD_SPLAT || NewOpcode == PPCISD::
SEXT_LD_SPLAT) : (NewOpcode == PPCISD::LD_SPLAT)) && "Unmatched element size and opcode!\n"
) ? void (0) : __assert_fail ("((ElementSize == 2 * MemorySize) ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || NewOpcode == PPCISD::SEXT_LD_SPLAT) : (NewOpcode == PPCISD::LD_SPLAT)) && \"Unmatched element size and opcode!\\n\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9306, __extension__
__PRETTY_FUNCTION__))
9306 "Unmatched element size and opcode!\n")(static_cast <bool> (((ElementSize == 2 * MemorySize) ?
(NewOpcode == PPCISD::ZEXT_LD_SPLAT || NewOpcode == PPCISD::
SEXT_LD_SPLAT) : (NewOpcode == PPCISD::LD_SPLAT)) && "Unmatched element size and opcode!\n"
) ? void (0) : __assert_fail ("((ElementSize == 2 * MemorySize) ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || NewOpcode == PPCISD::SEXT_LD_SPLAT) : (NewOpcode == PPCISD::LD_SPLAT)) && \"Unmatched element size and opcode!\\n\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9306, __extension__
__PRETTY_FUNCTION__))
;
9307
9308 // Checking for a single use of this load, we have to check for vector
9309 // width (128 bits) / ElementSize uses (since each operand of the
9310 // BUILD_VECTOR is a separate use of the value.
9311 unsigned NumUsesOfInputLD = 128 / ElementSize;
9312 for (SDValue BVInOp : Op->ops())
9313 if (BVInOp.isUndef())
9314 NumUsesOfInputLD--;
9315
9316 // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9317 // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9318 // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9319 // 15", but function IsValidSplatLoad() now will only return true when
9320 // the data at index 0 is not nullptr. So we will not get into trouble for
9321 // these cases.
9322 //
9323 // case 1 - lfiwzx/lfiwax
9324 // 1.1: load result is i32 and is sign/zero extend to i64;
9325 // 1.2: build a v2i64 vector type with above loaded value;
9326 // 1.3: the vector has only one value at index 0, others are all undef;
9327 // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9328 if (NumUsesOfInputLD == 1 &&
9329 (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9330 !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9331 Subtarget.hasLFIWAX()))
9332 return SDValue();
9333
9334 // case 2 - lxvr[hb]x
9335 // 2.1: load result is at most i16;
9336 // 2.2: build a vector with above loaded value;
9337 // 2.3: the vector has only one value at index 0, others are all undef;
9338 // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9339 if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9340 Subtarget.isISA3_1() && ElementSize <= 16)
9341 return SDValue();
9342
9343 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?")(static_cast <bool> (NumUsesOfInputLD > 0 &&
"No uses of input LD of a build_vector?") ? void (0) : __assert_fail
("NumUsesOfInputLD > 0 && \"No uses of input LD of a build_vector?\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9343, __extension__
__PRETTY_FUNCTION__))
;
9344 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9345 Subtarget.hasVSX()) {
9346 SDValue Ops[] = {
9347 LD->getChain(), // Chain
9348 LD->getBasePtr(), // Ptr
9349 DAG.getValueType(Op.getValueType()) // VT
9350 };
9351 SDValue LdSplt = DAG.getMemIntrinsicNode(
9352 NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9353 LD->getMemoryVT(), LD->getMemOperand());
9354 // Replace all uses of the output chain of the original load with the
9355 // output chain of the new load.
9356 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9357 LdSplt.getValue(1));
9358 return LdSplt;
9359 }
9360 }
9361
9362 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9363 // 32-bits can be lowered to VSX instructions under certain conditions.
9364 // Without VSX, there is no pattern more efficient than expanding the node.
9365 if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9366 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9367 Subtarget.hasP8Vector()))
9368 return Op;
9369 return SDValue();
9370 }
9371
9372 uint64_t SplatBits = APSplatBits.getZExtValue();
9373 uint64_t SplatUndef = APSplatUndef.getZExtValue();
9374 unsigned SplatSize = SplatBitSize / 8;
9375
9376 // First, handle single instruction cases.
9377
9378 // All zeros?
9379 if (SplatBits == 0) {
9380 // Canonicalize all zero vectors to be v4i32.
9381 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9382 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9383 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9384 }
9385 return Op;
9386 }
9387
9388 // We have XXSPLTIW for constant splats four bytes wide.
9389 // Given vector length is a multiple of 4, 2-byte splats can be replaced
9390 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9391 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9392 // turned into a 4-byte splat of 0xABABABAB.
9393 if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9394 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9395 Op.getValueType(), DAG, dl);
9396
9397 if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9398 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9399 dl);
9400
9401 // We have XXSPLTIB for constant splats one byte wide.
9402 if (Subtarget.hasP9Vector() && SplatSize == 1)
9403 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9404 dl);
9405
9406 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9407 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9408 (32-SplatBitSize));
9409 if (SextVal >= -16 && SextVal <= 15)
9410 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9411 dl);
9412
9413 // Two instruction sequences.
9414
9415 // If this value is in the range [-32,30] and is even, use:
9416 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9417 // If this value is in the range [17,31] and is odd, use:
9418 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9419 // If this value is in the range [-31,-17] and is odd, use:
9420 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9421 // Note the last two are three-instruction sequences.
9422 if (SextVal >= -32 && SextVal <= 31) {
9423 // To avoid having these optimizations undone by constant folding,
9424 // we convert to a pseudo that will be expanded later into one of
9425 // the above forms.
9426 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9427 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9428 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9429 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9430 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9431 if (VT == Op.getValueType())
9432 return RetVal;
9433 else
9434 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9435 }
9436
9437 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
9438 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
9439 // for fneg/fabs.
9440 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9441 // Make -1 and vspltisw -1:
9442 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9443
9444 // Make the VSLW intrinsic, computing 0x8000_0000.
9445 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9446 OnesV, DAG, dl);
9447
9448 // xor by OnesV to invert it.
9449 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9450 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9451 }
9452
9453 // Check to see if this is a wide variety of vsplti*, binop self cases.
9454 static const signed char SplatCsts[] = {
9455 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9456 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9457 };
9458
9459 for (unsigned idx = 0; idx < std::size(SplatCsts); ++idx) {
9460 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9461 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
9462 int i = SplatCsts[idx];
9463
9464 // Figure out what shift amount will be used by altivec if shifted by i in
9465 // this splat size.
9466 unsigned TypeShiftAmt = i & (SplatBitSize-1);
9467
9468 // vsplti + shl self.
9469 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9470 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9471 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9472 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9473 Intrinsic::ppc_altivec_vslw
9474 };
9475 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9476 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9477 }
9478
9479 // vsplti + srl self.
9480 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9481 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9482 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9483 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9484 Intrinsic::ppc_altivec_vsrw
9485 };
9486 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9487 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9488 }
9489
9490 // vsplti + rol self.
9491 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9492 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9493 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9494 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9495 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9496 Intrinsic::ppc_altivec_vrlw
9497 };
9498 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9499 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9500 }
9501
9502 // t = vsplti c, result = vsldoi t, t, 1
9503 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9504 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9505 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9506 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9507 }
9508 // t = vsplti c, result = vsldoi t, t, 2
9509 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9510 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9511 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9512 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9513 }
9514 // t = vsplti c, result = vsldoi t, t, 3
9515 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9516 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9517 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9518 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9519 }
9520 }
9521
9522 return SDValue();
9523}
9524
9525/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9526/// the specified operations to build the shuffle.
9527static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9528 SDValue RHS, SelectionDAG &DAG,
9529 const SDLoc &dl) {
9530 unsigned OpNum = (PFEntry >> 26) & 0x0F;
9531 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9532 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
9533
9534 enum {
9535 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9536 OP_VMRGHW,
9537 OP_VMRGLW,
9538 OP_VSPLTISW0,
9539 OP_VSPLTISW1,
9540 OP_VSPLTISW2,
9541 OP_VSPLTISW3,
9542 OP_VSLDOI4,
9543 OP_VSLDOI8,
9544 OP_VSLDOI12
9545 };
9546
9547 if (OpNum == OP_COPY) {
9548 if (LHSID == (1*9+2)*9+3) return LHS;
9549 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!")(static_cast <bool> (LHSID == ((4*9+5)*9+6)*9+7 &&
"Illegal OP_COPY!") ? void (0) : __assert_fail ("LHSID == ((4*9+5)*9+6)*9+7 && \"Illegal OP_COPY!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9549, __extension__
__PRETTY_FUNCTION__))
;
9550 return RHS;
9551 }
9552
9553 SDValue OpLHS, OpRHS;
9554 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9555 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9556
9557 int ShufIdxs[16];
9558 switch (OpNum) {
9559 default: llvm_unreachable("Unknown i32 permute!")::llvm::llvm_unreachable_internal("Unknown i32 permute!", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 9559)
;
9560 case OP_VMRGHW:
9561 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
9562 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9563 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
9564 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9565 break;
9566 case OP_VMRGLW:
9567 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9568 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9569 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9570 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9571 break;
9572 case OP_VSPLTISW0:
9573 for (unsigned i = 0; i != 16; ++i)
9574 ShufIdxs[i] = (i&3)+0;
9575 break;
9576 case OP_VSPLTISW1:
9577 for (unsigned i = 0; i != 16; ++i)
9578 ShufIdxs[i] = (i&3)+4;
9579 break;
9580 case OP_VSPLTISW2:
9581 for (unsigned i = 0; i != 16; ++i)
9582 ShufIdxs[i] = (i&3)+8;
9583 break;
9584 case OP_VSPLTISW3:
9585 for (unsigned i = 0; i != 16; ++i)
9586 ShufIdxs[i] = (i&3)+12;
9587 break;
9588 case OP_VSLDOI4:
9589 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9590 case OP_VSLDOI8:
9591 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9592 case OP_VSLDOI12:
9593 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9594 }
9595 EVT VT = OpLHS.getValueType();
9596 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9597 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9598 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9599 return DAG.getNode(ISD::BITCAST, dl, VT, T);
9600}
9601
9602/// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9603/// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9604/// SDValue.
9605SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9606 SelectionDAG &DAG) const {
9607 const unsigned BytesInVector = 16;
9608 bool IsLE = Subtarget.isLittleEndian();
9609 SDLoc dl(N);
9610 SDValue V1 = N->getOperand(0);
9611 SDValue V2 = N->getOperand(1);
9612 unsigned ShiftElts = 0, InsertAtByte = 0;
9613 bool Swap = false;
9614
9615 // Shifts required to get the byte we want at element 7.
9616 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1,
9617 0, 15, 14, 13, 12, 11, 10, 9};
9618 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9619 1, 2, 3, 4, 5, 6, 7, 8};
9620
9621 ArrayRef<int> Mask = N->getMask();
9622 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9623
9624 // For each mask element, find out if we're just inserting something
9625 // from V2 into V1 or vice versa.
9626 // Possible permutations inserting an element from V2 into V1:
9627 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9628 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9629 // ...
9630 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9631 // Inserting from V1 into V2 will be similar, except mask range will be
9632 // [16,31].
9633
9634 bool FoundCandidate = false;
9635 // If both vector operands for the shuffle are the same vector, the mask
9636 // will contain only elements from the first one and the second one will be
9637 // undef.
9638 unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9639 // Go through the mask of half-words to find an element that's being moved
9640 // from one vector to the other.
9641 for (unsigned i = 0; i < BytesInVector; ++i) {
9642 unsigned CurrentElement = Mask[i];
9643 // If 2nd operand is undefined, we should only look for element 7 in the
9644 // Mask.
9645 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9646 continue;
9647
9648 bool OtherElementsInOrder = true;
9649 // Examine the other elements in the Mask to see if they're in original
9650 // order.
9651 for (unsigned j = 0; j < BytesInVector; ++j) {
9652 if (j == i)
9653 continue;
9654 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9655 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined,
9656 // in which we always assume we're always picking from the 1st operand.
9657 int MaskOffset =
9658 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9659 if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9660 OtherElementsInOrder = false;
9661 break;
9662 }
9663 }
9664 // If other elements are in original order, we record the number of shifts
9665 // we need to get the element we want into element 7. Also record which byte
9666 // in the vector we should insert into.
9667 if (OtherElementsInOrder) {
9668 // If 2nd operand is undefined, we assume no shifts and no swapping.
9669 if (V2.isUndef()) {
9670 ShiftElts = 0;
9671 Swap = false;
9672 } else {
9673 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9674 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9675 : BigEndianShifts[CurrentElement & 0xF];
9676 Swap = CurrentElement < BytesInVector;
9677 }
9678 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9679 FoundCandidate = true;
9680 break;
9681 }
9682 }
9683
9684 if (!FoundCandidate)
9685 return SDValue();
9686
9687 // Candidate found, construct the proper SDAG sequence with VINSERTB,
9688 // optionally with VECSHL if shift is required.
9689 if (Swap)
9690 std::swap(V1, V2);
9691 if (V2.isUndef())
9692 V2 = V1;
9693 if (ShiftElts) {
9694 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9695 DAG.getConstant(ShiftElts, dl, MVT::i32));
9696 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9697 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9698 }
9699 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9700 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9701}
9702
9703/// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9704/// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9705/// SDValue.
9706SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9707 SelectionDAG &DAG) const {
9708 const unsigned NumHalfWords = 8;
9709 const unsigned BytesInVector = NumHalfWords * 2;
9710 // Check that the shuffle is on half-words.
9711 if (!isNByteElemShuffleMask(N, 2, 1))
9712 return SDValue();
9713
9714 bool IsLE = Subtarget.isLittleEndian();
9715 SDLoc dl(N);
9716 SDValue V1 = N->getOperand(0);
9717 SDValue V2 = N->getOperand(1);
9718 unsigned ShiftElts = 0, InsertAtByte = 0;
9719 bool Swap = false;
9720
9721 // Shifts required to get the half-word we want at element 3.
9722 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9723 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9724
9725 uint32_t Mask = 0;
9726 uint32_t OriginalOrderLow = 0x1234567;
9727 uint32_t OriginalOrderHigh = 0x89ABCDEF;
9728 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a
9729 // 32-bit space, only need 4-bit nibbles per element.
9730 for (unsigned i = 0; i < NumHalfWords; ++i) {
9731 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9732 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9733 }
9734
9735 // For each mask element, find out if we're just inserting something
9736 // from V2 into V1 or vice versa. Possible permutations inserting an element
9737 // from V2 into V1:
9738 // X, 1, 2, 3, 4, 5, 6, 7
9739 // 0, X, 2, 3, 4, 5, 6, 7
9740 // 0, 1, X, 3, 4, 5, 6, 7
9741 // 0, 1, 2, X, 4, 5, 6, 7
9742 // 0, 1, 2, 3, X, 5, 6, 7
9743 // 0, 1, 2, 3, 4, X, 6, 7
9744 // 0, 1, 2, 3, 4, 5, X, 7
9745 // 0, 1, 2, 3, 4, 5, 6, X
9746 // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9747
9748 bool FoundCandidate = false;
9749 // Go through the mask of half-words to find an element that's being moved
9750 // from one vector to the other.
9751 for (unsigned i = 0; i < NumHalfWords; ++i) {
9752 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9753 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9754 uint32_t MaskOtherElts = ~(0xF << MaskShift);
9755 uint32_t TargetOrder = 0x0;
9756
9757 // If both vector operands for the shuffle are the same vector, the mask
9758 // will contain only elements from the first one and the second one will be
9759 // undef.
9760 if (V2.isUndef()) {
9761 ShiftElts = 0;
9762 unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9763 TargetOrder = OriginalOrderLow;
9764 Swap = false;
9765 // Skip if not the correct element or mask of other elements don't equal
9766 // to our expected order.
9767 if (MaskOneElt == VINSERTHSrcElem &&
9768 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9769 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9770 FoundCandidate = true;
9771 break;
9772 }
9773 } else { // If both operands are defined.
9774 // Target order is [8,15] if the current mask is between [0,7].
9775 TargetOrder =
9776 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9777 // Skip if mask of other elements don't equal our expected order.
9778 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9779 // We only need the last 3 bits for the number of shifts.
9780 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9781 : BigEndianShifts[MaskOneElt & 0x7];
9782 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9783 Swap = MaskOneElt < NumHalfWords;
9784 FoundCandidate = true;
9785 break;
9786 }
9787 }
9788 }
9789
9790 if (!FoundCandidate)
9791 return SDValue();
9792
9793 // Candidate found, construct the proper SDAG sequence with VINSERTH,
9794 // optionally with VECSHL if shift is required.
9795 if (Swap)
9796 std::swap(V1, V2);
9797 if (V2.isUndef())
9798 V2 = V1;
9799 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9800 if (ShiftElts) {
9801 // Double ShiftElts because we're left shifting on v16i8 type.
9802 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9803 DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9804 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9805 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9806 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9807 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9808 }
9809 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9810 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9811 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9812 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9813}
9814
9815/// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9816/// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9817/// return the default SDValue.
9818SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9819 SelectionDAG &DAG) const {
9820 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9821 // to v16i8. Peek through the bitcasts to get the actual operands.
9822 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9823 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9824
9825 auto ShuffleMask = SVN->getMask();
9826 SDValue VecShuffle(SVN, 0);
9827 SDLoc DL(SVN);
9828
9829 // Check that we have a four byte shuffle.
9830 if (!isNByteElemShuffleMask(SVN, 4, 1))
9831 return SDValue();
9832
9833 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9834 if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9835 std::swap(LHS, RHS);
9836 VecShuffle = peekThroughBitcasts(DAG.getCommutedVectorShuffle(*SVN));
9837 ShuffleVectorSDNode *CommutedSV = dyn_cast<ShuffleVectorSDNode>(VecShuffle);
9838 if (!CommutedSV)
9839 return SDValue();
9840 ShuffleMask = CommutedSV->getMask();
9841 }
9842
9843 // Ensure that the RHS is a vector of constants.
9844 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9845 if (!BVN)
9846 return SDValue();
9847
9848 // Check if RHS is a splat of 4-bytes (or smaller).
9849 APInt APSplatValue, APSplatUndef;
9850 unsigned SplatBitSize;
9851 bool HasAnyUndefs;
9852 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9853 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9854 SplatBitSize > 32)
9855 return SDValue();
9856
9857 // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9858 // The instruction splats a constant C into two words of the source vector
9859 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9860 // Thus we check that the shuffle mask is the equivalent of
9861 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9862 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9863 // within each word are consecutive, so we only need to check the first byte.
9864 SDValue Index;
9865 bool IsLE = Subtarget.isLittleEndian();
9866 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9867 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9868 ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9869 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9870 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9871 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9872 ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9873 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9874 else
9875 return SDValue();
9876
9877 // If the splat is narrower than 32-bits, we need to get the 32-bit value
9878 // for XXSPLTI32DX.
9879 unsigned SplatVal = APSplatValue.getZExtValue();
9880 for (; SplatBitSize < 32; SplatBitSize <<= 1)
9881 SplatVal |= (SplatVal << SplatBitSize);
9882
9883 SDValue SplatNode = DAG.getNode(
9884 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9885 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9886 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9887}
9888
9889/// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9890/// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9891/// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9892/// i.e (or (shl x, C1), (srl x, 128-C1)).
9893SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9894 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL")(static_cast <bool> (Op.getOpcode() == ISD::ROTL &&
"Should only be called for ISD::ROTL") ? void (0) : __assert_fail
("Op.getOpcode() == ISD::ROTL && \"Should only be called for ISD::ROTL\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9894, __extension__
__PRETTY_FUNCTION__))
;
9895 assert(Op.getValueType() == MVT::v1i128 &&(static_cast <bool> (Op.getValueType() == MVT::v1i128 &&
"Only set v1i128 as custom, other type shouldn't reach here!"
) ? void (0) : __assert_fail ("Op.getValueType() == MVT::v1i128 && \"Only set v1i128 as custom, other type shouldn't reach here!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9896, __extension__
__PRETTY_FUNCTION__))
9896 "Only set v1i128 as custom, other type shouldn't reach here!")(static_cast <bool> (Op.getValueType() == MVT::v1i128 &&
"Only set v1i128 as custom, other type shouldn't reach here!"
) ? void (0) : __assert_fail ("Op.getValueType() == MVT::v1i128 && \"Only set v1i128 as custom, other type shouldn't reach here!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9896, __extension__
__PRETTY_FUNCTION__))
;
9897 SDLoc dl(Op);
9898 SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9899 SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9900 unsigned SHLAmt = N1.getConstantOperandVal(0);
9901 if (SHLAmt % 8 == 0) {
9902 std::array<int, 16> Mask;
9903 std::iota(Mask.begin(), Mask.end(), 0);
9904 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9905 if (SDValue Shuffle =
9906 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9907 DAG.getUNDEF(MVT::v16i8), Mask))
9908 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9909 }
9910 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9911 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9912 DAG.getConstant(SHLAmt, dl, MVT::i32));
9913 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9914 DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9915 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9916 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9917}
9918
9919/// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
9920/// is a shuffle we can handle in a single instruction, return it. Otherwise,
9921/// return the code it can be lowered into. Worst case, it can always be
9922/// lowered into a vperm.
9923SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9924 SelectionDAG &DAG) const {
9925 SDLoc dl(Op);
9926 SDValue V1 = Op.getOperand(0);
9927 SDValue V2 = Op.getOperand(1);
9928 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9929
9930 // Any nodes that were combined in the target-independent combiner prior
9931 // to vector legalization will not be sent to the target combine. Try to
9932 // combine it here.
9933 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
1
Taking false branch
9934 if (!isa<ShuffleVectorSDNode>(NewShuffle))
9935 return NewShuffle;
9936 Op = NewShuffle;
9937 SVOp = cast<ShuffleVectorSDNode>(Op);
9938 V1 = Op.getOperand(0);
9939 V2 = Op.getOperand(1);
9940 }
9941 EVT VT = Op.getValueType();
9942 bool isLittleEndian = Subtarget.isLittleEndian();
9943
9944 unsigned ShiftElts, InsertAtByte;
2
'ShiftElts' declared without an initial value
9945 bool Swap = false;
9946
9947 // If this is a load-and-splat, we can do that with a single instruction
9948 // in some cases. However if the load has multiple uses, we don't want to
9949 // combine it because that will just produce multiple loads.
9950 bool IsPermutedLoad = false;
9951 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
3
Calling 'getNormalLoadInput'
7
Returning from 'getNormalLoadInput'
9952 if (InputLoad
7.1
'InputLoad' is null
&& Subtarget.hasVSX() && V2.isUndef() &&
9953 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9954 InputLoad->hasOneUse()) {
9955 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9956 int SplatIdx =
9957 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9958
9959 // The splat index for permuted loads will be in the left half of the vector
9960 // which is strictly wider than the loaded value by 8 bytes. So we need to
9961 // adjust the splat index to point to the correct address in memory.
9962 if (IsPermutedLoad) {
9963 assert((isLittleEndian || IsFourByte) &&(static_cast <bool> ((isLittleEndian || IsFourByte) &&
"Unexpected size for permuted load on big endian target") ? void
(0) : __assert_fail ("(isLittleEndian || IsFourByte) && \"Unexpected size for permuted load on big endian target\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9964, __extension__
__PRETTY_FUNCTION__))
9964 "Unexpected size for permuted load on big endian target")(static_cast <bool> ((isLittleEndian || IsFourByte) &&
"Unexpected size for permuted load on big endian target") ? void
(0) : __assert_fail ("(isLittleEndian || IsFourByte) && \"Unexpected size for permuted load on big endian target\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9964, __extension__
__PRETTY_FUNCTION__))
;
9965 SplatIdx += IsFourByte ? 2 : 1;
9966 assert((SplatIdx < (IsFourByte ? 4 : 2)) &&(static_cast <bool> ((SplatIdx < (IsFourByte ? 4 : 2
)) && "Splat of a value outside of the loaded memory"
) ? void (0) : __assert_fail ("(SplatIdx < (IsFourByte ? 4 : 2)) && \"Splat of a value outside of the loaded memory\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9967, __extension__
__PRETTY_FUNCTION__))
9967 "Splat of a value outside of the loaded memory")(static_cast <bool> ((SplatIdx < (IsFourByte ? 4 : 2
)) && "Splat of a value outside of the loaded memory"
) ? void (0) : __assert_fail ("(SplatIdx < (IsFourByte ? 4 : 2)) && \"Splat of a value outside of the loaded memory\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 9967, __extension__
__PRETTY_FUNCTION__))
;
9968 }
9969
9970 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9971 // For 4-byte load-and-splat, we need Power9.
9972 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9973 uint64_t Offset = 0;
9974 if (IsFourByte)
9975 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9976 else
9977 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9978
9979 // If the width of the load is the same as the width of the splat,
9980 // loading with an offset would load the wrong memory.
9981 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9982 Offset = 0;
9983
9984 SDValue BasePtr = LD->getBasePtr();
9985 if (Offset != 0)
9986 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9987 BasePtr, DAG.getIntPtrConstant(Offset, dl));
9988 SDValue Ops[] = {
9989 LD->getChain(), // Chain
9990 BasePtr, // BasePtr
9991 DAG.getValueType(Op.getValueType()) // VT
9992 };
9993 SDVTList VTL =
9994 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9995 SDValue LdSplt =
9996 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9997 Ops, LD->getMemoryVT(), LD->getMemOperand());
9998 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9999 if (LdSplt.getValueType() != SVOp->getValueType(0))
10000 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
10001 return LdSplt;
10002 }
10003 }
10004
10005 // All v2i64 and v2f64 shuffles are legal
10006 if (VT == MVT::v2i64 || VT == MVT::v2f64)
10007 return Op;
10008
10009 if (Subtarget.hasP9Vector() &&
8
Assuming the condition is false
10010 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
10011 isLittleEndian)) {
10012 if (Swap)
10013 std::swap(V1, V2);
10014 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10015 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
10016 if (ShiftElts) {
10017 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
10018 DAG.getConstant(ShiftElts, dl, MVT::i32));
10019 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
10020 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10021 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10022 }
10023 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
10024 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10025 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10026 }
10027
10028 if (Subtarget.hasPrefixInstrs()) {
9
Assuming the condition is false
10
Taking false branch
10029 SDValue SplatInsertNode;
10030 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
10031 return SplatInsertNode;
10032 }
10033
10034 if (Subtarget.hasP9Altivec()) {
11
Assuming the condition is false
10035 SDValue NewISDNode;
10036 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
10037 return NewISDNode;
10038
10039 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
10040 return NewISDNode;
10041 }
10042
10043 if (Subtarget.hasVSX() &&
12
Assuming the condition is true
32
Taking true branch
10044 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
13
Calling 'isXXSLDWIShuffleMask'
31
Returning from 'isXXSLDWIShuffleMask'
10045 if (Swap
32.1
'Swap' is false
)
33
Taking false branch
10046 std::swap(V1, V2);
10047 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10048 SDValue Conv2 =
10049 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
34
'?' condition is false
10050
10051 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
10052 DAG.getConstant(ShiftElts, dl, MVT::i32));
35
1st function call argument is an uninitialized value
10053 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
10054 }
10055
10056 if (Subtarget.hasVSX() &&
10057 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10058 if (Swap)
10059 std::swap(V1, V2);
10060 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10061 SDValue Conv2 =
10062 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
10063
10064 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
10065 DAG.getConstant(ShiftElts, dl, MVT::i32));
10066 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
10067 }
10068
10069 if (Subtarget.hasP9Vector()) {
10070 if (PPC::isXXBRHShuffleMask(SVOp)) {
10071 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10072 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10073 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10074 } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10075 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10076 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10077 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10078 } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10079 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10080 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10081 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10082 } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10083 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10084 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10085 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10086 }
10087 }
10088
10089 if (Subtarget.hasVSX()) {
10090 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10091 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10092
10093 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10094 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10095 DAG.getConstant(SplatIdx, dl, MVT::i32));
10096 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10097 }
10098
10099 // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10100 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10101 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10102 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10103 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10104 }
10105 }
10106
10107 // Cases that are handled by instructions that take permute immediates
10108 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10109 // selected by the instruction selector.
10110 if (V2.isUndef()) {
10111 if (PPC::isSplatShuffleMask(SVOp, 1) ||
10112 PPC::isSplatShuffleMask(SVOp, 2) ||
10113 PPC::isSplatShuffleMask(SVOp, 4) ||
10114 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10115 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10116 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10117 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10118 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10119 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10120 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10121 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10122 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10123 (Subtarget.hasP8Altivec() && (
10124 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10125 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10126 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10127 return Op;
10128 }
10129 }
10130
10131 // Altivec has a variety of "shuffle immediates" that take two vector inputs
10132 // and produce a fixed permutation. If any of these match, do not lower to
10133 // VPERM.
10134 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10135 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10136 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10137 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10138 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10139 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10140 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10141 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10142 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10143 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10144 (Subtarget.hasP8Altivec() && (
10145 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10146 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10147 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10148 return Op;
10149
10150 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
10151 // perfect shuffle table to emit an optimal matching sequence.
10152 ArrayRef<int> PermMask = SVOp->getMask();
10153
10154 if (!DisablePerfectShuffle && !isLittleEndian) {
10155 unsigned PFIndexes[4];
10156 bool isFourElementShuffle = true;
10157 for (unsigned i = 0; i != 4 && isFourElementShuffle;
10158 ++i) { // Element number
10159 unsigned EltNo = 8; // Start out undef.
10160 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
10161 if (PermMask[i * 4 + j] < 0)
10162 continue; // Undef, ignore it.
10163
10164 unsigned ByteSource = PermMask[i * 4 + j];
10165 if ((ByteSource & 3) != j) {
10166 isFourElementShuffle = false;
10167 break;
10168 }
10169
10170 if (EltNo == 8) {
10171 EltNo = ByteSource / 4;
10172 } else if (EltNo != ByteSource / 4) {
10173 isFourElementShuffle = false;
10174 break;
10175 }
10176 }
10177 PFIndexes[i] = EltNo;
10178 }
10179
10180 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10181 // perfect shuffle vector to determine if it is cost effective to do this as
10182 // discrete instructions, or whether we should use a vperm.
10183 // For now, we skip this for little endian until such time as we have a
10184 // little-endian perfect shuffle table.
10185 if (isFourElementShuffle) {
10186 // Compute the index in the perfect shuffle table.
10187 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10188 PFIndexes[2] * 9 + PFIndexes[3];
10189
10190 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10191 unsigned Cost = (PFEntry >> 30);
10192
10193 // Determining when to avoid vperm is tricky. Many things affect the cost
10194 // of vperm, particularly how many times the perm mask needs to be
10195 // computed. For example, if the perm mask can be hoisted out of a loop or
10196 // is already used (perhaps because there are multiple permutes with the
10197 // same shuffle mask?) the vperm has a cost of 1. OTOH, hoisting the
10198 // permute mask out of the loop requires an extra register.
10199 //
10200 // As a compromise, we only emit discrete instructions if the shuffle can
10201 // be generated in 3 or fewer operations. When we have loop information
10202 // available, if this block is within a loop, we should avoid using vperm
10203 // for 3-operation perms and use a constant pool load instead.
10204 if (Cost < 3)
10205 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10206 }
10207 }
10208
10209 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10210 // vector that will get spilled to the constant pool.
10211 if (V2.isUndef()) V2 = V1;
10212
10213 return LowerVPERM(Op, DAG, PermMask, VT, V1, V2);
10214}
10215
10216SDValue PPCTargetLowering::LowerVPERM(SDValue Op, SelectionDAG &DAG,
10217 ArrayRef<int> PermMask, EVT VT,
10218 SDValue V1, SDValue V2) const {
10219 unsigned Opcode = PPCISD::VPERM;
10220 EVT ValType = V1.getValueType();
10221 SDLoc dl(Op);
10222 bool NeedSwap = false;
10223 bool isLittleEndian = Subtarget.isLittleEndian();
10224 bool isPPC64 = Subtarget.isPPC64();
10225
10226 // Only need to place items backwards in LE,
10227 // the mask will be properly calculated.
10228 if (isLittleEndian)
10229 std::swap(V1, V2);
10230
10231 if (Subtarget.hasVSX() && Subtarget.hasP9Vector() &&
10232 (V1->hasOneUse() || V2->hasOneUse())) {
10233 LLVM_DEBUG(dbgs() << "At least one of two input vectors are dead - using "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { dbgs() << "At least one of two input vectors are dead - using "
"XXPERM instead\n"; } } while (false)
10234 "XXPERM instead\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { dbgs() << "At least one of two input vectors are dead - using "
"XXPERM instead\n"; } } while (false)
;
10235 Opcode = PPCISD::XXPERM;
10236
10237 // The second input to XXPERM is also an output so if the second input has
10238 // multiple uses then copying is necessary, as a result we want the
10239 // single-use operand to be used as the second input to prevent copying.
10240 if (!V2->hasOneUse() && V1->hasOneUse()) {
10241 std::swap(V1, V2);
10242 NeedSwap = !NeedSwap;
10243 }
10244 }
10245
10246 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10247 // that it is in input element units, not in bytes. Convert now.
10248
10249 // For little endian, the order of the input vectors is reversed, and
10250 // the permutation mask is complemented with respect to 31. This is
10251 // necessary to produce proper semantics with the big-endian-based vperm
10252 // instruction.
10253 EVT EltVT = V1.getValueType().getVectorElementType();
10254 unsigned BytesPerElement = EltVT.getSizeInBits() / 8;
10255
10256 bool V1HasXXSWAPD = V1->getOperand(0)->getOpcode() == PPCISD::XXSWAPD;
10257 bool V2HasXXSWAPD = V2->getOperand(0)->getOpcode() == PPCISD::XXSWAPD;
10258
10259 /*
10260 Vectors will be appended like so: [ V1 | v2 ]
10261 XXSWAPD on V1:
10262 [ A | B | C | D ] -> [ C | D | A | B ]
10263 0-3 4-7 8-11 12-15 0-3 4-7 8-11 12-15
10264 i.e. index of A, B += 8, and index of C, D -= 8.
10265 XXSWAPD on V2:
10266 [ E | F | G | H ] -> [ G | H | E | F ]
10267 16-19 20-23 24-27 28-31 16-19 20-23 24-27 28-31
10268 i.e. index of E, F += 8, index of G, H -= 8
10269 Swap V1 and V2:
10270 [ V1 | V2 ] -> [ V2 | V1 ]
10271 0-15 16-31 0-15 16-31
10272 i.e. index of V1 += 16, index of V2 -= 16
10273 */
10274
10275 SmallVector<SDValue, 16> ResultMask;
10276 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10277 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10278
10279 if (Opcode == PPCISD::XXPERM) {
10280 if (V1HasXXSWAPD) {
10281 if (SrcElt < 8)
10282 SrcElt += 8;
10283 else if (SrcElt < 16)
10284 SrcElt -= 8;
10285 }
10286 if (V2HasXXSWAPD) {
10287 if (SrcElt > 23)
10288 SrcElt -= 8;
10289 else if (SrcElt > 15)
10290 SrcElt += 8;
10291 }
10292 if (NeedSwap) {
10293 if (SrcElt < 16)
10294 SrcElt += 16;
10295 else
10296 SrcElt -= 16;
10297 }
10298 }
10299
10300 for (unsigned j = 0; j != BytesPerElement; ++j)
10301 if (isLittleEndian)
10302 ResultMask.push_back(
10303 DAG.getConstant(31 - (SrcElt * BytesPerElement + j), dl, MVT::i32));
10304 else
10305 ResultMask.push_back(
10306 DAG.getConstant(SrcElt * BytesPerElement + j, dl, MVT::i32));
10307 }
10308
10309 if (Opcode == PPCISD::XXPERM && (V1HasXXSWAPD || V2HasXXSWAPD)) {
10310 if (V1HasXXSWAPD) {
10311 dl = SDLoc(V1->getOperand(0));
10312 V1 = V1->getOperand(0)->getOperand(1);
10313 }
10314 if (V2HasXXSWAPD) {
10315 dl = SDLoc(V2->getOperand(0));
10316 V2 = V2->getOperand(0)->getOperand(1);
10317 }
10318 if (isPPC64 && ValType != MVT::v2f64)
10319 V1 = DAG.getBitcast(MVT::v2f64, V1);
10320 if (isPPC64 && V2.getValueType() != MVT::v2f64)
10321 V2 = DAG.getBitcast(MVT::v2f64, V2);
10322 }
10323
10324 ShufflesHandledWithVPERM++;
10325 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10326 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
10327 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
10328 if (Opcode == PPCISD::XXPERM) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
10329 dbgs() << "Emitting a XXPERM for the following shuffle:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
10330 } else {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
10331 dbgs() << "Emitting a VPERM for the following shuffle:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
10332 }do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
10333 SVOp->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
10334 dbgs() << "With the following permute control vector:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
10335 VPermMask.dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
10336 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode
>(Op); if (Opcode == PPCISD::XXPERM) { dbgs() << "Emitting a XXPERM for the following shuffle:\n"
; } else { dbgs() << "Emitting a VPERM for the following shuffle:\n"
; } SVOp->dump(); dbgs() << "With the following permute control vector:\n"
; VPermMask.dump(); }; } } while (false)
;
10337
10338 if (Opcode == PPCISD::XXPERM)
10339 VPermMask = DAG.getBitcast(MVT::v4i32, VPermMask);
10340
10341 SDValue VPERMNode =
10342 DAG.getNode(Opcode, dl, V1.getValueType(), V1, V2, VPermMask);
10343
10344 VPERMNode = DAG.getBitcast(ValType, VPERMNode);
10345 return VPERMNode;
10346}
10347
10348/// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10349/// vector comparison. If it is, return true and fill in Opc/isDot with
10350/// information about the intrinsic.
10351static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10352 bool &isDot, const PPCSubtarget &Subtarget) {
10353 unsigned IntrinsicID =
10354 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10355 CompareOpc = -1;
10356 isDot = false;
10357 switch (IntrinsicID) {
10358 default:
10359 return false;
10360 // Comparison predicates.
10361 case Intrinsic::ppc_altivec_vcmpbfp_p:
10362 CompareOpc = 966;
10363 isDot = true;
10364 break;
10365 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10366 CompareOpc = 198;
10367 isDot = true;
10368 break;
10369 case Intrinsic::ppc_altivec_vcmpequb_p:
10370 CompareOpc = 6;
10371 isDot = true;
10372 break;
10373 case Intrinsic::ppc_altivec_vcmpequh_p:
10374 CompareOpc = 70;
10375 isDot = true;
10376 break;
10377 case Intrinsic::ppc_altivec_vcmpequw_p:
10378 CompareOpc = 134;
10379 isDot = true;
10380 break;
10381 case Intrinsic::ppc_altivec_vcmpequd_p:
10382 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10383 CompareOpc = 199;
10384 isDot = true;
10385 } else
10386 return false;
10387 break;
10388 case Intrinsic::ppc_altivec_vcmpneb_p:
10389 case Intrinsic::ppc_altivec_vcmpneh_p:
10390 case Intrinsic::ppc_altivec_vcmpnew_p:
10391 case Intrinsic::ppc_altivec_vcmpnezb_p:
10392 case Intrinsic::ppc_altivec_vcmpnezh_p:
10393 case Intrinsic::ppc_altivec_vcmpnezw_p:
10394 if (Subtarget.hasP9Altivec()) {
10395 switch (IntrinsicID) {
10396 default:
10397 llvm_unreachable("Unknown comparison intrinsic.")::llvm::llvm_unreachable_internal("Unknown comparison intrinsic."
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10397)
;
10398 case Intrinsic::ppc_altivec_vcmpneb_p:
10399 CompareOpc = 7;
10400 break;
10401 case Intrinsic::ppc_altivec_vcmpneh_p:
10402 CompareOpc = 71;
10403 break;
10404 case Intrinsic::ppc_altivec_vcmpnew_p:
10405 CompareOpc = 135;
10406 break;
10407 case Intrinsic::ppc_altivec_vcmpnezb_p:
10408 CompareOpc = 263;
10409 break;
10410 case Intrinsic::ppc_altivec_vcmpnezh_p:
10411 CompareOpc = 327;
10412 break;
10413 case Intrinsic::ppc_altivec_vcmpnezw_p:
10414 CompareOpc = 391;
10415 break;
10416 }
10417 isDot = true;
10418 } else
10419 return false;
10420 break;
10421 case Intrinsic::ppc_altivec_vcmpgefp_p:
10422 CompareOpc = 454;
10423 isDot = true;
10424 break;
10425 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10426 CompareOpc = 710;
10427 isDot = true;
10428 break;
10429 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10430 CompareOpc = 774;
10431 isDot = true;
10432 break;
10433 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10434 CompareOpc = 838;
10435 isDot = true;
10436 break;
10437 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10438 CompareOpc = 902;
10439 isDot = true;
10440 break;
10441 case Intrinsic::ppc_altivec_vcmpgtsd_p:
10442 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10443 CompareOpc = 967;
10444 isDot = true;
10445 } else
10446 return false;
10447 break;
10448 case Intrinsic::ppc_altivec_vcmpgtub_p:
10449 CompareOpc = 518;
10450 isDot = true;
10451 break;
10452 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10453 CompareOpc = 582;
10454 isDot = true;
10455 break;
10456 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10457 CompareOpc = 646;
10458 isDot = true;
10459 break;
10460 case Intrinsic::ppc_altivec_vcmpgtud_p:
10461 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10462 CompareOpc = 711;
10463 isDot = true;
10464 } else
10465 return false;
10466 break;
10467
10468 case Intrinsic::ppc_altivec_vcmpequq:
10469 case Intrinsic::ppc_altivec_vcmpgtsq:
10470 case Intrinsic::ppc_altivec_vcmpgtuq:
10471 if (!Subtarget.isISA3_1())
10472 return false;
10473 switch (IntrinsicID) {
10474 default:
10475 llvm_unreachable("Unknown comparison intrinsic.")::llvm::llvm_unreachable_internal("Unknown comparison intrinsic."
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10475)
;
10476 case Intrinsic::ppc_altivec_vcmpequq:
10477 CompareOpc = 455;
10478 break;
10479 case Intrinsic::ppc_altivec_vcmpgtsq:
10480 CompareOpc = 903;
10481 break;
10482 case Intrinsic::ppc_altivec_vcmpgtuq:
10483 CompareOpc = 647;
10484 break;
10485 }
10486 break;
10487
10488 // VSX predicate comparisons use the same infrastructure
10489 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10490 case Intrinsic::ppc_vsx_xvcmpgedp_p:
10491 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10492 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10493 case Intrinsic::ppc_vsx_xvcmpgesp_p:
10494 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10495 if (Subtarget.hasVSX()) {
10496 switch (IntrinsicID) {
10497 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10498 CompareOpc = 99;
10499 break;
10500 case Intrinsic::ppc_vsx_xvcmpgedp_p:
10501 CompareOpc = 115;
10502 break;
10503 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10504 CompareOpc = 107;
10505 break;
10506 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10507 CompareOpc = 67;
10508 break;
10509 case Intrinsic::ppc_vsx_xvcmpgesp_p:
10510 CompareOpc = 83;
10511 break;
10512 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10513 CompareOpc = 75;
10514 break;
10515 }
10516 isDot = true;
10517 } else
10518 return false;
10519 break;
10520
10521 // Normal Comparisons.
10522 case Intrinsic::ppc_altivec_vcmpbfp:
10523 CompareOpc = 966;
10524 break;
10525 case Intrinsic::ppc_altivec_vcmpeqfp:
10526 CompareOpc = 198;
10527 break;
10528 case Intrinsic::ppc_altivec_vcmpequb:
10529 CompareOpc = 6;
10530 break;
10531 case Intrinsic::ppc_altivec_vcmpequh:
10532 CompareOpc = 70;
10533 break;
10534 case Intrinsic::ppc_altivec_vcmpequw:
10535 CompareOpc = 134;
10536 break;
10537 case Intrinsic::ppc_altivec_vcmpequd:
10538 if (Subtarget.hasP8Altivec())
10539 CompareOpc = 199;
10540 else
10541 return false;
10542 break;
10543 case Intrinsic::ppc_altivec_vcmpneb:
10544 case Intrinsic::ppc_altivec_vcmpneh:
10545 case Intrinsic::ppc_altivec_vcmpnew:
10546 case Intrinsic::ppc_altivec_vcmpnezb:
10547 case Intrinsic::ppc_altivec_vcmpnezh:
10548 case Intrinsic::ppc_altivec_vcmpnezw:
10549 if (Subtarget.hasP9Altivec())
10550 switch (IntrinsicID) {
10551 default:
10552 llvm_unreachable("Unknown comparison intrinsic.")::llvm::llvm_unreachable_internal("Unknown comparison intrinsic."
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10552)
;
10553 case Intrinsic::ppc_altivec_vcmpneb:
10554 CompareOpc = 7;
10555 break;
10556 case Intrinsic::ppc_altivec_vcmpneh:
10557 CompareOpc = 71;
10558 break;
10559 case Intrinsic::ppc_altivec_vcmpnew:
10560 CompareOpc = 135;
10561 break;
10562 case Intrinsic::ppc_altivec_vcmpnezb:
10563 CompareOpc = 263;
10564 break;
10565 case Intrinsic::ppc_altivec_vcmpnezh:
10566 CompareOpc = 327;
10567 break;
10568 case Intrinsic::ppc_altivec_vcmpnezw:
10569 CompareOpc = 391;
10570 break;
10571 }
10572 else
10573 return false;
10574 break;
10575 case Intrinsic::ppc_altivec_vcmpgefp:
10576 CompareOpc = 454;
10577 break;
10578 case Intrinsic::ppc_altivec_vcmpgtfp:
10579 CompareOpc = 710;
10580 break;
10581 case Intrinsic::ppc_altivec_vcmpgtsb:
10582 CompareOpc = 774;
10583 break;
10584 case Intrinsic::ppc_altivec_vcmpgtsh:
10585 CompareOpc = 838;
10586 break;
10587 case Intrinsic::ppc_altivec_vcmpgtsw:
10588 CompareOpc = 902;
10589 break;
10590 case Intrinsic::ppc_altivec_vcmpgtsd:
10591 if (Subtarget.hasP8Altivec())
10592 CompareOpc = 967;
10593 else
10594 return false;
10595 break;
10596 case Intrinsic::ppc_altivec_vcmpgtub:
10597 CompareOpc = 518;
10598 break;
10599 case Intrinsic::ppc_altivec_vcmpgtuh:
10600 CompareOpc = 582;
10601 break;
10602 case Intrinsic::ppc_altivec_vcmpgtuw:
10603 CompareOpc = 646;
10604 break;
10605 case Intrinsic::ppc_altivec_vcmpgtud:
10606 if (Subtarget.hasP8Altivec())
10607 CompareOpc = 711;
10608 else
10609 return false;
10610 break;
10611 case Intrinsic::ppc_altivec_vcmpequq_p:
10612 case Intrinsic::ppc_altivec_vcmpgtsq_p:
10613 case Intrinsic::ppc_altivec_vcmpgtuq_p:
10614 if (!Subtarget.isISA3_1())
10615 return false;
10616 switch (IntrinsicID) {
10617 default:
10618 llvm_unreachable("Unknown comparison intrinsic.")::llvm::llvm_unreachable_internal("Unknown comparison intrinsic."
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10618)
;
10619 case Intrinsic::ppc_altivec_vcmpequq_p:
10620 CompareOpc = 455;
10621 break;
10622 case Intrinsic::ppc_altivec_vcmpgtsq_p:
10623 CompareOpc = 903;
10624 break;
10625 case Intrinsic::ppc_altivec_vcmpgtuq_p:
10626 CompareOpc = 647;
10627 break;
10628 }
10629 isDot = true;
10630 break;
10631 }
10632 return true;
10633}
10634
10635/// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10636/// lower, do it, otherwise return null.
10637SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10638 SelectionDAG &DAG) const {
10639 unsigned IntrinsicID =
10640 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10641
10642 SDLoc dl(Op);
10643
10644 switch (IntrinsicID) {
10645 case Intrinsic::thread_pointer:
10646 // Reads the thread pointer register, used for __builtin_thread_pointer.
10647 if (Subtarget.isPPC64())
10648 return DAG.getRegister(PPC::X13, MVT::i64);
10649 return DAG.getRegister(PPC::R2, MVT::i32);
10650
10651 case Intrinsic::ppc_mma_disassemble_acc: {
10652 if (Subtarget.isISAFuture()) {
10653 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
10654 SDValue WideVec = SDValue(DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl,
10655 ArrayRef(ReturnTypes, 2),
10656 Op.getOperand(1)),
10657 0);
10658 SmallVector<SDValue, 4> RetOps;
10659 SDValue Value = SDValue(WideVec.getNode(), 0);
10660 SDValue Value2 = SDValue(WideVec.getNode(), 1);
10661
10662 SDValue Extract;
10663 Extract = DAG.getNode(
10664 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
10665 Subtarget.isLittleEndian() ? Value2 : Value,
10666 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0,
10667 dl, getPointerTy(DAG.getDataLayout())));
10668 RetOps.push_back(Extract);
10669 Extract = DAG.getNode(
10670 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
10671 Subtarget.isLittleEndian() ? Value2 : Value,
10672 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1,
10673 dl, getPointerTy(DAG.getDataLayout())));
10674 RetOps.push_back(Extract);
10675 Extract = DAG.getNode(
10676 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
10677 Subtarget.isLittleEndian() ? Value : Value2,
10678 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0,
10679 dl, getPointerTy(DAG.getDataLayout())));
10680 RetOps.push_back(Extract);
10681 Extract = DAG.getNode(
10682 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
10683 Subtarget.isLittleEndian() ? Value : Value2,
10684 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1,
10685 dl, getPointerTy(DAG.getDataLayout())));
10686 RetOps.push_back(Extract);
10687 return DAG.getMergeValues(RetOps, dl);
10688 }
10689 LLVM_FALLTHROUGH[[fallthrough]];
10690 }
10691 case Intrinsic::ppc_vsx_disassemble_pair: {
10692 int NumVecs = 2;
10693 SDValue WideVec = Op.getOperand(1);
10694 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10695 NumVecs = 4;
10696 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10697 }
10698 SmallVector<SDValue, 4> RetOps;
10699 for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10700 SDValue Extract = DAG.getNode(
10701 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10702 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10703 : VecNo,
10704 dl, getPointerTy(DAG.getDataLayout())));
10705 RetOps.push_back(Extract);
10706 }
10707 return DAG.getMergeValues(RetOps, dl);
10708 }
10709
10710 case Intrinsic::ppc_unpack_longdouble: {
10711 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10712 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&(static_cast <bool> (Idx && (Idx->getSExtValue
() == 0 || Idx->getSExtValue() == 1) && "Argument of long double unpack must be 0 or 1!"
) ? void (0) : __assert_fail ("Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) && \"Argument of long double unpack must be 0 or 1!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10713, __extension__
__PRETTY_FUNCTION__))
10713 "Argument of long double unpack must be 0 or 1!")(static_cast <bool> (Idx && (Idx->getSExtValue
() == 0 || Idx->getSExtValue() == 1) && "Argument of long double unpack must be 0 or 1!"
) ? void (0) : __assert_fail ("Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) && \"Argument of long double unpack must be 0 or 1!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10713, __extension__
__PRETTY_FUNCTION__))
;
10714 return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
10715 DAG.getConstant(!!(Idx->getSExtValue()), dl,
10716 Idx->getValueType(0)));
10717 }
10718
10719 case Intrinsic::ppc_compare_exp_lt:
10720 case Intrinsic::ppc_compare_exp_gt:
10721 case Intrinsic::ppc_compare_exp_eq:
10722 case Intrinsic::ppc_compare_exp_uo: {
10723 unsigned Pred;
10724 switch (IntrinsicID) {
10725 case Intrinsic::ppc_compare_exp_lt:
10726 Pred = PPC::PRED_LT;
10727 break;
10728 case Intrinsic::ppc_compare_exp_gt:
10729 Pred = PPC::PRED_GT;
10730 break;
10731 case Intrinsic::ppc_compare_exp_eq:
10732 Pred = PPC::PRED_EQ;
10733 break;
10734 case Intrinsic::ppc_compare_exp_uo:
10735 Pred = PPC::PRED_UN;
10736 break;
10737 }
10738 return SDValue(
10739 DAG.getMachineNode(
10740 PPC::SELECT_CC_I4, dl, MVT::i32,
10741 {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10742 Op.getOperand(1), Op.getOperand(2)),
10743 0),
10744 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10745 DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10746 0);
10747 }
10748 case Intrinsic::ppc_test_data_class: {
10749 EVT OpVT = Op.getOperand(1).getValueType();
10750 unsigned CmprOpc = OpVT == MVT::f128 ? PPC::XSTSTDCQP
10751 : (OpVT == MVT::f64 ? PPC::XSTSTDCDP
10752 : PPC::XSTSTDCSP);
10753 return SDValue(
10754 DAG.getMachineNode(
10755 PPC::SELECT_CC_I4, dl, MVT::i32,
10756 {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10757 Op.getOperand(1)),
10758 0),
10759 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10760 DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10761 0);
10762 }
10763 case Intrinsic::ppc_fnmsub: {
10764 EVT VT = Op.getOperand(1).getValueType();
10765 if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128))
10766 return DAG.getNode(
10767 ISD::FNEG, dl, VT,
10768 DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2),
10769 DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3))));
10770 return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1),
10771 Op.getOperand(2), Op.getOperand(3));
10772 }
10773 case Intrinsic::ppc_convert_f128_to_ppcf128:
10774 case Intrinsic::ppc_convert_ppcf128_to_f128: {
10775 RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
10776 ? RTLIB::CONVERT_PPCF128_F128
10777 : RTLIB::CONVERT_F128_PPCF128;
10778 MakeLibCallOptions CallOptions;
10779 std::pair<SDValue, SDValue> Result =
10780 makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
10781 dl, SDValue());
10782 return Result.first;
10783 }
10784 case Intrinsic::ppc_maxfe:
10785 case Intrinsic::ppc_maxfl:
10786 case Intrinsic::ppc_maxfs:
10787 case Intrinsic::ppc_minfe:
10788 case Intrinsic::ppc_minfl:
10789 case Intrinsic::ppc_minfs: {
10790 EVT VT = Op.getValueType();
10791 assert((static_cast <bool> (all_of(Op->ops().drop_front(4),
[VT](const SDUse &Use) { return Use.getValueType() == VT
; }) && "ppc_[max|min]f[e|l|s] must have uniform type arguments"
) ? void (0) : __assert_fail ("all_of(Op->ops().drop_front(4), [VT](const SDUse &Use) { return Use.getValueType() == VT; }) && \"ppc_[max|min]f[e|l|s] must have uniform type arguments\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10794, __extension__
__PRETTY_FUNCTION__))
10792 all_of(Op->ops().drop_front(4),(static_cast <bool> (all_of(Op->ops().drop_front(4),
[VT](const SDUse &Use) { return Use.getValueType() == VT
; }) && "ppc_[max|min]f[e|l|s] must have uniform type arguments"
) ? void (0) : __assert_fail ("all_of(Op->ops().drop_front(4), [VT](const SDUse &Use) { return Use.getValueType() == VT; }) && \"ppc_[max|min]f[e|l|s] must have uniform type arguments\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10794, __extension__
__PRETTY_FUNCTION__))
10793 [VT](const SDUse &Use) { return Use.getValueType() == VT; }) &&(static_cast <bool> (all_of(Op->ops().drop_front(4),
[VT](const SDUse &Use) { return Use.getValueType() == VT
; }) && "ppc_[max|min]f[e|l|s] must have uniform type arguments"
) ? void (0) : __assert_fail ("all_of(Op->ops().drop_front(4), [VT](const SDUse &Use) { return Use.getValueType() == VT; }) && \"ppc_[max|min]f[e|l|s] must have uniform type arguments\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10794, __extension__
__PRETTY_FUNCTION__))
10794 "ppc_[max|min]f[e|l|s] must have uniform type arguments")(static_cast <bool> (all_of(Op->ops().drop_front(4),
[VT](const SDUse &Use) { return Use.getValueType() == VT
; }) && "ppc_[max|min]f[e|l|s] must have uniform type arguments"
) ? void (0) : __assert_fail ("all_of(Op->ops().drop_front(4), [VT](const SDUse &Use) { return Use.getValueType() == VT; }) && \"ppc_[max|min]f[e|l|s] must have uniform type arguments\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10794, __extension__
__PRETTY_FUNCTION__))
;
10795 (void)VT;
10796 ISD::CondCode CC = ISD::SETGT;
10797 if (IntrinsicID == Intrinsic::ppc_minfe ||
10798 IntrinsicID == Intrinsic::ppc_minfl ||
10799 IntrinsicID == Intrinsic::ppc_minfs)
10800 CC = ISD::SETLT;
10801 unsigned I = Op.getNumOperands() - 2, Cnt = I;
10802 SDValue Res = Op.getOperand(I);
10803 for (--I; Cnt != 0; --Cnt, I = (--I == 0 ? (Op.getNumOperands() - 1) : I)) {
10804 Res =
10805 DAG.getSelectCC(dl, Res, Op.getOperand(I), Res, Op.getOperand(I), CC);
10806 }
10807 return Res;
10808 }
10809 }
10810
10811 // If this is a lowered altivec predicate compare, CompareOpc is set to the
10812 // opcode number of the comparison.
10813 int CompareOpc;
10814 bool isDot;
10815 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10816 return SDValue(); // Don't custom lower most intrinsics.
10817
10818 // If this is a non-dot comparison, make the VCMP node and we are done.
10819 if (!isDot) {
10820 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10821 Op.getOperand(1), Op.getOperand(2),
10822 DAG.getConstant(CompareOpc, dl, MVT::i32));
10823 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10824 }
10825
10826 // Create the PPCISD altivec 'dot' comparison node.
10827 SDValue Ops[] = {
10828 Op.getOperand(2), // LHS
10829 Op.getOperand(3), // RHS
10830 DAG.getConstant(CompareOpc, dl, MVT::i32)
10831 };
10832 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10833 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10834
10835 // Now that we have the comparison, emit a copy from the CR to a GPR.
10836 // This is flagged to the above dot comparison.
10837 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10838 DAG.getRegister(PPC::CR6, MVT::i32),
10839 CompNode.getValue(1));
10840
10841 // Unpack the result based on how the target uses it.
10842 unsigned BitNo; // Bit # of CR6.
10843 bool InvertBit; // Invert result?
10844 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10845 default: // Can't happen, don't crash on invalid number though.
10846 case 0: // Return the value of the EQ bit of CR6.
10847 BitNo = 0; InvertBit = false;
10848 break;
10849 case 1: // Return the inverted value of the EQ bit of CR6.
10850 BitNo = 0; InvertBit = true;
10851 break;
10852 case 2: // Return the value of the LT bit of CR6.
10853 BitNo = 2; InvertBit = false;
10854 break;
10855 case 3: // Return the inverted value of the LT bit of CR6.
10856 BitNo = 2; InvertBit = true;
10857 break;
10858 }
10859
10860 // Shift the bit into the low position.
10861 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10862 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10863 // Isolate the bit.
10864 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10865 DAG.getConstant(1, dl, MVT::i32));
10866
10867 // If we are supposed to, toggle the bit.
10868 if (InvertBit)
10869 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10870 DAG.getConstant(1, dl, MVT::i32));
10871 return Flags;
10872}
10873
10874SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10875 SelectionDAG &DAG) const {
10876 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10877 // the beginning of the argument list.
10878 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10879 SDLoc DL(Op);
10880 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10881 case Intrinsic::ppc_cfence: {
10882 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.")(static_cast <bool> (ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."
) ? void (0) : __assert_fail ("ArgStart == 1 && \"llvm.ppc.cfence must carry a chain argument.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10882, __extension__
__PRETTY_FUNCTION__))
;
10883 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.")(static_cast <bool> (Subtarget.isPPC64() && "Only 64-bit is supported for now."
) ? void (0) : __assert_fail ("Subtarget.isPPC64() && \"Only 64-bit is supported for now.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10883, __extension__
__PRETTY_FUNCTION__))
;
10884 SDValue Val = Op.getOperand(ArgStart + 1);
10885 EVT Ty = Val.getValueType();
10886 if (Ty == MVT::i128) {
10887 // FIXME: Testing one of two paired registers is sufficient to guarantee
10888 // ordering?
10889 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10890 }
10891 return SDValue(
10892 DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10893 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10894 Op.getOperand(0)),
10895 0);
10896 }
10897 default:
10898 break;
10899 }
10900 return SDValue();
10901}
10902
10903// Lower scalar BSWAP64 to xxbrd.
10904SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10905 SDLoc dl(Op);
10906 if (!Subtarget.isPPC64())
10907 return Op;
10908 // MTVSRDD
10909 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10910 Op.getOperand(0));
10911 // XXBRD
10912 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10913 // MFVSRD
10914 int VectorIndex = 0;
10915 if (Subtarget.isLittleEndian())
10916 VectorIndex = 1;
10917 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10918 DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10919 return Op;
10920}
10921
10922// ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10923// compared to a value that is atomically loaded (atomic loads zero-extend).
10924SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10925 SelectionDAG &DAG) const {
10926 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&(static_cast <bool> (Op.getOpcode() == ISD::ATOMIC_CMP_SWAP
&& "Expecting an atomic compare-and-swap here.") ? void
(0) : __assert_fail ("Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && \"Expecting an atomic compare-and-swap here.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10927, __extension__
__PRETTY_FUNCTION__))
10927 "Expecting an atomic compare-and-swap here.")(static_cast <bool> (Op.getOpcode() == ISD::ATOMIC_CMP_SWAP
&& "Expecting an atomic compare-and-swap here.") ? void
(0) : __assert_fail ("Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && \"Expecting an atomic compare-and-swap here.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10927, __extension__
__PRETTY_FUNCTION__))
;
10928 SDLoc dl(Op);
10929 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10930 EVT MemVT = AtomicNode->getMemoryVT();
10931 if (MemVT.getSizeInBits() >= 32)
10932 return Op;
10933
10934 SDValue CmpOp = Op.getOperand(2);
10935 // If this is already correctly zero-extended, leave it alone.
10936 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10937 if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10938 return Op;
10939
10940 // Clear the high bits of the compare operand.
10941 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10942 SDValue NewCmpOp =
10943 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10944 DAG.getConstant(MaskVal, dl, MVT::i32));
10945
10946 // Replace the existing compare operand with the properly zero-extended one.
10947 SmallVector<SDValue, 4> Ops;
10948 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10949 Ops.push_back(AtomicNode->getOperand(i));
10950 Ops[2] = NewCmpOp;
10951 MachineMemOperand *MMO = AtomicNode->getMemOperand();
10952 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10953 auto NodeTy =
10954 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10955 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10956}
10957
10958SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10959 SelectionDAG &DAG) const {
10960 AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10961 EVT MemVT = N->getMemoryVT();
10962 assert(MemVT.getSimpleVT() == MVT::i128 &&(static_cast <bool> (MemVT.getSimpleVT() == MVT::i128 &&
"Expect quadword atomic operations") ? void (0) : __assert_fail
("MemVT.getSimpleVT() == MVT::i128 && \"Expect quadword atomic operations\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10963, __extension__
__PRETTY_FUNCTION__))
10963 "Expect quadword atomic operations")(static_cast <bool> (MemVT.getSimpleVT() == MVT::i128 &&
"Expect quadword atomic operations") ? void (0) : __assert_fail
("MemVT.getSimpleVT() == MVT::i128 && \"Expect quadword atomic operations\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 10963, __extension__
__PRETTY_FUNCTION__))
;
10964 SDLoc dl(N);
10965 unsigned Opc = N->getOpcode();
10966 switch (Opc) {
10967 case ISD::ATOMIC_LOAD: {
10968 // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10969 // lowered to ppc instructions by pattern matching instruction selector.
10970 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10971 SmallVector<SDValue, 4> Ops{
10972 N->getOperand(0),
10973 DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10974 for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10975 Ops.push_back(N->getOperand(I));
10976 SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10977 Ops, MemVT, N->getMemOperand());
10978 SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10979 SDValue ValHi =
10980 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10981 ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10982 DAG.getConstant(64, dl, MVT::i32));
10983 SDValue Val =
10984 DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10985 return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10986 {Val, LoadedVal.getValue(2)});
10987 }
10988 case ISD::ATOMIC_STORE: {
10989 // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10990 // lowered to ppc instructions by pattern matching instruction selector.
10991 SDVTList Tys = DAG.getVTList(MVT::Other);
10992 SmallVector<SDValue, 4> Ops{
10993 N->getOperand(0),
10994 DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10995 SDValue Val = N->getOperand(2);
10996 SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10997 SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10998 DAG.getConstant(64, dl, MVT::i32));
10999 ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
11000 Ops.push_back(ValLo);
11001 Ops.push_back(ValHi);
11002 Ops.push_back(N->getOperand(1));
11003 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
11004 N->getMemOperand());
11005 }
11006 default:
11007 llvm_unreachable("Unexpected atomic opcode")::llvm::llvm_unreachable_internal("Unexpected atomic opcode",
"llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11007)
;
11008 }
11009}
11010
11011static SDValue getDataClassTest(SDValue Op, FPClassTest Mask, const SDLoc &Dl,
11012 SelectionDAG &DAG,
11013 const PPCSubtarget &Subtarget) {
11014 assert(Mask <= fcAllFlags && "Invalid fp_class flags!")(static_cast <bool> (Mask <= fcAllFlags && "Invalid fp_class flags!"
) ? void (0) : __assert_fail ("Mask <= fcAllFlags && \"Invalid fp_class flags!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11014, __extension__
__PRETTY_FUNCTION__))
;
11015
11016 enum DataClassMask {
11017 DC_NAN = 1 << 6,
11018 DC_NEG_INF = 1 << 4,
11019 DC_POS_INF = 1 << 5,
11020 DC_NEG_ZERO = 1 << 2,
11021 DC_POS_ZERO = 1 << 3,
11022 DC_NEG_SUBNORM = 1,
11023 DC_POS_SUBNORM = 1 << 1,
11024 };
11025
11026 EVT VT = Op.getValueType();
11027
11028 unsigned TestOp = VT == MVT::f128 ? PPC::XSTSTDCQP
11029 : VT == MVT::f64 ? PPC::XSTSTDCDP
11030 : PPC::XSTSTDCSP;
11031
11032 if (Mask == fcAllFlags)
11033 return DAG.getBoolConstant(true, Dl, MVT::i1, VT);
11034 if (Mask == 0)
11035 return DAG.getBoolConstant(false, Dl, MVT::i1, VT);
11036
11037 // When it's cheaper or necessary to test reverse flags.
11038 if ((Mask & fcNormal) == fcNormal || Mask == ~fcQNan || Mask == ~fcSNan) {
11039 SDValue Rev = getDataClassTest(Op, ~Mask, Dl, DAG, Subtarget);
11040 return DAG.getNOT(Dl, Rev, MVT::i1);
11041 }
11042
11043 // Power doesn't support testing whether a value is 'normal'. Test the rest
11044 // first, and test if it's 'not not-normal' with expected sign.
11045 if (Mask & fcNormal) {
11046 SDValue Rev(DAG.getMachineNode(
11047 TestOp, Dl, MVT::i32,
11048 DAG.getTargetConstant(DC_NAN | DC_NEG_INF | DC_POS_INF |
11049 DC_NEG_ZERO | DC_POS_ZERO |
11050 DC_NEG_SUBNORM | DC_POS_SUBNORM,
11051 Dl, MVT::i32),
11052 Op),
11053 0);
11054 // Sign are stored in CR bit 0, result are in CR bit 2.
11055 SDValue Sign(
11056 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1, Rev,
11057 DAG.getTargetConstant(PPC::sub_lt, Dl, MVT::i32)),
11058 0);
11059 SDValue Normal(DAG.getNOT(
11060 Dl,
11061 SDValue(DAG.getMachineNode(
11062 TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1, Rev,
11063 DAG.getTargetConstant(PPC::sub_eq, Dl, MVT::i32)),
11064 0),
11065 MVT::i1));
11066 if (Mask & fcPosNormal)
11067 Sign = DAG.getNOT(Dl, Sign, MVT::i1);
11068 SDValue Result = DAG.getNode(ISD::AND, Dl, MVT::i1, Sign, Normal);
11069 if (Mask == fcPosNormal || Mask == fcNegNormal)
11070 return Result;
11071
11072 return DAG.getNode(
11073 ISD::OR, Dl, MVT::i1,
11074 getDataClassTest(Op, Mask & ~fcNormal, Dl, DAG, Subtarget), Result);
11075 }
11076
11077 // The instruction doesn't differentiate between signaling or quiet NaN. Test
11078 // the rest first, and test if it 'is NaN and is signaling/quiet'.
11079 if ((Mask & fcNan) == fcQNan || (Mask & fcNan) == fcSNan) {
11080 bool IsQuiet = Mask & fcQNan;
11081 SDValue NanCheck = getDataClassTest(Op, fcNan, Dl, DAG, Subtarget);
11082
11083 // Quietness is determined by the first bit in fraction field.
11084 uint64_t QuietMask = 0;
11085 SDValue HighWord;
11086 if (VT == MVT::f128) {
11087 HighWord = DAG.getNode(
11088 ISD::EXTRACT_VECTOR_ELT, Dl, MVT::i32, DAG.getBitcast(MVT::v4i32, Op),
11089 DAG.getVectorIdxConstant(Subtarget.isLittleEndian() ? 3 : 0, Dl));
11090 QuietMask = 0x8000;
11091 } else if (VT == MVT::f64) {
11092 if (Subtarget.isPPC64()) {
11093 HighWord = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32,
11094 DAG.getBitcast(MVT::i64, Op),
11095 DAG.getConstant(1, Dl, MVT::i32));
11096 } else {
11097 SDValue Vec = DAG.getBitcast(
11098 MVT::v4i32, DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v2f64, Op));
11099 HighWord = DAG.getNode(
11100 ISD::EXTRACT_VECTOR_ELT, Dl, MVT::i32, Vec,
11101 DAG.getVectorIdxConstant(Subtarget.isLittleEndian() ? 1 : 0, Dl));
11102 }
11103 QuietMask = 0x80000;
11104 } else if (VT == MVT::f32) {
11105 HighWord = DAG.getBitcast(MVT::i32, Op);
11106 QuietMask = 0x400000;
11107 }
11108 SDValue NanRes = DAG.getSetCC(
11109 Dl, MVT::i1,
11110 DAG.getNode(ISD::AND, Dl, MVT::i32, HighWord,
11111 DAG.getConstant(QuietMask, Dl, MVT::i32)),
11112 DAG.getConstant(0, Dl, MVT::i32), IsQuiet ? ISD::SETNE : ISD::SETEQ);
11113 NanRes = DAG.getNode(ISD::AND, Dl, MVT::i1, NanCheck, NanRes);
11114 if (Mask == fcQNan || Mask == fcSNan)
11115 return NanRes;
11116
11117 return DAG.getNode(ISD::OR, Dl, MVT::i1,
11118 getDataClassTest(Op, Mask & ~fcNan, Dl, DAG, Subtarget),
11119 NanRes);
11120 }
11121
11122 unsigned NativeMask = 0;
11123 if ((Mask & fcNan) == fcNan)
11124 NativeMask |= DC_NAN;
11125 if (Mask & fcNegInf)
11126 NativeMask |= DC_NEG_INF;
11127 if (Mask & fcPosInf)
11128 NativeMask |= DC_POS_INF;
11129 if (Mask & fcNegZero)
11130 NativeMask |= DC_NEG_ZERO;
11131 if (Mask & fcPosZero)
11132 NativeMask |= DC_POS_ZERO;
11133 if (Mask & fcNegSubnormal)
11134 NativeMask |= DC_NEG_SUBNORM;
11135 if (Mask & fcPosSubnormal)
11136 NativeMask |= DC_POS_SUBNORM;
11137 return SDValue(
11138 DAG.getMachineNode(
11139 TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1,
11140 SDValue(DAG.getMachineNode(
11141 TestOp, Dl, MVT::i32,
11142 DAG.getTargetConstant(NativeMask, Dl, MVT::i32), Op),
11143 0),
11144 DAG.getTargetConstant(PPC::sub_eq, Dl, MVT::i32)),
11145 0);
11146}
11147
11148SDValue PPCTargetLowering::LowerIS_FPCLASS(SDValue Op,
11149 SelectionDAG &DAG) const {
11150 assert(Subtarget.hasP9Vector() && "Test data class requires Power9")(static_cast <bool> (Subtarget.hasP9Vector() &&
"Test data class requires Power9") ? void (0) : __assert_fail
("Subtarget.hasP9Vector() && \"Test data class requires Power9\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11150, __extension__
__PRETTY_FUNCTION__))
;
11151 SDValue LHS = Op.getOperand(0);
11152 const auto *RHS = cast<ConstantSDNode>(Op.getOperand(1));
11153 SDLoc Dl(Op);
11154 FPClassTest Category = static_cast<FPClassTest>(RHS->getZExtValue());
11155 return getDataClassTest(LHS, Category, Dl, DAG, Subtarget);
11156}
11157
11158SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
11159 SelectionDAG &DAG) const {
11160 SDLoc dl(Op);
11161 // Create a stack slot that is 16-byte aligned.
11162 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11163 int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
11164 EVT PtrVT = getPointerTy(DAG.getDataLayout());
11165 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
11166
11167 // Store the input value into Value#0 of the stack slot.
11168 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
11169 MachinePointerInfo());
11170 // Load it out.
11171 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
11172}
11173
11174SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11175 SelectionDAG &DAG) const {
11176 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&(static_cast <bool> (Op.getOpcode() == ISD::INSERT_VECTOR_ELT
&& "Should only be called for ISD::INSERT_VECTOR_ELT"
) ? void (0) : __assert_fail ("Op.getOpcode() == ISD::INSERT_VECTOR_ELT && \"Should only be called for ISD::INSERT_VECTOR_ELT\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11177, __extension__
__PRETTY_FUNCTION__))
11177 "Should only be called for ISD::INSERT_VECTOR_ELT")(static_cast <bool> (Op.getOpcode() == ISD::INSERT_VECTOR_ELT
&& "Should only be called for ISD::INSERT_VECTOR_ELT"
) ? void (0) : __assert_fail ("Op.getOpcode() == ISD::INSERT_VECTOR_ELT && \"Should only be called for ISD::INSERT_VECTOR_ELT\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11177, __extension__
__PRETTY_FUNCTION__))
;
11178
11179 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
11180
11181 EVT VT = Op.getValueType();
11182 SDLoc dl(Op);
11183 SDValue V1 = Op.getOperand(0);
11184 SDValue V2 = Op.getOperand(1);
11185
11186 if (VT == MVT::v2f64 && C)
11187 return Op;
11188
11189 if (Subtarget.hasP9Vector()) {
11190 // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
11191 // because on P10, it allows this specific insert_vector_elt load pattern to
11192 // utilize the refactored load and store infrastructure in order to exploit
11193 // prefixed loads.
11194 // On targets with inexpensive direct moves (Power9 and up), a
11195 // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
11196 // load since a single precision load will involve conversion to double
11197 // precision on the load followed by another conversion to single precision.
11198 if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
11199 (isa<LoadSDNode>(V2))) {
11200 SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
11201 SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
11202 SDValue InsVecElt =
11203 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
11204 BitcastLoad, Op.getOperand(2));
11205 return DAG.getBitcast(MVT::v4f32, InsVecElt);
11206 }
11207 }
11208
11209 if (Subtarget.isISA3_1()) {
11210 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
11211 return SDValue();
11212 // On P10, we have legal lowering for constant and variable indices for
11213 // all vectors.
11214 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
11215 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
11216 return Op;
11217 }
11218
11219 // Before P10, we have legal lowering for constant indices but not for
11220 // variable ones.
11221 if (!C)
11222 return SDValue();
11223
11224 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
11225 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
11226 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
11227 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
11228 unsigned InsertAtElement = C->getZExtValue();
11229 unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
11230 if (Subtarget.isLittleEndian()) {
11231 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
11232 }
11233 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
11234 DAG.getConstant(InsertAtByte, dl, MVT::i32));
11235 }
11236 return Op;
11237}
11238
11239SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
11240 SelectionDAG &DAG) const {
11241 SDLoc dl(Op);
11242 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
11243 SDValue LoadChain = LN->getChain();
11244 SDValue BasePtr = LN->getBasePtr();
11245 EVT VT = Op.getValueType();
11246
11247 if (VT != MVT::v256i1 && VT != MVT::v512i1)
11248 return Op;
11249
11250 // Type v256i1 is used for pairs and v512i1 is used for accumulators.
11251 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
11252 // 2 or 4 vsx registers.
11253 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&(static_cast <bool> ((VT != MVT::v512i1 || Subtarget.hasMMA
()) && "Type unsupported without MMA") ? void (0) : __assert_fail
("(VT != MVT::v512i1 || Subtarget.hasMMA()) && \"Type unsupported without MMA\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11254, __extension__
__PRETTY_FUNCTION__))
11254 "Type unsupported without MMA")(static_cast <bool> ((VT != MVT::v512i1 || Subtarget.hasMMA
()) && "Type unsupported without MMA") ? void (0) : __assert_fail
("(VT != MVT::v512i1 || Subtarget.hasMMA()) && \"Type unsupported without MMA\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11254, __extension__
__PRETTY_FUNCTION__))
;
11255 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&(static_cast <bool> ((VT != MVT::v256i1 || Subtarget.pairedVectorMemops
()) && "Type unsupported without paired vector support"
) ? void (0) : __assert_fail ("(VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && \"Type unsupported without paired vector support\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11256, __extension__
__PRETTY_FUNCTION__))
11256 "Type unsupported without paired vector support")(static_cast <bool> ((VT != MVT::v256i1 || Subtarget.pairedVectorMemops
()) && "Type unsupported without paired vector support"
) ? void (0) : __assert_fail ("(VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && \"Type unsupported without paired vector support\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11256, __extension__
__PRETTY_FUNCTION__))
;
11257 Align Alignment = LN->getAlign();
11258 SmallVector<SDValue, 4> Loads;
11259 SmallVector<SDValue, 4> LoadChains;
11260 unsigned NumVecs = VT.getSizeInBits() / 128;
11261 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
11262 SDValue Load =
11263 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
11264 LN->getPointerInfo().getWithOffset(Idx * 16),
11265 commonAlignment(Alignment, Idx * 16),
11266 LN->getMemOperand()->getFlags(), LN->getAAInfo());
11267 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11268 DAG.getConstant(16, dl, BasePtr.getValueType()));
11269 Loads.push_back(Load);
11270 LoadChains.push_back(Load.getValue(1));
11271 }
11272 if (Subtarget.isLittleEndian()) {
11273 std::reverse(Loads.begin(), Loads.end());
11274 std::reverse(LoadChains.begin(), LoadChains.end());
11275 }
11276 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
11277 SDValue Value =
11278 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
11279 dl, VT, Loads);
11280 SDValue RetOps[] = {Value, TF};
11281 return DAG.getMergeValues(RetOps, dl);
11282}
11283
11284SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
11285 SelectionDAG &DAG) const {
11286 SDLoc dl(Op);
11287 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
11288 SDValue StoreChain = SN->getChain();
11289 SDValue BasePtr = SN->getBasePtr();
11290 SDValue Value = SN->getValue();
11291 SDValue Value2 = SN->getValue();
11292 EVT StoreVT = Value.getValueType();
11293
11294 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
11295 return Op;
11296
11297 // Type v256i1 is used for pairs and v512i1 is used for accumulators.
11298 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
11299 // underlying registers individually.
11300 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&(static_cast <bool> ((StoreVT != MVT::v512i1 || Subtarget
.hasMMA()) && "Type unsupported without MMA") ? void (
0) : __assert_fail ("(StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && \"Type unsupported without MMA\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11301, __extension__
__PRETTY_FUNCTION__))
11301 "Type unsupported without MMA")(static_cast <bool> ((StoreVT != MVT::v512i1 || Subtarget
.hasMMA()) && "Type unsupported without MMA") ? void (
0) : __assert_fail ("(StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && \"Type unsupported without MMA\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11301, __extension__
__PRETTY_FUNCTION__))
;
11302 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&(static_cast <bool> ((StoreVT != MVT::v256i1 || Subtarget
.pairedVectorMemops()) && "Type unsupported without paired vector support"
) ? void (0) : __assert_fail ("(StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && \"Type unsupported without paired vector support\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11303, __extension__
__PRETTY_FUNCTION__))
11303 "Type unsupported without paired vector support")(static_cast <bool> ((StoreVT != MVT::v256i1 || Subtarget
.pairedVectorMemops()) && "Type unsupported without paired vector support"
) ? void (0) : __assert_fail ("(StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && \"Type unsupported without paired vector support\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11303, __extension__
__PRETTY_FUNCTION__))
;
11304 Align Alignment = SN->getAlign();
11305 SmallVector<SDValue, 4> Stores;
11306 unsigned NumVecs = 2;
11307 if (StoreVT == MVT::v512i1) {
11308 if (Subtarget.isISAFuture()) {
11309 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
11310 MachineSDNode *ExtNode = DAG.getMachineNode(
11311 PPC::DMXXEXTFDMR512, dl, ArrayRef(ReturnTypes, 2), Op.getOperand(1));
11312
11313 Value = SDValue(ExtNode, 0);
11314 Value2 = SDValue(ExtNode, 1);
11315 } else
11316 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
11317 NumVecs = 4;
11318 }
11319 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
11320 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
11321 SDValue Elt;
11322 if (Subtarget.isISAFuture()) {
11323 VecNum = Subtarget.isLittleEndian() ? 1 - (Idx % 2) : (Idx % 2);
11324 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11325 Idx > 1 ? Value2 : Value,
11326 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
11327 } else
11328 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
11329 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
11330
11331 SDValue Store =
11332 DAG.getStore(StoreChain, dl, Elt, BasePtr,
11333 SN->getPointerInfo().getWithOffset(Idx * 16),
11334 commonAlignment(Alignment, Idx * 16),
11335 SN->getMemOperand()->getFlags(), SN->getAAInfo());
11336 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11337 DAG.getConstant(16, dl, BasePtr.getValueType()));
11338 Stores.push_back(Store);
11339 }
11340 SDValue TF = DAG.getTokenFactor(dl, Stores);
11341 return TF;
11342}
11343
11344SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
11345 SDLoc dl(Op);
11346 if (Op.getValueType() == MVT::v4i32) {
11347 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
11348
11349 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
11350 // +16 as shift amt.
11351 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
11352 SDValue RHSSwap = // = vrlw RHS, 16
11353 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
11354
11355 // Shrinkify inputs to v8i16.
11356 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
11357 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
11358 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
11359
11360 // Low parts multiplied together, generating 32-bit results (we ignore the
11361 // top parts).
11362 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
11363 LHS, RHS, DAG, dl, MVT::v4i32);
11364
11365 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
11366 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
11367 // Shift the high parts up 16 bits.
11368 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
11369 Neg16, DAG, dl);
11370 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
11371 } else if (Op.getValueType() == MVT::v16i8) {
11372 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
11373 bool isLittleEndian = Subtarget.isLittleEndian();
11374
11375 // Multiply the even 8-bit parts, producing 16-bit sums.
11376 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
11377 LHS, RHS, DAG, dl, MVT::v8i16);
11378 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
11379
11380 // Multiply the odd 8-bit parts, producing 16-bit sums.
11381 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
11382 LHS, RHS, DAG, dl, MVT::v8i16);
11383 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
11384
11385 // Merge the results together. Because vmuleub and vmuloub are
11386 // instructions with a big-endian bias, we must reverse the
11387 // element numbering and reverse the meaning of "odd" and "even"
11388 // when generating little endian code.
11389 int Ops[16];
11390 for (unsigned i = 0; i != 8; ++i) {
11391 if (isLittleEndian) {
11392 Ops[i*2 ] = 2*i;
11393 Ops[i*2+1] = 2*i+16;
11394 } else {
11395 Ops[i*2 ] = 2*i+1;
11396 Ops[i*2+1] = 2*i+1+16;
11397 }
11398 }
11399 if (isLittleEndian)
11400 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
11401 else
11402 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
11403 } else {
11404 llvm_unreachable("Unknown mul to lower!")::llvm::llvm_unreachable_internal("Unknown mul to lower!", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 11404)
;
11405 }
11406}
11407
11408SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11409 bool IsStrict = Op->isStrictFPOpcode();
11410 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
11411 !Subtarget.hasP9Vector())
11412 return SDValue();
11413
11414 return Op;
11415}
11416
11417// Custom lowering for fpext vf32 to v2f64
11418SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11419
11420 assert(Op.getOpcode() == ISD::FP_EXTEND &&(static_cast <bool> (Op.getOpcode() == ISD::FP_EXTEND &&
"Should only be called for ISD::FP_EXTEND") ? void (0) : __assert_fail
("Op.getOpcode() == ISD::FP_EXTEND && \"Should only be called for ISD::FP_EXTEND\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11421, __extension__
__PRETTY_FUNCTION__))
11421 "Should only be called for ISD::FP_EXTEND")(static_cast <bool> (Op.getOpcode() == ISD::FP_EXTEND &&
"Should only be called for ISD::FP_EXTEND") ? void (0) : __assert_fail
("Op.getOpcode() == ISD::FP_EXTEND && \"Should only be called for ISD::FP_EXTEND\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11421, __extension__
__PRETTY_FUNCTION__))
;
11422
11423 // FIXME: handle extends from half precision float vectors on P9.
11424 // We only want to custom lower an extend from v2f32 to v2f64.
11425 if (Op.getValueType() != MVT::v2f64 ||
11426 Op.getOperand(0).getValueType() != MVT::v2f32)
11427 return SDValue();
11428
11429 SDLoc dl(Op);
11430 SDValue Op0 = Op.getOperand(0);
11431
11432 switch (Op0.getOpcode()) {
11433 default:
11434 return SDValue();
11435 case ISD::EXTRACT_SUBVECTOR: {
11436 assert(Op0.getNumOperands() == 2 &&(static_cast <bool> (Op0.getNumOperands() == 2 &&
isa<ConstantSDNode>(Op0->getOperand(1)) && "Node should have 2 operands with second one being a constant!"
) ? void (0) : __assert_fail ("Op0.getNumOperands() == 2 && isa<ConstantSDNode>(Op0->getOperand(1)) && \"Node should have 2 operands with second one being a constant!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11438, __extension__
__PRETTY_FUNCTION__))
11437 isa<ConstantSDNode>(Op0->getOperand(1)) &&(static_cast <bool> (Op0.getNumOperands() == 2 &&
isa<ConstantSDNode>(Op0->getOperand(1)) && "Node should have 2 operands with second one being a constant!"
) ? void (0) : __assert_fail ("Op0.getNumOperands() == 2 && isa<ConstantSDNode>(Op0->getOperand(1)) && \"Node should have 2 operands with second one being a constant!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11438, __extension__
__PRETTY_FUNCTION__))
11438 "Node should have 2 operands with second one being a constant!")(static_cast <bool> (Op0.getNumOperands() == 2 &&
isa<ConstantSDNode>(Op0->getOperand(1)) && "Node should have 2 operands with second one being a constant!"
) ? void (0) : __assert_fail ("Op0.getNumOperands() == 2 && isa<ConstantSDNode>(Op0->getOperand(1)) && \"Node should have 2 operands with second one being a constant!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11438, __extension__
__PRETTY_FUNCTION__))
;
11439
11440 if (Op0.getOperand(0).getValueType() != MVT::v4f32)
11441 return SDValue();
11442
11443 // Custom lower is only done for high or low doubleword.
11444 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
11445 if (Idx % 2 != 0)
11446 return SDValue();
11447
11448 // Since input is v4f32, at this point Idx is either 0 or 2.
11449 // Shift to get the doubleword position we want.
11450 int DWord = Idx >> 1;
11451
11452 // High and low word positions are different on little endian.
11453 if (Subtarget.isLittleEndian())
11454 DWord ^= 0x1;
11455
11456 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
11457 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
11458 }
11459 case ISD::FADD:
11460 case ISD::FMUL:
11461 case ISD::FSUB: {
11462 SDValue NewLoad[2];
11463 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11464 // Ensure both input are loads.
11465 SDValue LdOp = Op0.getOperand(i);
11466 if (LdOp.getOpcode() != ISD::LOAD)
11467 return SDValue();
11468 // Generate new load node.
11469 LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11470 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11471 NewLoad[i] = DAG.getMemIntrinsicNode(
11472 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11473 LD->getMemoryVT(), LD->getMemOperand());
11474 }
11475 SDValue NewOp =
11476 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11477 NewLoad[1], Op0.getNode()->getFlags());
11478 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11479 DAG.getConstant(0, dl, MVT::i32));
11480 }
11481 case ISD::LOAD: {
11482 LoadSDNode *LD = cast<LoadSDNode>(Op0);
11483 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11484 SDValue NewLd = DAG.getMemIntrinsicNode(
11485 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11486 LD->getMemoryVT(), LD->getMemOperand());
11487 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11488 DAG.getConstant(0, dl, MVT::i32));
11489 }
11490 }
11491 llvm_unreachable("ERROR:Should return for all cases within swtich.")::llvm::llvm_unreachable_internal("ERROR:Should return for all cases within swtich."
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11491)
;
11492}
11493
11494/// LowerOperation - Provide custom lowering hooks for some operations.
11495///
11496SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11497 switch (Op.getOpcode()) {
11498 default: llvm_unreachable("Wasn't expecting to be able to lower this!")::llvm::llvm_unreachable_internal("Wasn't expecting to be able to lower this!"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11498)
;
11499 case ISD::FPOW: return lowerPow(Op, DAG);
11500 case ISD::FSIN: return lowerSin(Op, DAG);
11501 case ISD::FCOS: return lowerCos(Op, DAG);
11502 case ISD::FLOG: return lowerLog(Op, DAG);
11503 case ISD::FLOG10: return lowerLog10(Op, DAG);
11504 case ISD::FEXP: return lowerExp(Op, DAG);
11505 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11506 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11507 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11508 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11509 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11510 case ISD::STRICT_FSETCC:
11511 case ISD::STRICT_FSETCCS:
11512 case ISD::SETCC: return LowerSETCC(Op, DAG);
11513 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11514 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11515
11516 case ISD::INLINEASM:
11517 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG);
11518 // Variable argument lowering.
11519 case ISD::VASTART: return LowerVASTART(Op, DAG);
11520 case ISD::VAARG: return LowerVAARG(Op, DAG);
11521 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
11522
11523 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG);
11524 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11525 case ISD::GET_DYNAMIC_AREA_OFFSET:
11526 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11527
11528 // Exception handling lowering.
11529 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG);
11530 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
11531 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
11532
11533 case ISD::LOAD: return LowerLOAD(Op, DAG);
11534 case ISD::STORE: return LowerSTORE(Op, DAG);
11535 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
11536 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
11537 case ISD::STRICT_FP_TO_UINT:
11538 case ISD::STRICT_FP_TO_SINT:
11539 case ISD::FP_TO_UINT:
11540 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11541 case ISD::STRICT_UINT_TO_FP:
11542 case ISD::STRICT_SINT_TO_FP:
11543 case ISD::UINT_TO_FP:
11544 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
11545 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
11546
11547 // Lower 64-bit shifts.
11548 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
11549 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
11550 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
11551
11552 case ISD::FSHL: return LowerFunnelShift(Op, DAG);
11553 case ISD::FSHR: return LowerFunnelShift(Op, DAG);
11554
11555 // Vector-related lowering.
11556 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11557 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11558 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11559 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11560 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11561 case ISD::MUL: return LowerMUL(Op, DAG);
11562 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
11563 case ISD::STRICT_FP_ROUND:
11564 case ISD::FP_ROUND:
11565 return LowerFP_ROUND(Op, DAG);
11566 case ISD::ROTL: return LowerROTL(Op, DAG);
11567
11568 // For counter-based loop handling.
11569 case ISD::INTRINSIC_W_CHAIN: return SDValue();
11570
11571 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11572
11573 // Frame & Return address.
11574 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11575 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11576
11577 case ISD::INTRINSIC_VOID:
11578 return LowerINTRINSIC_VOID(Op, DAG);
11579 case ISD::BSWAP:
11580 return LowerBSWAP(Op, DAG);
11581 case ISD::ATOMIC_CMP_SWAP:
11582 return LowerATOMIC_CMP_SWAP(Op, DAG);
11583 case ISD::ATOMIC_STORE:
11584 return LowerATOMIC_LOAD_STORE(Op, DAG);
11585 case ISD::IS_FPCLASS:
11586 return LowerIS_FPCLASS(Op, DAG);
11587 }
11588}
11589
11590void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11591 SmallVectorImpl<SDValue>&Results,
11592 SelectionDAG &DAG) const {
11593 SDLoc dl(N);
11594 switch (N->getOpcode()) {
11595 default:
11596 llvm_unreachable("Do not know how to custom type legalize this operation!")::llvm::llvm_unreachable_internal("Do not know how to custom type legalize this operation!"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11596)
;
11597 case ISD::ATOMIC_LOAD: {
11598 SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11599 Results.push_back(Res);
11600 Results.push_back(Res.getValue(1));
11601 break;
11602 }
11603 case ISD::READCYCLECOUNTER: {
11604 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11605 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11606
11607 Results.push_back(
11608 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11609 Results.push_back(RTB.getValue(2));
11610 break;
11611 }
11612 case ISD::INTRINSIC_W_CHAIN: {
11613 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11614 Intrinsic::loop_decrement)
11615 break;
11616
11617 assert(N->getValueType(0) == MVT::i1 &&(static_cast <bool> (N->getValueType(0) == MVT::i1 &&
"Unexpected result type for CTR decrement intrinsic") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::i1 && \"Unexpected result type for CTR decrement intrinsic\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11618, __extension__
__PRETTY_FUNCTION__))
11618 "Unexpected result type for CTR decrement intrinsic")(static_cast <bool> (N->getValueType(0) == MVT::i1 &&
"Unexpected result type for CTR decrement intrinsic") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::i1 && \"Unexpected result type for CTR decrement intrinsic\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11618, __extension__
__PRETTY_FUNCTION__))
;
11619 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11620 N->getValueType(0));
11621 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11622 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11623 N->getOperand(1));
11624
11625 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11626 Results.push_back(NewInt.getValue(1));
11627 break;
11628 }
11629 case ISD::INTRINSIC_WO_CHAIN: {
11630 switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
11631 case Intrinsic::ppc_pack_longdouble:
11632 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
11633 N->getOperand(2), N->getOperand(1)));
11634 break;
11635 case Intrinsic::ppc_maxfe:
11636 case Intrinsic::ppc_minfe:
11637 case Intrinsic::ppc_fnmsub:
11638 case Intrinsic::ppc_convert_f128_to_ppcf128:
11639 Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
11640 break;
11641 }
11642 break;
11643 }
11644 case ISD::VAARG: {
11645 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11646 return;
11647
11648 EVT VT = N->getValueType(0);
11649
11650 if (VT == MVT::i64) {
11651 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11652
11653 Results.push_back(NewNode);
11654 Results.push_back(NewNode.getValue(1));
11655 }
11656 return;
11657 }
11658 case ISD::STRICT_FP_TO_SINT:
11659 case ISD::STRICT_FP_TO_UINT:
11660 case ISD::FP_TO_SINT:
11661 case ISD::FP_TO_UINT: {
11662 // LowerFP_TO_INT() can only handle f32 and f64.
11663 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11664 MVT::ppcf128)
11665 return;
11666 SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
11667 Results.push_back(LoweredValue);
11668 if (N->isStrictFPOpcode())
11669 Results.push_back(LoweredValue.getValue(1));
11670 return;
11671 }
11672 case ISD::TRUNCATE: {
11673 if (!N->getValueType(0).isVector())
11674 return;
11675 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11676 if (Lowered)
11677 Results.push_back(Lowered);
11678 return;
11679 }
11680 case ISD::FSHL:
11681 case ISD::FSHR:
11682 // Don't handle funnel shifts here.
11683 return;
11684 case ISD::BITCAST:
11685 // Don't handle bitcast here.
11686 return;
11687 case ISD::FP_EXTEND:
11688 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11689 if (Lowered)
11690 Results.push_back(Lowered);
11691 return;
11692 }
11693}
11694
11695//===----------------------------------------------------------------------===//
11696// Other Lowering Code
11697//===----------------------------------------------------------------------===//
11698
11699static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11700 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11701 Function *Func = Intrinsic::getDeclaration(M, Id);
11702 return Builder.CreateCall(Func, {});
11703}
11704
11705// The mappings for emitLeading/TrailingFence is taken from
11706// http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11707Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11708 Instruction *Inst,
11709 AtomicOrdering Ord) const {
11710 if (Ord == AtomicOrdering::SequentiallyConsistent)
11711 return callIntrinsic(Builder, Intrinsic::ppc_sync);
11712 if (isReleaseOrStronger(Ord))
11713 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11714 return nullptr;
11715}
11716
11717Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11718 Instruction *Inst,
11719 AtomicOrdering Ord) const {
11720 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11721 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11722 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11723 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11724 if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11725 return Builder.CreateCall(
11726 Intrinsic::getDeclaration(
11727 Builder.GetInsertBlock()->getParent()->getParent(),
11728 Intrinsic::ppc_cfence, {Inst->getType()}),
11729 {Inst});
11730 // FIXME: Can use isync for rmw operation.
11731 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11732 }
11733 return nullptr;
11734}
11735
11736MachineBasicBlock *
11737PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11738 unsigned AtomicSize,
11739 unsigned BinOpcode,
11740 unsigned CmpOpcode,
11741 unsigned CmpPred) const {
11742 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11743 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11744
11745 auto LoadMnemonic = PPC::LDARX;
11746 auto StoreMnemonic = PPC::STDCX;
11747 switch (AtomicSize) {
11748 default:
11749 llvm_unreachable("Unexpected size of atomic entity")::llvm::llvm_unreachable_internal("Unexpected size of atomic entity"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11749)
;
11750 case 1:
11751 LoadMnemonic = PPC::LBARX;
11752 StoreMnemonic = PPC::STBCX;
11753 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4")(static_cast <bool> (Subtarget.hasPartwordAtomics() &&
"Call this only with size >=4") ? void (0) : __assert_fail
("Subtarget.hasPartwordAtomics() && \"Call this only with size >=4\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11753, __extension__
__PRETTY_FUNCTION__))
;
11754 break;
11755 case 2:
11756 LoadMnemonic = PPC::LHARX;
11757 StoreMnemonic = PPC::STHCX;
11758 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4")(static_cast <bool> (Subtarget.hasPartwordAtomics() &&
"Call this only with size >=4") ? void (0) : __assert_fail
("Subtarget.hasPartwordAtomics() && \"Call this only with size >=4\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 11758, __extension__
__PRETTY_FUNCTION__))
;
11759 break;
11760 case 4:
11761 LoadMnemonic = PPC::LWARX;
11762 StoreMnemonic = PPC::STWCX;
11763 break;
11764 case 8:
11765 LoadMnemonic = PPC::LDARX;
11766 StoreMnemonic = PPC::STDCX;
11767 break;
11768 }
11769
11770 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11771 MachineFunction *F = BB->getParent();
11772 MachineFunction::iterator It = ++BB->getIterator();
11773
11774 Register dest = MI.getOperand(0).getReg();
11775 Register ptrA = MI.getOperand(1).getReg();
11776 Register ptrB = MI.getOperand(2).getReg();
11777 Register incr = MI.getOperand(3).getReg();
11778 DebugLoc dl = MI.getDebugLoc();
11779
11780 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11781 MachineBasicBlock *loop2MBB =
11782 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11783 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11784 F->insert(It, loopMBB);
11785 if (CmpOpcode)
11786 F->insert(It, loop2MBB);
11787 F->insert(It, exitMBB);
11788 exitMBB->splice(exitMBB->begin(), BB,
11789 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11790 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11791
11792 MachineRegisterInfo &RegInfo = F->getRegInfo();
11793 Register TmpReg = (!BinOpcode) ? incr :
11794 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11795 : &PPC::GPRCRegClass);
11796
11797 // thisMBB:
11798 // ...
11799 // fallthrough --> loopMBB
11800 BB->addSuccessor(loopMBB);
11801
11802 // loopMBB:
11803 // l[wd]arx dest, ptr
11804 // add r0, dest, incr
11805 // st[wd]cx. r0, ptr
11806 // bne- loopMBB
11807 // fallthrough --> exitMBB
11808
11809 // For max/min...
11810 // loopMBB:
11811 // l[wd]arx dest, ptr
11812 // cmpl?[wd] dest, incr
11813 // bgt exitMBB
11814 // loop2MBB:
11815 // st[wd]cx. dest, ptr
11816 // bne- loopMBB
11817 // fallthrough --> exitMBB
11818
11819 BB = loopMBB;
11820 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11821 .addReg(ptrA).addReg(ptrB);
11822 if (BinOpcode)
11823 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11824 if (CmpOpcode) {
11825 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11826 // Signed comparisons of byte or halfword values must be sign-extended.
11827 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11828 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11829 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11830 ExtReg).addReg(dest);
11831 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ExtReg).addReg(incr);
11832 } else
11833 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(dest).addReg(incr);
11834
11835 BuildMI(BB, dl, TII->get(PPC::BCC))
11836 .addImm(CmpPred)
11837 .addReg(CrReg)
11838 .addMBB(exitMBB);
11839 BB->addSuccessor(loop2MBB);
11840 BB->addSuccessor(exitMBB);
11841 BB = loop2MBB;
11842 }
11843 BuildMI(BB, dl, TII->get(StoreMnemonic))
11844 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11845 BuildMI(BB, dl, TII->get(PPC::BCC))
11846 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11847 BB->addSuccessor(loopMBB);
11848 BB->addSuccessor(exitMBB);
11849
11850 // exitMBB:
11851 // ...
11852 BB = exitMBB;
11853 return BB;
11854}
11855
11856static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11857 switch(MI.getOpcode()) {
11858 default:
11859 return false;
11860 case PPC::COPY:
11861 return TII->isSignExtended(MI.getOperand(1).getReg(),
11862 &MI.getMF()->getRegInfo());
11863 case PPC::LHA:
11864 case PPC::LHA8:
11865 case PPC::LHAU:
11866 case PPC::LHAU8:
11867 case PPC::LHAUX:
11868 case PPC::LHAUX8:
11869 case PPC::LHAX:
11870 case PPC::LHAX8:
11871 case PPC::LWA:
11872 case PPC::LWAUX:
11873 case PPC::LWAX:
11874 case PPC::LWAX_32:
11875 case PPC::LWA_32:
11876 case PPC::PLHA:
11877 case PPC::PLHA8:
11878 case PPC::PLHA8pc:
11879 case PPC::PLHApc:
11880 case PPC::PLWA:
11881 case PPC::PLWA8:
11882 case PPC::PLWA8pc:
11883 case PPC::PLWApc:
11884 case PPC::EXTSB:
11885 case PPC::EXTSB8:
11886 case PPC::EXTSB8_32_64:
11887 case PPC::EXTSB8_rec:
11888 case PPC::EXTSB_rec:
11889 case PPC::EXTSH:
11890 case PPC::EXTSH8:
11891 case PPC::EXTSH8_32_64:
11892 case PPC::EXTSH8_rec:
11893 case PPC::EXTSH_rec:
11894 case PPC::EXTSW:
11895 case PPC::EXTSWSLI:
11896 case PPC::EXTSWSLI_32_64:
11897 case PPC::EXTSWSLI_32_64_rec:
11898 case PPC::EXTSWSLI_rec:
11899 case PPC::EXTSW_32:
11900 case PPC::EXTSW_32_64:
11901 case PPC::EXTSW_32_64_rec:
11902 case PPC::EXTSW_rec:
11903 case PPC::SRAW:
11904 case PPC::SRAWI:
11905 case PPC::SRAWI_rec:
11906 case PPC::SRAW_rec:
11907 return true;
11908 }
11909 return false;
11910}
11911
11912MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11913 MachineInstr &MI, MachineBasicBlock *BB,
11914 bool is8bit, // operation
11915 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11916 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11917 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11918
11919 // If this is a signed comparison and the value being compared is not known
11920 // to be sign extended, sign extend it here.
11921 DebugLoc dl = MI.getDebugLoc();
11922 MachineFunction *F = BB->getParent();
11923 MachineRegisterInfo &RegInfo = F->getRegInfo();
11924 Register incr = MI.getOperand(3).getReg();
11925 bool IsSignExtended =
11926 incr.isVirtual() && isSignExtended(*RegInfo.getVRegDef(incr), TII);
11927
11928 if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11929 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11930 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11931 .addReg(MI.getOperand(3).getReg());
11932 MI.getOperand(3).setReg(ValueReg);
11933 incr = ValueReg;
11934 }
11935 // If we support part-word atomic mnemonics, just use them
11936 if (Subtarget.hasPartwordAtomics())
11937 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11938 CmpPred);
11939
11940 // In 64 bit mode we have to use 64 bits for addresses, even though the
11941 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
11942 // registers without caring whether they're 32 or 64, but here we're
11943 // doing actual arithmetic on the addresses.
11944 bool is64bit = Subtarget.isPPC64();
11945 bool isLittleEndian = Subtarget.isLittleEndian();
11946 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11947
11948 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11949 MachineFunction::iterator It = ++BB->getIterator();
11950
11951 Register dest = MI.getOperand(0).getReg();
11952 Register ptrA = MI.getOperand(1).getReg();
11953 Register ptrB = MI.getOperand(2).getReg();
11954
11955 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11956 MachineBasicBlock *loop2MBB =
11957 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11958 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11959 F->insert(It, loopMBB);
11960 if (CmpOpcode)
11961 F->insert(It, loop2MBB);
11962 F->insert(It, exitMBB);
11963 exitMBB->splice(exitMBB->begin(), BB,
11964 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11965 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11966
11967 const TargetRegisterClass *RC =
11968 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11969 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11970
11971 Register PtrReg = RegInfo.createVirtualRegister(RC);
11972 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11973 Register ShiftReg =
11974 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11975 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11976 Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11977 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11978 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11979 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11980 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11981 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11982 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11983 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11984 Register Ptr1Reg;
11985 Register TmpReg =
11986 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11987
11988 // thisMBB:
11989 // ...
11990 // fallthrough --> loopMBB
11991 BB->addSuccessor(loopMBB);
11992
11993 // The 4-byte load must be aligned, while a char or short may be
11994 // anywhere in the word. Hence all this nasty bookkeeping code.
11995 // add ptr1, ptrA, ptrB [copy if ptrA==0]
11996 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11997 // xori shift, shift1, 24 [16]
11998 // rlwinm ptr, ptr1, 0, 0, 29
11999 // slw incr2, incr, shift
12000 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12001 // slw mask, mask2, shift
12002 // loopMBB:
12003 // lwarx tmpDest, ptr
12004 // add tmp, tmpDest, incr2
12005 // andc tmp2, tmpDest, mask
12006 // and tmp3, tmp, mask
12007 // or tmp4, tmp3, tmp2
12008 // stwcx. tmp4, ptr
12009 // bne- loopMBB
12010 // fallthrough --> exitMBB
12011 // srw SrwDest, tmpDest, shift
12012 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31
12013 if (ptrA != ZeroReg) {
12014 Ptr1Reg = RegInfo.createVirtualRegister(RC);
12015 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12016 .addReg(ptrA)
12017 .addReg(ptrB);
12018 } else {
12019 Ptr1Reg = ptrB;
12020 }
12021 // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12022 // mode.
12023 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12024 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12025 .addImm(3)
12026 .addImm(27)
12027 .addImm(is8bit ? 28 : 27);
12028 if (!isLittleEndian)
12029 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12030 .addReg(Shift1Reg)
12031 .addImm(is8bit ? 24 : 16);
12032 if (is64bit)
12033 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12034 .addReg(Ptr1Reg)
12035 .addImm(0)
12036 .addImm(61);
12037 else
12038 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12039 .addReg(Ptr1Reg)
12040 .addImm(0)
12041 .addImm(0)
12042 .addImm(29);
12043 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
12044 if (is8bit)
12045 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12046 else {
12047 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12048 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12049 .addReg(Mask3Reg)
12050 .addImm(65535);
12051 }
12052 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12053 .addReg(Mask2Reg)
12054 .addReg(ShiftReg);
12055
12056 BB = loopMBB;
12057 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12058 .addReg(ZeroReg)
12059 .addReg(PtrReg);
12060 if (BinOpcode)
12061 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
12062 .addReg(Incr2Reg)
12063 .addReg(TmpDestReg);
12064 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12065 .addReg(TmpDestReg)
12066 .addReg(MaskReg);
12067 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
12068 if (CmpOpcode) {
12069 // For unsigned comparisons, we can directly compare the shifted values.
12070 // For signed comparisons we shift and sign extend.
12071 Register SReg = RegInfo.createVirtualRegister(GPRC);
12072 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12073 BuildMI(BB, dl, TII->get(PPC::AND), SReg)
12074 .addReg(TmpDestReg)
12075 .addReg(MaskReg);
12076 unsigned ValueReg = SReg;
12077 unsigned CmpReg = Incr2Reg;
12078 if (CmpOpcode == PPC::CMPW) {
12079 ValueReg = RegInfo.createVirtualRegister(GPRC);
12080 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
12081 .addReg(SReg)
12082 .addReg(ShiftReg);
12083 Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
12084 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
12085 .addReg(ValueReg);
12086 ValueReg = ValueSReg;
12087 CmpReg = incr;
12088 }
12089 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ValueReg).addReg(CmpReg);
12090 BuildMI(BB, dl, TII->get(PPC::BCC))
12091 .addImm(CmpPred)
12092 .addReg(CrReg)
12093 .addMBB(exitMBB);
12094 BB->addSuccessor(loop2MBB);
12095 BB->addSuccessor(exitMBB);
12096 BB = loop2MBB;
12097 }
12098 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
12099 BuildMI(BB, dl, TII->get(PPC::STWCX))
12100 .addReg(Tmp4Reg)
12101 .addReg(ZeroReg)
12102 .addReg(PtrReg);
12103 BuildMI(BB, dl, TII->get(PPC::BCC))
12104 .addImm(PPC::PRED_NE)
12105 .addReg(PPC::CR0)
12106 .addMBB(loopMBB);
12107 BB->addSuccessor(loopMBB);
12108 BB->addSuccessor(exitMBB);
12109
12110 // exitMBB:
12111 // ...
12112 BB = exitMBB;
12113 // Since the shift amount is not a constant, we need to clear
12114 // the upper bits with a separate RLWINM.
12115 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
12116 .addReg(SrwDestReg)
12117 .addImm(0)
12118 .addImm(is8bit ? 24 : 16)
12119 .addImm(31);
12120 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
12121 .addReg(TmpDestReg)
12122 .addReg(ShiftReg);
12123 return BB;
12124}
12125
12126llvm::MachineBasicBlock *
12127PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
12128 MachineBasicBlock *MBB) const {
12129 DebugLoc DL = MI.getDebugLoc();
12130 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12131 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12132
12133 MachineFunction *MF = MBB->getParent();
12134 MachineRegisterInfo &MRI = MF->getRegInfo();
12135
12136 const BasicBlock *BB = MBB->getBasicBlock();
12137 MachineFunction::iterator I = ++MBB->getIterator();
12138
12139 Register DstReg = MI.getOperand(0).getReg();
12140 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12141 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!")(static_cast <bool> (TRI->isTypeLegalForClass(*RC, MVT
::i32) && "Invalid destination!") ? void (0) : __assert_fail
("TRI->isTypeLegalForClass(*RC, MVT::i32) && \"Invalid destination!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12141, __extension__
__PRETTY_FUNCTION__))
;
12142 Register mainDstReg = MRI.createVirtualRegister(RC);
12143 Register restoreDstReg = MRI.createVirtualRegister(RC);
12144
12145 MVT PVT = getPointerTy(MF->getDataLayout());
12146 assert((PVT == MVT::i64 || PVT == MVT::i32) &&(static_cast <bool> ((PVT == MVT::i64 || PVT == MVT::i32
) && "Invalid Pointer Size!") ? void (0) : __assert_fail
("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12147, __extension__
__PRETTY_FUNCTION__))
12147 "Invalid Pointer Size!")(static_cast <bool> ((PVT == MVT::i64 || PVT == MVT::i32
) && "Invalid Pointer Size!") ? void (0) : __assert_fail
("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12147, __extension__
__PRETTY_FUNCTION__))
;
12148 // For v = setjmp(buf), we generate
12149 //
12150 // thisMBB:
12151 // SjLjSetup mainMBB
12152 // bl mainMBB
12153 // v_restore = 1
12154 // b sinkMBB
12155 //
12156 // mainMBB:
12157 // buf[LabelOffset] = LR
12158 // v_main = 0
12159 //
12160 // sinkMBB:
12161 // v = phi(main, restore)
12162 //
12163
12164 MachineBasicBlock *thisMBB = MBB;
12165 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12166 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12167 MF->insert(I, mainMBB);
12168 MF->insert(I, sinkMBB);
12169
12170 MachineInstrBuilder MIB;
12171
12172 // Transfer the remainder of BB and its successor edges to sinkMBB.
12173 sinkMBB->splice(sinkMBB->begin(), MBB,
12174 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12175 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12176
12177 // Note that the structure of the jmp_buf used here is not compatible
12178 // with that used by libc, and is not designed to be. Specifically, it
12179 // stores only those 'reserved' registers that LLVM does not otherwise
12180 // understand how to spill. Also, by convention, by the time this
12181 // intrinsic is called, Clang has already stored the frame address in the
12182 // first slot of the buffer and stack address in the third. Following the
12183 // X86 target code, we'll store the jump address in the second slot. We also
12184 // need to save the TOC pointer (R2) to handle jumps between shared
12185 // libraries, and that will be stored in the fourth slot. The thread
12186 // identifier (R13) is not affected.
12187
12188 // thisMBB:
12189 const int64_t LabelOffset = 1 * PVT.getStoreSize();
12190 const int64_t TOCOffset = 3 * PVT.getStoreSize();
12191 const int64_t BPOffset = 4 * PVT.getStoreSize();
12192
12193 // Prepare IP either in reg.
12194 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
12195 Register LabelReg = MRI.createVirtualRegister(PtrRC);
12196 Register BufReg = MI.getOperand(1).getReg();
12197
12198 if (Subtarget.is64BitELFABI()) {
12199 setUsesTOCBasePtr(*MBB->getParent());
12200 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
12201 .addReg(PPC::X2)
12202 .addImm(TOCOffset)
12203 .addReg(BufReg)
12204 .cloneMemRefs(MI);
12205 }
12206
12207 // Naked functions never have a base pointer, and so we use r1. For all
12208 // other functions, this decision must be delayed until during PEI.
12209 unsigned BaseReg;
12210 if (MF->getFunction().hasFnAttribute(Attribute::Naked))
12211 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
12212 else
12213 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
12214
12215 MIB = BuildMI(*thisMBB, MI, DL,
12216 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
12217 .addReg(BaseReg)
12218 .addImm(BPOffset)
12219 .addReg(BufReg)
12220 .cloneMemRefs(MI);
12221
12222 // Setup
12223 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
12224 MIB.addRegMask(TRI->getNoPreservedMask());
12225
12226 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
12227
12228 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
12229 .addMBB(mainMBB);
12230 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
12231
12232 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
12233 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
12234
12235 // mainMBB:
12236 // mainDstReg = 0
12237 MIB =
12238 BuildMI(mainMBB, DL,
12239 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
12240
12241 // Store IP
12242 if (Subtarget.isPPC64()) {
12243 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
12244 .addReg(LabelReg)
12245 .addImm(LabelOffset)
12246 .addReg(BufReg);
12247 } else {
12248 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
12249 .addReg(LabelReg)
12250 .addImm(LabelOffset)
12251 .addReg(BufReg);
12252 }
12253 MIB.cloneMemRefs(MI);
12254
12255 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
12256 mainMBB->addSuccessor(sinkMBB);
12257
12258 // sinkMBB:
12259 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12260 TII->get(PPC::PHI), DstReg)
12261 .addReg(mainDstReg).addMBB(mainMBB)
12262 .addReg(restoreDstReg).addMBB(thisMBB);
12263
12264 MI.eraseFromParent();
12265 return sinkMBB;
12266}
12267
12268MachineBasicBlock *
12269PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
12270 MachineBasicBlock *MBB) const {
12271 DebugLoc DL = MI.getDebugLoc();
12272 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12273
12274 MachineFunction *MF = MBB->getParent();
12275 MachineRegisterInfo &MRI = MF->getRegInfo();
12276
12277 MVT PVT = getPointerTy(MF->getDataLayout());
12278 assert((PVT == MVT::i64 || PVT == MVT::i32) &&(static_cast <bool> ((PVT == MVT::i64 || PVT == MVT::i32
) && "Invalid Pointer Size!") ? void (0) : __assert_fail
("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12279, __extension__
__PRETTY_FUNCTION__))
12279 "Invalid Pointer Size!")(static_cast <bool> ((PVT == MVT::i64 || PVT == MVT::i32
) && "Invalid Pointer Size!") ? void (0) : __assert_fail
("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12279, __extension__
__PRETTY_FUNCTION__))
;
12280
12281 const TargetRegisterClass *RC =
12282 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12283 Register Tmp = MRI.createVirtualRegister(RC);
12284 // Since FP is only updated here but NOT referenced, it's treated as GPR.
12285 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
12286 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
12287 unsigned BP =
12288 (PVT == MVT::i64)
12289 ? PPC::X30
12290 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
12291 : PPC::R30);
12292
12293 MachineInstrBuilder MIB;
12294
12295 const int64_t LabelOffset = 1 * PVT.getStoreSize();
12296 const int64_t SPOffset = 2 * PVT.getStoreSize();
12297 const int64_t TOCOffset = 3 * PVT.getStoreSize();
12298 const int64_t BPOffset = 4 * PVT.getStoreSize();
12299
12300 Register BufReg = MI.getOperand(0).getReg();
12301
12302 // Reload FP (the jumped-to function may not have had a
12303 // frame pointer, and if so, then its r31 will be restored
12304 // as necessary).
12305 if (PVT == MVT::i64) {
12306 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
12307 .addImm(0)
12308 .addReg(BufReg);
12309 } else {
12310 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
12311 .addImm(0)
12312 .addReg(BufReg);
12313 }
12314 MIB.cloneMemRefs(MI);
12315
12316 // Reload IP
12317 if (PVT == MVT::i64) {
12318 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
12319 .addImm(LabelOffset)
12320 .addReg(BufReg);
12321 } else {
12322 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
12323 .addImm(LabelOffset)
12324 .addReg(BufReg);
12325 }
12326 MIB.cloneMemRefs(MI);
12327
12328 // Reload SP
12329 if (PVT == MVT::i64) {
12330 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
12331 .addImm(SPOffset)
12332 .addReg(BufReg);
12333 } else {
12334 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
12335 .addImm(SPOffset)
12336 .addReg(BufReg);
12337 }
12338 MIB.cloneMemRefs(MI);
12339
12340 // Reload BP
12341 if (PVT == MVT::i64) {
12342 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
12343 .addImm(BPOffset)
12344 .addReg(BufReg);
12345 } else {
12346 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
12347 .addImm(BPOffset)
12348 .addReg(BufReg);
12349 }
12350 MIB.cloneMemRefs(MI);
12351
12352 // Reload TOC
12353 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
12354 setUsesTOCBasePtr(*MBB->getParent());
12355 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
12356 .addImm(TOCOffset)
12357 .addReg(BufReg)
12358 .cloneMemRefs(MI);
12359 }
12360
12361 // Jump
12362 BuildMI(*MBB, MI, DL,
12363 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
12364 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
12365
12366 MI.eraseFromParent();
12367 return MBB;
12368}
12369
12370bool PPCTargetLowering::hasInlineStackProbe(const MachineFunction &MF) const {
12371 // If the function specifically requests inline stack probes, emit them.
12372 if (MF.getFunction().hasFnAttribute("probe-stack"))
12373 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
12374 "inline-asm";
12375 return false;
12376}
12377
12378unsigned PPCTargetLowering::getStackProbeSize(const MachineFunction &MF) const {
12379 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
12380 unsigned StackAlign = TFI->getStackAlignment();
12381 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&(static_cast <bool> (StackAlign >= 1 && isPowerOf2_32
(StackAlign) && "Unexpected stack alignment") ? void (
0) : __assert_fail ("StackAlign >= 1 && isPowerOf2_32(StackAlign) && \"Unexpected stack alignment\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12382, __extension__
__PRETTY_FUNCTION__))
12382 "Unexpected stack alignment")(static_cast <bool> (StackAlign >= 1 && isPowerOf2_32
(StackAlign) && "Unexpected stack alignment") ? void (
0) : __assert_fail ("StackAlign >= 1 && isPowerOf2_32(StackAlign) && \"Unexpected stack alignment\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12382, __extension__
__PRETTY_FUNCTION__))
;
12383 // The default stack probe size is 4096 if the function has no
12384 // stack-probe-size attribute.
12385 const Function &Fn = MF.getFunction();
12386 unsigned StackProbeSize =
12387 Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
12388 // Round down to the stack alignment.
12389 StackProbeSize &= ~(StackAlign - 1);
12390 return StackProbeSize ? StackProbeSize : StackAlign;
12391}
12392
12393// Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
12394// into three phases. In the first phase, it uses pseudo instruction
12395// PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
12396// FinalStackPtr. In the second phase, it generates a loop for probing blocks.
12397// At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
12398// MaxCallFrameSize so that it can calculate correct data area pointer.
12399MachineBasicBlock *
12400PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
12401 MachineBasicBlock *MBB) const {
12402 const bool isPPC64 = Subtarget.isPPC64();
12403 MachineFunction *MF = MBB->getParent();
12404 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12405 DebugLoc DL = MI.getDebugLoc();
12406 const unsigned ProbeSize = getStackProbeSize(*MF);
12407 const BasicBlock *ProbedBB = MBB->getBasicBlock();
12408 MachineRegisterInfo &MRI = MF->getRegInfo();
12409 // The CFG of probing stack looks as
12410 // +-----+
12411 // | MBB |
12412 // +--+--+
12413 // |
12414 // +----v----+
12415 // +--->+ TestMBB +---+
12416 // | +----+----+ |
12417 // | | |
12418 // | +-----v----+ |
12419 // +---+ BlockMBB | |
12420 // +----------+ |
12421 // |
12422 // +---------+ |
12423 // | TailMBB +<--+
12424 // +---------+
12425 // In MBB, calculate previous frame pointer and final stack pointer.
12426 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
12427 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
12428 // TailMBB is spliced via \p MI.
12429 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
12430 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
12431 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
12432
12433 MachineFunction::iterator MBBIter = ++MBB->getIterator();
12434 MF->insert(MBBIter, TestMBB);
12435 MF->insert(MBBIter, BlockMBB);
12436 MF->insert(MBBIter, TailMBB);
12437
12438 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
12439 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12440
12441 Register DstReg = MI.getOperand(0).getReg();
12442 Register NegSizeReg = MI.getOperand(1).getReg();
12443 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
12444 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12445 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12446 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12447
12448 // Since value of NegSizeReg might be realigned in prologepilog, insert a
12449 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
12450 // NegSize.
12451 unsigned ProbeOpc;
12452 if (!MRI.hasOneNonDBGUse(NegSizeReg))
12453 ProbeOpc =
12454 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
12455 else
12456 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
12457 // and NegSizeReg will be allocated in the same phyreg to avoid
12458 // redundant copy when NegSizeReg has only one use which is current MI and
12459 // will be replaced by PREPARE_PROBED_ALLOCA then.
12460 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
12461 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
12462 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
12463 .addDef(ActualNegSizeReg)
12464 .addReg(NegSizeReg)
12465 .add(MI.getOperand(2))
12466 .add(MI.getOperand(3));
12467
12468 // Calculate final stack pointer, which equals to SP + ActualNegSize.
12469 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
12470 FinalStackPtr)
12471 .addReg(SPReg)
12472 .addReg(ActualNegSizeReg);
12473
12474 // Materialize a scratch register for update.
12475 int64_t NegProbeSize = -(int64_t)ProbeSize;
12476 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!")(static_cast <bool> (isInt<32>(NegProbeSize) &&
"Unhandled probe size!") ? void (0) : __assert_fail ("isInt<32>(NegProbeSize) && \"Unhandled probe size!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12476, __extension__
__PRETTY_FUNCTION__))
;
12477 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12478 if (!isInt<16>(NegProbeSize)) {
12479 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12480 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
12481 .addImm(NegProbeSize >> 16);
12482 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
12483 ScratchReg)
12484 .addReg(TempReg)
12485 .addImm(NegProbeSize & 0xFFFF);
12486 } else
12487 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
12488 .addImm(NegProbeSize);
12489
12490 {
12491 // Probing leading residual part.
12492 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12493 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
12494 .addReg(ActualNegSizeReg)
12495 .addReg(ScratchReg);
12496 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12497 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
12498 .addReg(Div)
12499 .addReg(ScratchReg);
12500 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12501 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
12502 .addReg(Mul)
12503 .addReg(ActualNegSizeReg);
12504 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12505 .addReg(FramePointer)
12506 .addReg(SPReg)
12507 .addReg(NegMod);
12508 }
12509
12510 {
12511 // Remaining part should be multiple of ProbeSize.
12512 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
12513 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
12514 .addReg(SPReg)
12515 .addReg(FinalStackPtr);
12516 BuildMI(TestMBB, DL, TII->get(PPC::BCC))
12517 .addImm(PPC::PRED_EQ)
12518 .addReg(CmpResult)
12519 .addMBB(TailMBB);
12520 TestMBB->addSuccessor(BlockMBB);
12521 TestMBB->addSuccessor(TailMBB);
12522 }
12523
12524 {
12525 // Touch the block.
12526 // |P...|P...|P...
12527 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12528 .addReg(FramePointer)
12529 .addReg(SPReg)
12530 .addReg(ScratchReg);
12531 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
12532 BlockMBB->addSuccessor(TestMBB);
12533 }
12534
12535 // Calculation of MaxCallFrameSize is deferred to prologepilog, use
12536 // DYNAREAOFFSET pseudo instruction to get the future result.
12537 Register MaxCallFrameSizeReg =
12538 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12539 BuildMI(TailMBB, DL,
12540 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
12541 MaxCallFrameSizeReg)
12542 .add(MI.getOperand(2))
12543 .add(MI.getOperand(3));
12544 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
12545 .addReg(SPReg)
12546 .addReg(MaxCallFrameSizeReg);
12547
12548 // Splice instructions after MI to TailMBB.
12549 TailMBB->splice(TailMBB->end(), MBB,
12550 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12551 TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12552 MBB->addSuccessor(TestMBB);
12553
12554 // Delete the pseudo instruction.
12555 MI.eraseFromParent();
12556
12557 ++NumDynamicAllocaProbed;
12558 return TailMBB;
12559}
12560
12561MachineBasicBlock *
12562PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12563 MachineBasicBlock *BB) const {
12564 if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12565 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12566 if (Subtarget.is64BitELFABI() &&
12567 MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12568 !Subtarget.isUsingPCRelativeCalls()) {
12569 // Call lowering should have added an r2 operand to indicate a dependence
12570 // on the TOC base pointer value. It can't however, because there is no
12571 // way to mark the dependence as implicit there, and so the stackmap code
12572 // will confuse it with a regular operand. Instead, add the dependence
12573 // here.
12574 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12575 }
12576
12577 return emitPatchPoint(MI, BB);
12578 }
12579
12580 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12581 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12582 return emitEHSjLjSetJmp(MI, BB);
12583 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12584 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12585 return emitEHSjLjLongJmp(MI, BB);
12586 }
12587
12588 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12589
12590 // To "insert" these instructions we actually have to insert their
12591 // control-flow patterns.
12592 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12593 MachineFunction::iterator It = ++BB->getIterator();
12594
12595 MachineFunction *F = BB->getParent();
12596 MachineRegisterInfo &MRI = F->getRegInfo();
12597
12598 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12599 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12600 MI.getOpcode() == PPC::SELECT_I8) {
12601 SmallVector<MachineOperand, 2> Cond;
12602 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12603 MI.getOpcode() == PPC::SELECT_CC_I8)
12604 Cond.push_back(MI.getOperand(4));
12605 else
12606 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12607 Cond.push_back(MI.getOperand(1));
12608
12609 DebugLoc dl = MI.getDebugLoc();
12610 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12611 MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12612 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12613 MI.getOpcode() == PPC::SELECT_CC_F8 ||
12614 MI.getOpcode() == PPC::SELECT_CC_F16 ||
12615 MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12616 MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12617 MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12618 MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12619 MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12620 MI.getOpcode() == PPC::SELECT_CC_SPE ||
12621 MI.getOpcode() == PPC::SELECT_F4 ||
12622 MI.getOpcode() == PPC::SELECT_F8 ||
12623 MI.getOpcode() == PPC::SELECT_F16 ||
12624 MI.getOpcode() == PPC::SELECT_SPE ||
12625 MI.getOpcode() == PPC::SELECT_SPE4 ||
12626 MI.getOpcode() == PPC::SELECT_VRRC ||
12627 MI.getOpcode() == PPC::SELECT_VSFRC ||
12628 MI.getOpcode() == PPC::SELECT_VSSRC ||
12629 MI.getOpcode() == PPC::SELECT_VSRC) {
12630 // The incoming instruction knows the destination vreg to set, the
12631 // condition code register to branch on, the true/false values to
12632 // select between, and a branch opcode to use.
12633
12634 // thisMBB:
12635 // ...
12636 // TrueVal = ...
12637 // cmpTY ccX, r1, r2
12638 // bCC copy1MBB
12639 // fallthrough --> copy0MBB
12640 MachineBasicBlock *thisMBB = BB;
12641 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12642 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12643 DebugLoc dl = MI.getDebugLoc();
12644 F->insert(It, copy0MBB);
12645 F->insert(It, sinkMBB);
12646
12647 // Transfer the remainder of BB and its successor edges to sinkMBB.
12648 sinkMBB->splice(sinkMBB->begin(), BB,
12649 std::next(MachineBasicBlock::iterator(MI)), BB->end());
12650 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12651
12652 // Next, add the true and fallthrough blocks as its successors.
12653 BB->addSuccessor(copy0MBB);
12654 BB->addSuccessor(sinkMBB);
12655
12656 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12657 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12658 MI.getOpcode() == PPC::SELECT_F16 ||
12659 MI.getOpcode() == PPC::SELECT_SPE4 ||
12660 MI.getOpcode() == PPC::SELECT_SPE ||
12661 MI.getOpcode() == PPC::SELECT_VRRC ||
12662 MI.getOpcode() == PPC::SELECT_VSFRC ||
12663 MI.getOpcode() == PPC::SELECT_VSSRC ||
12664 MI.getOpcode() == PPC::SELECT_VSRC) {
12665 BuildMI(BB, dl, TII->get(PPC::BC))
12666 .addReg(MI.getOperand(1).getReg())
12667 .addMBB(sinkMBB);
12668 } else {
12669 unsigned SelectPred = MI.getOperand(4).getImm();
12670 BuildMI(BB, dl, TII->get(PPC::BCC))
12671 .addImm(SelectPred)
12672 .addReg(MI.getOperand(1).getReg())
12673 .addMBB(sinkMBB);
12674 }
12675
12676 // copy0MBB:
12677 // %FalseValue = ...
12678 // # fallthrough to sinkMBB
12679 BB = copy0MBB;
12680
12681 // Update machine-CFG edges
12682 BB->addSuccessor(sinkMBB);
12683
12684 // sinkMBB:
12685 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12686 // ...
12687 BB = sinkMBB;
12688 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12689 .addReg(MI.getOperand(3).getReg())
12690 .addMBB(copy0MBB)
12691 .addReg(MI.getOperand(2).getReg())
12692 .addMBB(thisMBB);
12693 } else if (MI.getOpcode() == PPC::ReadTB) {
12694 // To read the 64-bit time-base register on a 32-bit target, we read the
12695 // two halves. Should the counter have wrapped while it was being read, we
12696 // need to try again.
12697 // ...
12698 // readLoop:
12699 // mfspr Rx,TBU # load from TBU
12700 // mfspr Ry,TB # load from TB
12701 // mfspr Rz,TBU # load from TBU
12702 // cmpw crX,Rx,Rz # check if 'old'='new'
12703 // bne readLoop # branch if they're not equal
12704 // ...
12705
12706 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12707 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12708 DebugLoc dl = MI.getDebugLoc();
12709 F->insert(It, readMBB);
12710 F->insert(It, sinkMBB);
12711
12712 // Transfer the remainder of BB and its successor edges to sinkMBB.
12713 sinkMBB->splice(sinkMBB->begin(), BB,
12714 std::next(MachineBasicBlock::iterator(MI)), BB->end());
12715 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12716
12717 BB->addSuccessor(readMBB);
12718 BB = readMBB;
12719
12720 MachineRegisterInfo &RegInfo = F->getRegInfo();
12721 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12722 Register LoReg = MI.getOperand(0).getReg();
12723 Register HiReg = MI.getOperand(1).getReg();
12724
12725 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12726 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12727 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12728
12729 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12730
12731 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12732 .addReg(HiReg)
12733 .addReg(ReadAgainReg);
12734 BuildMI(BB, dl, TII->get(PPC::BCC))
12735 .addImm(PPC::PRED_NE)
12736 .addReg(CmpReg)
12737 .addMBB(readMBB);
12738
12739 BB->addSuccessor(readMBB);
12740 BB->addSuccessor(sinkMBB);
12741 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12742 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12743 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12744 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12745 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12746 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12747 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12748 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12749
12750 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12751 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12752 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12753 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12754 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12755 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12756 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12757 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12758
12759 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12760 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12761 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12762 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12763 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12764 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12765 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12766 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12767
12768 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12769 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12770 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12771 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12772 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12773 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12774 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12775 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12776
12777 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12778 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12779 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12780 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12781 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12782 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12783 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12784 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12785
12786 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12787 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12788 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12789 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12790 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12791 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12792 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12793 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12794
12795 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12796 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LT);
12797 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12798 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LT);
12799 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12800 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LT);
12801 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12802 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LT);
12803
12804 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12805 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GT);
12806 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12807 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GT);
12808 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12809 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GT);
12810 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12811 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GT);
12812
12813 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12814 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LT);
12815 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12816 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LT);
12817 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12818 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LT);
12819 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12820 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LT);
12821
12822 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12823 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GT);
12824 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12825 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GT);
12826 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12827 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GT);
12828 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12829 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GT);
12830
12831 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12832 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12833 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12834 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12835 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12836 BB = EmitAtomicBinary(MI, BB, 4, 0);
12837 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12838 BB = EmitAtomicBinary(MI, BB, 8, 0);
12839 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12840 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12841 (Subtarget.hasPartwordAtomics() &&
12842 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12843 (Subtarget.hasPartwordAtomics() &&
12844 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12845 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12846
12847 auto LoadMnemonic = PPC::LDARX;
12848 auto StoreMnemonic = PPC::STDCX;
12849 switch (MI.getOpcode()) {
12850 default:
12851 llvm_unreachable("Compare and swap of unknown size")::llvm::llvm_unreachable_internal("Compare and swap of unknown size"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12851)
;
12852 case PPC::ATOMIC_CMP_SWAP_I8:
12853 LoadMnemonic = PPC::LBARX;
12854 StoreMnemonic = PPC::STBCX;
12855 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.")(static_cast <bool> (Subtarget.hasPartwordAtomics() &&
"No support partword atomics.") ? void (0) : __assert_fail (
"Subtarget.hasPartwordAtomics() && \"No support partword atomics.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12855, __extension__
__PRETTY_FUNCTION__))
;
12856 break;
12857 case PPC::ATOMIC_CMP_SWAP_I16:
12858 LoadMnemonic = PPC::LHARX;
12859 StoreMnemonic = PPC::STHCX;
12860 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.")(static_cast <bool> (Subtarget.hasPartwordAtomics() &&
"No support partword atomics.") ? void (0) : __assert_fail (
"Subtarget.hasPartwordAtomics() && \"No support partword atomics.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 12860, __extension__
__PRETTY_FUNCTION__))
;
12861 break;
12862 case PPC::ATOMIC_CMP_SWAP_I32:
12863 LoadMnemonic = PPC::LWARX;
12864 StoreMnemonic = PPC::STWCX;
12865 break;
12866 case PPC::ATOMIC_CMP_SWAP_I64:
12867 LoadMnemonic = PPC::LDARX;
12868 StoreMnemonic = PPC::STDCX;
12869 break;
12870 }
12871 MachineRegisterInfo &RegInfo = F->getRegInfo();
12872 Register dest = MI.getOperand(0).getReg();
12873 Register ptrA = MI.getOperand(1).getReg();
12874 Register ptrB = MI.getOperand(2).getReg();
12875 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12876 Register oldval = MI.getOperand(3).getReg();
12877 Register newval = MI.getOperand(4).getReg();
12878 DebugLoc dl = MI.getDebugLoc();
12879
12880 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12881 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12882 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12883 F->insert(It, loop1MBB);
12884 F->insert(It, loop2MBB);
12885 F->insert(It, exitMBB);
12886 exitMBB->splice(exitMBB->begin(), BB,
12887 std::next(MachineBasicBlock::iterator(MI)), BB->end());
12888 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12889
12890 // thisMBB:
12891 // ...
12892 // fallthrough --> loopMBB
12893 BB->addSuccessor(loop1MBB);
12894
12895 // loop1MBB:
12896 // l[bhwd]arx dest, ptr
12897 // cmp[wd] dest, oldval
12898 // bne- exitBB
12899 // loop2MBB:
12900 // st[bhwd]cx. newval, ptr
12901 // bne- loopMBB
12902 // b exitBB
12903 // exitBB:
12904 BB = loop1MBB;
12905 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12906 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), CrReg)
12907 .addReg(dest)
12908 .addReg(oldval);
12909 BuildMI(BB, dl, TII->get(PPC::BCC))
12910 .addImm(PPC::PRED_NE)
12911 .addReg(CrReg)
12912 .addMBB(exitMBB);
12913 BB->addSuccessor(loop2MBB);
12914 BB->addSuccessor(exitMBB);
12915
12916 BB = loop2MBB;
12917 BuildMI(BB, dl, TII->get(StoreMnemonic))
12918 .addReg(newval)
12919 .addReg(ptrA)
12920 .addReg(ptrB);
12921 BuildMI(BB, dl, TII->get(PPC::BCC))
12922 .addImm(PPC::PRED_NE)
12923 .addReg(PPC::CR0)
12924 .addMBB(loop1MBB);
12925 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12926 BB->addSuccessor(loop1MBB);
12927 BB->addSuccessor(exitMBB);
12928
12929 // exitMBB:
12930 // ...
12931 BB = exitMBB;
12932 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12933 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12934 // We must use 64-bit registers for addresses when targeting 64-bit,
12935 // since we're actually doing arithmetic on them. Other registers
12936 // can be 32-bit.
12937 bool is64bit = Subtarget.isPPC64();
12938 bool isLittleEndian = Subtarget.isLittleEndian();
12939 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12940
12941 Register dest = MI.getOperand(0).getReg();
12942 Register ptrA = MI.getOperand(1).getReg();
12943 Register ptrB = MI.getOperand(2).getReg();
12944 Register oldval = MI.getOperand(3).getReg();
12945 Register newval = MI.getOperand(4).getReg();
12946 DebugLoc dl = MI.getDebugLoc();
12947
12948 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12949 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12950 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12951 F->insert(It, loop1MBB);
12952 F->insert(It, loop2MBB);
12953 F->insert(It, exitMBB);
12954 exitMBB->splice(exitMBB->begin(), BB,
12955 std::next(MachineBasicBlock::iterator(MI)), BB->end());
12956 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12957
12958 MachineRegisterInfo &RegInfo = F->getRegInfo();
12959 const TargetRegisterClass *RC =
12960 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12961 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12962
12963 Register PtrReg = RegInfo.createVirtualRegister(RC);
12964 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12965 Register ShiftReg =
12966 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12967 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12968 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12969 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12970 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12971 Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12972 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12973 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12974 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12975 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12976 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12977 Register Ptr1Reg;
12978 Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12979 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12980 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12981 // thisMBB:
12982 // ...
12983 // fallthrough --> loopMBB
12984 BB->addSuccessor(loop1MBB);
12985
12986 // The 4-byte load must be aligned, while a char or short may be
12987 // anywhere in the word. Hence all this nasty bookkeeping code.
12988 // add ptr1, ptrA, ptrB [copy if ptrA==0]
12989 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12990 // xori shift, shift1, 24 [16]
12991 // rlwinm ptr, ptr1, 0, 0, 29
12992 // slw newval2, newval, shift
12993 // slw oldval2, oldval,shift
12994 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12995 // slw mask, mask2, shift
12996 // and newval3, newval2, mask
12997 // and oldval3, oldval2, mask
12998 // loop1MBB:
12999 // lwarx tmpDest, ptr
13000 // and tmp, tmpDest, mask
13001 // cmpw tmp, oldval3
13002 // bne- exitBB
13003 // loop2MBB:
13004 // andc tmp2, tmpDest, mask
13005 // or tmp4, tmp2, newval3
13006 // stwcx. tmp4, ptr
13007 // bne- loop1MBB
13008 // b exitBB
13009 // exitBB:
13010 // srw dest, tmpDest, shift
13011 if (ptrA != ZeroReg) {
13012 Ptr1Reg = RegInfo.createVirtualRegister(RC);
13013 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
13014 .addReg(ptrA)
13015 .addReg(ptrB);
13016 } else {
13017 Ptr1Reg = ptrB;
13018 }
13019
13020 // We need use 32-bit subregister to avoid mismatch register class in 64-bit
13021 // mode.
13022 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
13023 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
13024 .addImm(3)
13025 .addImm(27)
13026 .addImm(is8bit ? 28 : 27);
13027 if (!isLittleEndian)
13028 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
13029 .addReg(Shift1Reg)
13030 .addImm(is8bit ? 24 : 16);
13031 if (is64bit)
13032 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
13033 .addReg(Ptr1Reg)
13034 .addImm(0)
13035 .addImm(61);
13036 else
13037 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
13038 .addReg(Ptr1Reg)
13039 .addImm(0)
13040 .addImm(0)
13041 .addImm(29);
13042 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
13043 .addReg(newval)
13044 .addReg(ShiftReg);
13045 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
13046 .addReg(oldval)
13047 .addReg(ShiftReg);
13048 if (is8bit)
13049 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
13050 else {
13051 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
13052 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
13053 .addReg(Mask3Reg)
13054 .addImm(65535);
13055 }
13056 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
13057 .addReg(Mask2Reg)
13058 .addReg(ShiftReg);
13059 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
13060 .addReg(NewVal2Reg)
13061 .addReg(MaskReg);
13062 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
13063 .addReg(OldVal2Reg)
13064 .addReg(MaskReg);
13065
13066 BB = loop1MBB;
13067 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
13068 .addReg(ZeroReg)
13069 .addReg(PtrReg);
13070 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
13071 .addReg(TmpDestReg)
13072 .addReg(MaskReg);
13073 BuildMI(BB, dl, TII->get(PPC::CMPW), CrReg)
13074 .addReg(TmpReg)
13075 .addReg(OldVal3Reg);
13076 BuildMI(BB, dl, TII->get(PPC::BCC))
13077 .addImm(PPC::PRED_NE)
13078 .addReg(CrReg)
13079 .addMBB(exitMBB);
13080 BB->addSuccessor(loop2MBB);
13081 BB->addSuccessor(exitMBB);
13082
13083 BB = loop2MBB;
13084 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
13085 .addReg(TmpDestReg)
13086 .addReg(MaskReg);
13087 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
13088 .addReg(Tmp2Reg)
13089 .addReg(NewVal3Reg);
13090 BuildMI(BB, dl, TII->get(PPC::STWCX))
13091 .addReg(Tmp4Reg)
13092 .addReg(ZeroReg)
13093 .addReg(PtrReg);
13094 BuildMI(BB, dl, TII->get(PPC::BCC))
13095 .addImm(PPC::PRED_NE)
13096 .addReg(PPC::CR0)
13097 .addMBB(loop1MBB);
13098 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
13099 BB->addSuccessor(loop1MBB);
13100 BB->addSuccessor(exitMBB);
13101
13102 // exitMBB:
13103 // ...
13104 BB = exitMBB;
13105 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
13106 .addReg(TmpReg)
13107 .addReg(ShiftReg);
13108 } else if (MI.getOpcode() == PPC::FADDrtz) {
13109 // This pseudo performs an FADD with rounding mode temporarily forced
13110 // to round-to-zero. We emit this via custom inserter since the FPSCR
13111 // is not modeled at the SelectionDAG level.
13112 Register Dest = MI.getOperand(0).getReg();
13113 Register Src1 = MI.getOperand(1).getReg();
13114 Register Src2 = MI.getOperand(2).getReg();
13115 DebugLoc dl = MI.getDebugLoc();
13116
13117 MachineRegisterInfo &RegInfo = F->getRegInfo();
13118 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
13119
13120 // Save FPSCR value.
13121 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
13122
13123 // Set rounding mode to round-to-zero.
13124 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
13125 .addImm(31)
13126 .addReg(PPC::RM, RegState::ImplicitDefine);
13127
13128 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
13129 .addImm(30)
13130 .addReg(PPC::RM, RegState::ImplicitDefine);
13131
13132 // Perform addition.
13133 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
13134 .addReg(Src1)
13135 .addReg(Src2);
13136 if (MI.getFlag(MachineInstr::NoFPExcept))
13137 MIB.setMIFlag(MachineInstr::NoFPExcept);
13138
13139 // Restore FPSCR value.
13140 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
13141 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
13142 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
13143 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
13144 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
13145 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
13146 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
13147 ? PPC::ANDI8_rec
13148 : PPC::ANDI_rec;
13149 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
13150 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
13151
13152 MachineRegisterInfo &RegInfo = F->getRegInfo();
13153 Register Dest = RegInfo.createVirtualRegister(
13154 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
13155
13156 DebugLoc Dl = MI.getDebugLoc();
13157 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
13158 .addReg(MI.getOperand(1).getReg())
13159 .addImm(1);
13160 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
13161 MI.getOperand(0).getReg())
13162 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
13163 } else if (MI.getOpcode() == PPC::TCHECK_RET) {
13164 DebugLoc Dl = MI.getDebugLoc();
13165 MachineRegisterInfo &RegInfo = F->getRegInfo();
13166 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
13167 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
13168 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
13169 MI.getOperand(0).getReg())
13170 .addReg(CRReg);
13171 } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
13172 DebugLoc Dl = MI.getDebugLoc();
13173 unsigned Imm = MI.getOperand(1).getImm();
13174 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
13175 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
13176 MI.getOperand(0).getReg())
13177 .addReg(PPC::CR0EQ);
13178 } else if (MI.getOpcode() == PPC::SETRNDi) {
13179 DebugLoc dl = MI.getDebugLoc();
13180 Register OldFPSCRReg = MI.getOperand(0).getReg();
13181
13182 // Save FPSCR value.
13183 if (MRI.use_empty(OldFPSCRReg))
13184 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
13185 else
13186 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
13187
13188 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
13189 // the following settings:
13190 // 00 Round to nearest
13191 // 01 Round to 0
13192 // 10 Round to +inf
13193 // 11 Round to -inf
13194
13195 // When the operand is immediate, using the two least significant bits of
13196 // the immediate to set the bits 62:63 of FPSCR.
13197 unsigned Mode = MI.getOperand(1).getImm();
13198 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
13199 .addImm(31)
13200 .addReg(PPC::RM, RegState::ImplicitDefine);
13201
13202 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
13203 .addImm(30)
13204 .addReg(PPC::RM, RegState::ImplicitDefine);
13205 } else if (MI.getOpcode() == PPC::SETRND) {
13206 DebugLoc dl = MI.getDebugLoc();
13207
13208 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
13209 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
13210 // If the target doesn't have DirectMove, we should use stack to do the
13211 // conversion, because the target doesn't have the instructions like mtvsrd
13212 // or mfvsrd to do this conversion directly.
13213 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
13214 if (Subtarget.hasDirectMove()) {
13215 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
13216 .addReg(SrcReg);
13217 } else {
13218 // Use stack to do the register copy.
13219 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
13220 MachineRegisterInfo &RegInfo = F->getRegInfo();
13221 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
13222 if (RC == &PPC::F8RCRegClass) {
13223 // Copy register from F8RCRegClass to G8RCRegclass.
13224 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&(static_cast <bool> ((RegInfo.getRegClass(DestReg) == &
PPC::G8RCRegClass) && "Unsupported RegClass.") ? void
(0) : __assert_fail ("(RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && \"Unsupported RegClass.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 13225, __extension__
__PRETTY_FUNCTION__))
13225 "Unsupported RegClass.")(static_cast <bool> ((RegInfo.getRegClass(DestReg) == &
PPC::G8RCRegClass) && "Unsupported RegClass.") ? void
(0) : __assert_fail ("(RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && \"Unsupported RegClass.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 13225, __extension__
__PRETTY_FUNCTION__))
;
13226
13227 StoreOp = PPC::STFD;
13228 LoadOp = PPC::LD;
13229 } else {
13230 // Copy register from G8RCRegClass to F8RCRegclass.
13231 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&(static_cast <bool> ((RegInfo.getRegClass(SrcReg) == &
PPC::G8RCRegClass) && (RegInfo.getRegClass(DestReg) ==
&PPC::F8RCRegClass) && "Unsupported RegClass.") ?
void (0) : __assert_fail ("(RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && \"Unsupported RegClass.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 13233, __extension__
__PRETTY_FUNCTION__))
13232 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&(static_cast <bool> ((RegInfo.getRegClass(SrcReg) == &
PPC::G8RCRegClass) && (RegInfo.getRegClass(DestReg) ==
&PPC::F8RCRegClass) && "Unsupported RegClass.") ?
void (0) : __assert_fail ("(RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && \"Unsupported RegClass.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 13233, __extension__
__PRETTY_FUNCTION__))
13233 "Unsupported RegClass.")(static_cast <bool> ((RegInfo.getRegClass(SrcReg) == &
PPC::G8RCRegClass) && (RegInfo.getRegClass(DestReg) ==
&PPC::F8RCRegClass) && "Unsupported RegClass.") ?
void (0) : __assert_fail ("(RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && \"Unsupported RegClass.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 13233, __extension__
__PRETTY_FUNCTION__))
;
13234 }
13235
13236 MachineFrameInfo &MFI = F->getFrameInfo();
13237 int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
13238
13239 MachineMemOperand *MMOStore = F->getMachineMemOperand(
13240 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
13241 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
13242 MFI.getObjectAlign(FrameIdx));
13243
13244 // Store the SrcReg into the stack.
13245 BuildMI(*BB, MI, dl, TII->get(StoreOp))
13246 .addReg(SrcReg)
13247 .addImm(0)
13248 .addFrameIndex(FrameIdx)
13249 .addMemOperand(MMOStore);
13250
13251 MachineMemOperand *MMOLoad = F->getMachineMemOperand(
13252 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
13253 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
13254 MFI.getObjectAlign(FrameIdx));
13255
13256 // Load from the stack where SrcReg is stored, and save to DestReg,
13257 // so we have done the RegClass conversion from RegClass::SrcReg to
13258 // RegClass::DestReg.
13259 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
13260 .addImm(0)
13261 .addFrameIndex(FrameIdx)
13262 .addMemOperand(MMOLoad);
13263 }
13264 };
13265
13266 Register OldFPSCRReg = MI.getOperand(0).getReg();
13267
13268 // Save FPSCR value.
13269 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
13270
13271 // When the operand is gprc register, use two least significant bits of the
13272 // register and mtfsf instruction to set the bits 62:63 of FPSCR.
13273 //
13274 // copy OldFPSCRTmpReg, OldFPSCRReg
13275 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
13276 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
13277 // copy NewFPSCRReg, NewFPSCRTmpReg
13278 // mtfsf 255, NewFPSCRReg
13279 MachineOperand SrcOp = MI.getOperand(1);
13280 MachineRegisterInfo &RegInfo = F->getRegInfo();
13281 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
13282
13283 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
13284
13285 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
13286 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
13287
13288 // The first operand of INSERT_SUBREG should be a register which has
13289 // subregisters, we only care about its RegClass, so we should use an
13290 // IMPLICIT_DEF register.
13291 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
13292 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
13293 .addReg(ImDefReg)
13294 .add(SrcOp)
13295 .addImm(1);
13296
13297 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
13298 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
13299 .addReg(OldFPSCRTmpReg)
13300 .addReg(ExtSrcReg)
13301 .addImm(0)
13302 .addImm(62);
13303
13304 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
13305 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
13306
13307 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
13308 // bits of FPSCR.
13309 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
13310 .addImm(255)
13311 .addReg(NewFPSCRReg)
13312 .addImm(0)
13313 .addImm(0);
13314 } else if (MI.getOpcode() == PPC::SETFLM) {
13315 DebugLoc Dl = MI.getDebugLoc();
13316
13317 // Result of setflm is previous FPSCR content, so we need to save it first.
13318 Register OldFPSCRReg = MI.getOperand(0).getReg();
13319 if (MRI.use_empty(OldFPSCRReg))
13320 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
13321 else
13322 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
13323
13324 // Put bits in 32:63 to FPSCR.
13325 Register NewFPSCRReg = MI.getOperand(1).getReg();
13326 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
13327 .addImm(255)
13328 .addReg(NewFPSCRReg)
13329 .addImm(0)
13330 .addImm(0);
13331 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
13332 MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
13333 return emitProbedAlloca(MI, BB);
13334 } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
13335 DebugLoc DL = MI.getDebugLoc();
13336 Register Src = MI.getOperand(2).getReg();
13337 Register Lo = MI.getOperand(0).getReg();
13338 Register Hi = MI.getOperand(1).getReg();
13339 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
13340 .addDef(Lo)
13341 .addUse(Src, 0, PPC::sub_gp8_x1);
13342 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
13343 .addDef(Hi)
13344 .addUse(Src, 0, PPC::sub_gp8_x0);
13345 } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
13346 MI.getOpcode() == PPC::STQX_PSEUDO) {
13347 DebugLoc DL = MI.getDebugLoc();
13348 // Ptr is used as the ptr_rc_no_r0 part
13349 // of LQ/STQ's memory operand and adding result of RA and RB,
13350 // so it has to be g8rc_and_g8rc_nox0.
13351 Register Ptr =
13352 F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
13353 Register Val = MI.getOperand(0).getReg();
13354 Register RA = MI.getOperand(1).getReg();
13355 Register RB = MI.getOperand(2).getReg();
13356 BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
13357 BuildMI(*BB, MI, DL,
13358 MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
13359 : TII->get(PPC::STQ))
13360 .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
13361 .addImm(0)
13362 .addReg(Ptr);
13363 } else {
13364 llvm_unreachable("Unexpected instr type to insert")::llvm::llvm_unreachable_internal("Unexpected instr type to insert"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 13364)
;
13365 }
13366
13367 MI.eraseFromParent(); // The pseudo instruction is gone now.
13368 return BB;
13369}
13370
13371//===----------------------------------------------------------------------===//
13372// Target Optimization Hooks
13373//===----------------------------------------------------------------------===//
13374
13375static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
13376 // For the estimates, convergence is quadratic, so we essentially double the
13377 // number of digits correct after every iteration. For both FRE and FRSQRTE,
13378 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
13379 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
13380 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
13381 if (VT.getScalarType() == MVT::f64)
13382 RefinementSteps++;
13383 return RefinementSteps;
13384}
13385
13386SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
13387 const DenormalMode &Mode) const {
13388 // We only have VSX Vector Test for software Square Root.
13389 EVT VT = Op.getValueType();
13390 if (!isTypeLegal(MVT::i1) ||
13391 (VT != MVT::f64 &&
13392 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
13393 return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
13394
13395 SDLoc DL(Op);
13396 // The output register of FTSQRT is CR field.
13397 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
13398 // ftsqrt BF,FRB
13399 // Let e_b be the unbiased exponent of the double-precision
13400 // floating-point operand in register FRB.
13401 // fe_flag is set to 1 if either of the following conditions occurs.
13402 // - The double-precision floating-point operand in register FRB is a zero,
13403 // a NaN, or an infinity, or a negative value.
13404 // - e_b is less than or equal to -970.
13405 // Otherwise fe_flag is set to 0.
13406 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
13407 // not eligible for iteration. (zero/negative/infinity/nan or unbiased
13408 // exponent is less than -970)
13409 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
13410 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
13411 FTSQRT, SRIdxVal),
13412 0);
13413}
13414
13415SDValue
13416PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
13417 SelectionDAG &DAG) const {
13418 // We only have VSX Vector Square Root.
13419 EVT VT = Op.getValueType();
13420 if (VT != MVT::f64 &&
13421 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
13422 return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
13423
13424 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
13425}
13426
13427SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
13428 int Enabled, int &RefinementSteps,
13429 bool &UseOneConstNR,
13430 bool Reciprocal) const {
13431 EVT VT = Operand.getValueType();
13432 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
13433 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
13434 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13435 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13436 if (RefinementSteps == ReciprocalEstimate::Unspecified)
13437 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13438
13439 // The Newton-Raphson computation with a single constant does not provide
13440 // enough accuracy on some CPUs.
13441 UseOneConstNR = !Subtarget.needsTwoConstNR();
13442 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
13443 }
13444 return SDValue();
13445}
13446
13447SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
13448 int Enabled,
13449 int &RefinementSteps) const {
13450 EVT VT = Operand.getValueType();
13451 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
13452 (VT == MVT::f64 && Subtarget.hasFRE()) ||
13453 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13454 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13455 if (RefinementSteps == ReciprocalEstimate::Unspecified)
13456 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13457 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
13458 }
13459 return SDValue();
13460}
13461
13462unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
13463 // Note: This functionality is used only when unsafe-fp-math is enabled, and
13464 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
13465 // enabled for division), this functionality is redundant with the default
13466 // combiner logic (once the division -> reciprocal/multiply transformation
13467 // has taken place). As a result, this matters more for older cores than for
13468 // newer ones.
13469
13470 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13471 // reciprocal if there are two or more FDIVs (for embedded cores with only
13472 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
13473 switch (Subtarget.getCPUDirective()) {
13474 default:
13475 return 3;
13476 case PPC::DIR_440:
13477 case PPC::DIR_A2:
13478 case PPC::DIR_E500:
13479 case PPC::DIR_E500mc:
13480 case PPC::DIR_E5500:
13481 return 2;
13482 }
13483}
13484
13485// isConsecutiveLSLoc needs to work even if all adds have not yet been
13486// collapsed, and so we need to look through chains of them.
13487static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
13488 int64_t& Offset, SelectionDAG &DAG) {
13489 if (DAG.isBaseWithConstantOffset(Loc)) {
13490 Base = Loc.getOperand(0);
13491 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
13492
13493 // The base might itself be a base plus an offset, and if so, accumulate
13494 // that as well.
13495 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
13496 }
13497}
13498
13499static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
13500 unsigned Bytes, int Dist,
13501 SelectionDAG &DAG) {
13502 if (VT.getSizeInBits() / 8 != Bytes)
13503 return false;
13504
13505 SDValue BaseLoc = Base->getBasePtr();
13506 if (Loc.getOpcode() == ISD::FrameIndex) {
13507 if (BaseLoc.getOpcode() != ISD::FrameIndex)
13508 return false;
13509 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
13510 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
13511 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
13512 int FS = MFI.getObjectSize(FI);
13513 int BFS = MFI.getObjectSize(BFI);
13514 if (FS != BFS || FS != (int)Bytes) return false;
13515 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
13516 }
13517
13518 SDValue Base1 = Loc, Base2 = BaseLoc;
13519 int64_t Offset1 = 0, Offset2 = 0;
13520 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
13521 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
13522 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
13523 return true;
13524
13525 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13526 const GlobalValue *GV1 = nullptr;
13527 const GlobalValue *GV2 = nullptr;
13528 Offset1 = 0;
13529 Offset2 = 0;
13530 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
13531 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
13532 if (isGA1 && isGA2 && GV1 == GV2)
13533 return Offset1 == (Offset2 + Dist*Bytes);
13534 return false;
13535}
13536
13537// Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
13538// not enforce equality of the chain operands.
13539static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
13540 unsigned Bytes, int Dist,
13541 SelectionDAG &DAG) {
13542 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
13543 EVT VT = LS->getMemoryVT();
13544 SDValue Loc = LS->getBasePtr();
13545 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
13546 }
13547
13548 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
13549 EVT VT;
13550 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13551 default: return false;
13552 case Intrinsic::ppc_altivec_lvx:
13553 case Intrinsic::ppc_altivec_lvxl:
13554 case Intrinsic::ppc_vsx_lxvw4x:
13555 case Intrinsic::ppc_vsx_lxvw4x_be:
13556 VT = MVT::v4i32;
13557 break;
13558 case Intrinsic::ppc_vsx_lxvd2x:
13559 case Intrinsic::ppc_vsx_lxvd2x_be:
13560 VT = MVT::v2f64;
13561 break;
13562 case Intrinsic::ppc_altivec_lvebx:
13563 VT = MVT::i8;
13564 break;
13565 case Intrinsic::ppc_altivec_lvehx:
13566 VT = MVT::i16;
13567 break;
13568 case Intrinsic::ppc_altivec_lvewx:
13569 VT = MVT::i32;
13570 break;
13571 }
13572
13573 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13574 }
13575
13576 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13577 EVT VT;
13578 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13579 default: return false;
13580 case Intrinsic::ppc_altivec_stvx:
13581 case Intrinsic::ppc_altivec_stvxl:
13582 case Intrinsic::ppc_vsx_stxvw4x:
13583 VT = MVT::v4i32;
13584 break;
13585 case Intrinsic::ppc_vsx_stxvd2x:
13586 VT = MVT::v2f64;
13587 break;
13588 case Intrinsic::ppc_vsx_stxvw4x_be:
13589 VT = MVT::v4i32;
13590 break;
13591 case Intrinsic::ppc_vsx_stxvd2x_be:
13592 VT = MVT::v2f64;
13593 break;
13594 case Intrinsic::ppc_altivec_stvebx:
13595 VT = MVT::i8;
13596 break;
13597 case Intrinsic::ppc_altivec_stvehx:
13598 VT = MVT::i16;
13599 break;
13600 case Intrinsic::ppc_altivec_stvewx:
13601 VT = MVT::i32;
13602 break;
13603 }
13604
13605 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13606 }
13607
13608 return false;
13609}
13610
13611// Return true is there is a nearyby consecutive load to the one provided
13612// (regardless of alignment). We search up and down the chain, looking though
13613// token factors and other loads (but nothing else). As a result, a true result
13614// indicates that it is safe to create a new consecutive load adjacent to the
13615// load provided.
13616static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13617 SDValue Chain = LD->getChain();
13618 EVT VT = LD->getMemoryVT();
13619
13620 SmallSet<SDNode *, 16> LoadRoots;
13621 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13622 SmallSet<SDNode *, 16> Visited;
13623
13624 // First, search up the chain, branching to follow all token-factor operands.
13625 // If we find a consecutive load, then we're done, otherwise, record all
13626 // nodes just above the top-level loads and token factors.
13627 while (!Queue.empty()) {
13628 SDNode *ChainNext = Queue.pop_back_val();
13629 if (!Visited.insert(ChainNext).second)
13630 continue;
13631
13632 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13633 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13634 return true;
13635
13636 if (!Visited.count(ChainLD->getChain().getNode()))
13637 Queue.push_back(ChainLD->getChain().getNode());
13638 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13639 for (const SDUse &O : ChainNext->ops())
13640 if (!Visited.count(O.getNode()))
13641 Queue.push_back(O.getNode());
13642 } else
13643 LoadRoots.insert(ChainNext);
13644 }
13645
13646 // Second, search down the chain, starting from the top-level nodes recorded
13647 // in the first phase. These top-level nodes are the nodes just above all
13648 // loads and token factors. Starting with their uses, recursively look though
13649 // all loads (just the chain uses) and token factors to find a consecutive
13650 // load.
13651 Visited.clear();
13652 Queue.clear();
13653
13654 for (SDNode *I : LoadRoots) {
13655 Queue.push_back(I);
13656
13657 while (!Queue.empty()) {
13658 SDNode *LoadRoot = Queue.pop_back_val();
13659 if (!Visited.insert(LoadRoot).second)
13660 continue;
13661
13662 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13663 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13664 return true;
13665
13666 for (SDNode *U : LoadRoot->uses())
13667 if (((isa<MemSDNode>(U) &&
13668 cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
13669 U->getOpcode() == ISD::TokenFactor) &&
13670 !Visited.count(U))
13671 Queue.push_back(U);
13672 }
13673 }
13674
13675 return false;
13676}
13677
13678/// This function is called when we have proved that a SETCC node can be replaced
13679/// by subtraction (and other supporting instructions) so that the result of
13680/// comparison is kept in a GPR instead of CR. This function is purely for
13681/// codegen purposes and has some flags to guide the codegen process.
13682static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13683 bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13684 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.")(static_cast <bool> (N->getOpcode() == ISD::SETCC &&
"ISD::SETCC Expected.") ? void (0) : __assert_fail ("N->getOpcode() == ISD::SETCC && \"ISD::SETCC Expected.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 13684, __extension__
__PRETTY_FUNCTION__))
;
13685
13686 // Zero extend the operands to the largest legal integer. Originally, they
13687 // must be of a strictly smaller size.
13688 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13689 DAG.getConstant(Size, DL, MVT::i32));
13690 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13691 DAG.getConstant(Size, DL, MVT::i32));
13692
13693 // Swap if needed. Depends on the condition code.
13694 if (Swap)
13695 std::swap(Op0, Op1);
13696
13697 // Subtract extended integers.
13698 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13699
13700 // Move the sign bit to the least significant position and zero out the rest.
13701 // Now the least significant bit carries the result of original comparison.
13702 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13703 DAG.getConstant(Size - 1, DL, MVT::i32));
13704 auto Final = Shifted;
13705
13706 // Complement the result if needed. Based on the condition code.
13707 if (Complement)
13708 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13709 DAG.getConstant(1, DL, MVT::i64));
13710
13711 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13712}
13713
13714SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13715 DAGCombinerInfo &DCI) const {
13716 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.")(static_cast <bool> (N->getOpcode() == ISD::SETCC &&
"ISD::SETCC Expected.") ? void (0) : __assert_fail ("N->getOpcode() == ISD::SETCC && \"ISD::SETCC Expected.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 13716, __extension__
__PRETTY_FUNCTION__))
;
13717
13718 SelectionDAG &DAG = DCI.DAG;
13719 SDLoc DL(N);
13720
13721 // Size of integers being compared has a critical role in the following
13722 // analysis, so we prefer to do this when all types are legal.
13723 if (!DCI.isAfterLegalizeDAG())
13724 return SDValue();
13725
13726 // If all users of SETCC extend its value to a legal integer type
13727 // then we replace SETCC with a subtraction
13728 for (const SDNode *U : N->uses())
13729 if (U->getOpcode() != ISD::ZERO_EXTEND)
13730 return SDValue();
13731
13732 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13733 auto OpSize = N->getOperand(0).getValueSizeInBits();
13734
13735 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13736
13737 if (OpSize < Size) {
13738 switch (CC) {
13739 default: break;
13740 case ISD::SETULT:
13741 return generateEquivalentSub(N, Size, false, false, DL, DAG);
13742 case ISD::SETULE:
13743 return generateEquivalentSub(N, Size, true, true, DL, DAG);
13744 case ISD::SETUGT:
13745 return generateEquivalentSub(N, Size, false, true, DL, DAG);
13746 case ISD::SETUGE:
13747 return generateEquivalentSub(N, Size, true, false, DL, DAG);
13748 }
13749 }
13750
13751 return SDValue();
13752}
13753
13754SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13755 DAGCombinerInfo &DCI) const {
13756 SelectionDAG &DAG = DCI.DAG;
13757 SDLoc dl(N);
13758
13759 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits")(static_cast <bool> (Subtarget.useCRBits() && "Expecting to be tracking CR bits"
) ? void (0) : __assert_fail ("Subtarget.useCRBits() && \"Expecting to be tracking CR bits\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 13759, __extension__
__PRETTY_FUNCTION__))
;
13760 // If we're tracking CR bits, we need to be careful that we don't have:
13761 // trunc(binary-ops(zext(x), zext(y)))
13762 // or
13763 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13764 // such that we're unnecessarily moving things into GPRs when it would be
13765 // better to keep them in CR bits.
13766
13767 // Note that trunc here can be an actual i1 trunc, or can be the effective
13768 // truncation that comes from a setcc or select_cc.
13769 if (N->getOpcode() == ISD::TRUNCATE &&
13770 N->getValueType(0) != MVT::i1)
13771 return SDValue();
13772
13773 if (N->getOperand(0).getValueType() != MVT::i32 &&
13774 N->getOperand(0).getValueType() != MVT::i64)
13775 return SDValue();
13776
13777 if (N->getOpcode() == ISD::SETCC ||
13778 N->getOpcode() == ISD::SELECT_CC) {
13779 // If we're looking at a comparison, then we need to make sure that the
13780 // high bits (all except for the first) don't matter the result.
13781 ISD::CondCode CC =
13782 cast<CondCodeSDNode>(N->getOperand(
13783 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13784 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13785
13786 if (ISD::isSignedIntSetCC(CC)) {
13787 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13788 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13789 return SDValue();
13790 } else if (ISD::isUnsignedIntSetCC(CC)) {
13791 if (!DAG.MaskedValueIsZero(N->getOperand(0),
13792 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13793 !DAG.MaskedValueIsZero(N->getOperand(1),
13794 APInt::getHighBitsSet(OpBits, OpBits-1)))
13795 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13796 : SDValue());
13797 } else {
13798 // This is neither a signed nor an unsigned comparison, just make sure
13799 // that the high bits are equal.
13800 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13801 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13802
13803 // We don't really care about what is known about the first bit (if
13804 // anything), so pretend that it is known zero for both to ensure they can
13805 // be compared as constants.
13806 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13807 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13808
13809 if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13810 Op1Known.getConstant() != Op2Known.getConstant())
13811 return SDValue();
13812 }
13813 }
13814
13815 // We now know that the higher-order bits are irrelevant, we just need to
13816 // make sure that all of the intermediate operations are bit operations, and
13817 // all inputs are extensions.
13818 if (N->getOperand(0).getOpcode() != ISD::AND &&
13819 N->getOperand(0).getOpcode() != ISD::OR &&
13820 N->getOperand(0).getOpcode() != ISD::XOR &&
13821 N->getOperand(0).getOpcode() != ISD::SELECT &&
13822 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13823 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13824 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13825 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13826 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13827 return SDValue();
13828
13829 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13830 N->getOperand(1).getOpcode() != ISD::AND &&
13831 N->getOperand(1).getOpcode() != ISD::OR &&
13832 N->getOperand(1).getOpcode() != ISD::XOR &&
13833 N->getOperand(1).getOpcode() != ISD::SELECT &&
13834 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13835 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13836 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13837 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13838 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13839 return SDValue();
13840
13841 SmallVector<SDValue, 4> Inputs;
13842 SmallVector<SDValue, 8> BinOps, PromOps;
13843 SmallPtrSet<SDNode *, 16> Visited;
13844
13845 for (unsigned i = 0; i < 2; ++i) {
13846 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13847 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13848 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13849 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13850 isa<ConstantSDNode>(N->getOperand(i)))
13851 Inputs.push_back(N->getOperand(i));
13852 else
13853 BinOps.push_back(N->getOperand(i));
13854
13855 if (N->getOpcode() == ISD::TRUNCATE)
13856 break;
13857 }
13858
13859 // Visit all inputs, collect all binary operations (and, or, xor and
13860 // select) that are all fed by extensions.
13861 while (!BinOps.empty()) {
13862 SDValue BinOp = BinOps.pop_back_val();
13863
13864 if (!Visited.insert(BinOp.getNode()).second)
13865 continue;
13866
13867 PromOps.push_back(BinOp);
13868
13869 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13870 // The condition of the select is not promoted.
13871 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13872 continue;
13873 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13874 continue;
13875
13876 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13877 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13878 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13879 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13880 isa<ConstantSDNode>(BinOp.getOperand(i))) {
13881 Inputs.push_back(BinOp.getOperand(i));
13882 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13883 BinOp.getOperand(i).getOpcode() == ISD::OR ||
13884 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13885 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13886 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13887 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13888 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13889 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13890 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13891 BinOps.push_back(BinOp.getOperand(i));
13892 } else {
13893 // We have an input that is not an extension or another binary
13894 // operation; we'll abort this transformation.
13895 return SDValue();
13896 }
13897 }
13898 }
13899
13900 // Make sure that this is a self-contained cluster of operations (which
13901 // is not quite the same thing as saying that everything has only one
13902 // use).
13903 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13904 if (isa<ConstantSDNode>(Inputs[i]))
13905 continue;
13906
13907 for (const SDNode *User : Inputs[i].getNode()->uses()) {
13908 if (User != N && !Visited.count(User))
13909 return SDValue();
13910
13911 // Make sure that we're not going to promote the non-output-value
13912 // operand(s) or SELECT or SELECT_CC.
13913 // FIXME: Although we could sometimes handle this, and it does occur in
13914 // practice that one of the condition inputs to the select is also one of
13915 // the outputs, we currently can't deal with this.
13916 if (User->getOpcode() == ISD::SELECT) {
13917 if (User->getOperand(0) == Inputs[i])
13918 return SDValue();
13919 } else if (User->getOpcode() == ISD::SELECT_CC) {
13920 if (User->getOperand(0) == Inputs[i] ||
13921 User->getOperand(1) == Inputs[i])
13922 return SDValue();
13923 }
13924 }
13925 }
13926
13927 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13928 for (const SDNode *User : PromOps[i].getNode()->uses()) {
13929 if (User != N && !Visited.count(User))
13930 return SDValue();
13931
13932 // Make sure that we're not going to promote the non-output-value
13933 // operand(s) or SELECT or SELECT_CC.
13934 // FIXME: Although we could sometimes handle this, and it does occur in
13935 // practice that one of the condition inputs to the select is also one of
13936 // the outputs, we currently can't deal with this.
13937 if (User->getOpcode() == ISD::SELECT) {
13938 if (User->getOperand(0) == PromOps[i])
13939 return SDValue();
13940 } else if (User->getOpcode() == ISD::SELECT_CC) {
13941 if (User->getOperand(0) == PromOps[i] ||
13942 User->getOperand(1) == PromOps[i])
13943 return SDValue();
13944 }
13945 }
13946 }
13947
13948 // Replace all inputs with the extension operand.
13949 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13950 // Constants may have users outside the cluster of to-be-promoted nodes,
13951 // and so we need to replace those as we do the promotions.
13952 if (isa<ConstantSDNode>(Inputs[i]))
13953 continue;
13954 else
13955 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13956 }
13957
13958 std::list<HandleSDNode> PromOpHandles;
13959 for (auto &PromOp : PromOps)
13960 PromOpHandles.emplace_back(PromOp);
13961
13962 // Replace all operations (these are all the same, but have a different
13963 // (i1) return type). DAG.getNode will validate that the types of
13964 // a binary operator match, so go through the list in reverse so that
13965 // we've likely promoted both operands first. Any intermediate truncations or
13966 // extensions disappear.
13967 while (!PromOpHandles.empty()) {
13968 SDValue PromOp = PromOpHandles.back().getValue();
13969 PromOpHandles.pop_back();
13970
13971 if (PromOp.getOpcode() == ISD::TRUNCATE ||
13972 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13973 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13974 PromOp.getOpcode() == ISD::ANY_EXTEND) {
13975 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13976 PromOp.getOperand(0).getValueType() != MVT::i1) {
13977 // The operand is not yet ready (see comment below).
13978 PromOpHandles.emplace_front(PromOp);
13979 continue;
13980 }
13981
13982 SDValue RepValue = PromOp.getOperand(0);
13983 if (isa<ConstantSDNode>(RepValue))
13984 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13985
13986 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13987 continue;
13988 }
13989
13990 unsigned C;
13991 switch (PromOp.getOpcode()) {
13992 default: C = 0; break;
13993 case ISD::SELECT: C = 1; break;
13994 case ISD::SELECT_CC: C = 2; break;
13995 }
13996
13997 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13998 PromOp.getOperand(C).getValueType() != MVT::i1) ||
13999 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
14000 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
14001 // The to-be-promoted operands of this node have not yet been
14002 // promoted (this should be rare because we're going through the
14003 // list backward, but if one of the operands has several users in
14004 // this cluster of to-be-promoted nodes, it is possible).
14005 PromOpHandles.emplace_front(PromOp);
14006 continue;
14007 }
14008
14009 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
14010 PromOp.getNode()->op_end());
14011
14012 // If there are any constant inputs, make sure they're replaced now.
14013 for (unsigned i = 0; i < 2; ++i)
14014 if (isa<ConstantSDNode>(Ops[C+i]))
14015 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
14016
14017 DAG.ReplaceAllUsesOfValueWith(PromOp,
14018 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
14019 }
14020
14021 // Now we're left with the initial truncation itself.
14022 if (N->getOpcode() == ISD::TRUNCATE)
14023 return N->getOperand(0);
14024
14025 // Otherwise, this is a comparison. The operands to be compared have just
14026 // changed type (to i1), but everything else is the same.
14027 return SDValue(N, 0);
14028}
14029
14030SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
14031 DAGCombinerInfo &DCI) const {
14032 SelectionDAG &DAG = DCI.DAG;
14033 SDLoc dl(N);
14034
14035 // If we're tracking CR bits, we need to be careful that we don't have:
14036 // zext(binary-ops(trunc(x), trunc(y)))
14037 // or
14038 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
14039 // such that we're unnecessarily moving things into CR bits that can more
14040 // efficiently stay in GPRs. Note that if we're not certain that the high
14041 // bits are set as required by the final extension, we still may need to do
14042 // some masking to get the proper behavior.
14043
14044 // This same functionality is important on PPC64 when dealing with
14045 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
14046 // the return values of functions. Because it is so similar, it is handled
14047 // here as well.
14048
14049 if (N->getValueType(0) != MVT::i32 &&
14050 N->getValueType(0) != MVT::i64)
14051 return SDValue();
14052
14053 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
14054 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
14055 return SDValue();
14056
14057 if (N->getOperand(0).getOpcode() != ISD::AND &&
14058 N->getOperand(0).getOpcode() != ISD::OR &&
14059 N->getOperand(0).getOpcode() != ISD::XOR &&
14060 N->getOperand(0).getOpcode() != ISD::SELECT &&
14061 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
14062 return SDValue();
14063
14064 SmallVector<SDValue, 4> Inputs;
14065 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
14066 SmallPtrSet<SDNode *, 16> Visited;
14067
14068 // Visit all inputs, collect all binary operations (and, or, xor and
14069 // select) that are all fed by truncations.
14070 while (!BinOps.empty()) {
14071 SDValue BinOp = BinOps.pop_back_val();
14072
14073 if (!Visited.insert(BinOp.getNode()).second)
14074 continue;
14075
14076 PromOps.push_back(BinOp);
14077
14078 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
14079 // The condition of the select is not promoted.
14080 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
14081 continue;
14082 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
14083 continue;
14084
14085 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
14086 isa<ConstantSDNode>(BinOp.getOperand(i))) {
14087 Inputs.push_back(BinOp.getOperand(i));
14088 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
14089 BinOp.getOperand(i).getOpcode() == ISD::OR ||
14090 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
14091 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
14092 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
14093 BinOps.push_back(BinOp.getOperand(i));
14094 } else {
14095 // We have an input that is not a truncation or another binary
14096 // operation; we'll abort this transformation.
14097 return SDValue();
14098 }
14099 }
14100 }
14101
14102 // The operands of a select that must be truncated when the select is
14103 // promoted because the operand is actually part of the to-be-promoted set.
14104 DenseMap<SDNode *, EVT> SelectTruncOp[2];
14105
14106 // Make sure that this is a self-contained cluster of operations (which
14107 // is not quite the same thing as saying that everything has only one
14108 // use).
14109 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
14110 if (isa<ConstantSDNode>(Inputs[i]))
14111 continue;
14112
14113 for (SDNode *User : Inputs[i].getNode()->uses()) {
14114 if (User != N && !Visited.count(User))
14115 return SDValue();
14116
14117 // If we're going to promote the non-output-value operand(s) or SELECT or
14118 // SELECT_CC, record them for truncation.
14119 if (User->getOpcode() == ISD::SELECT) {
14120 if (User->getOperand(0) == Inputs[i])
14121 SelectTruncOp[0].insert(std::make_pair(User,
14122 User->getOperand(0).getValueType()));
14123 } else if (User->getOpcode() == ISD::SELECT_CC) {
14124 if (User->getOperand(0) == Inputs[i])
14125 SelectTruncOp[0].insert(std::make_pair(User,
14126 User->getOperand(0).getValueType()));
14127 if (User->getOperand(1) == Inputs[i])
14128 SelectTruncOp[1].insert(std::make_pair(User,
14129 User->getOperand(1).getValueType()));
14130 }
14131 }
14132 }
14133
14134 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
14135 for (SDNode *User : PromOps[i].getNode()->uses()) {
14136 if (User != N && !Visited.count(User))
14137 return SDValue();
14138
14139 // If we're going to promote the non-output-value operand(s) or SELECT or
14140 // SELECT_CC, record them for truncation.
14141 if (User->getOpcode() == ISD::SELECT) {
14142 if (User->getOperand(0) == PromOps[i])
14143 SelectTruncOp[0].insert(std::make_pair(User,
14144 User->getOperand(0).getValueType()));
14145 } else if (User->getOpcode() == ISD::SELECT_CC) {
14146 if (User->getOperand(0) == PromOps[i])
14147 SelectTruncOp[0].insert(std::make_pair(User,
14148 User->getOperand(0).getValueType()));
14149 if (User->getOperand(1) == PromOps[i])
14150 SelectTruncOp[1].insert(std::make_pair(User,
14151 User->getOperand(1).getValueType()));
14152 }
14153 }
14154 }
14155
14156 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
14157 bool ReallyNeedsExt = false;
14158 if (N->getOpcode() != ISD::ANY_EXTEND) {
14159 // If all of the inputs are not already sign/zero extended, then
14160 // we'll still need to do that at the end.
14161 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
14162 if (isa<ConstantSDNode>(Inputs[i]))
14163 continue;
14164
14165 unsigned OpBits =
14166 Inputs[i].getOperand(0).getValueSizeInBits();
14167 assert(PromBits < OpBits && "Truncation not to a smaller bit count?")(static_cast <bool> (PromBits < OpBits && "Truncation not to a smaller bit count?"
) ? void (0) : __assert_fail ("PromBits < OpBits && \"Truncation not to a smaller bit count?\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14167, __extension__
__PRETTY_FUNCTION__))
;
14168
14169 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
14170 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
14171 APInt::getHighBitsSet(OpBits,
14172 OpBits-PromBits))) ||
14173 (N->getOpcode() == ISD::SIGN_EXTEND &&
14174 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
14175 (OpBits-(PromBits-1)))) {
14176 ReallyNeedsExt = true;
14177 break;
14178 }
14179 }
14180 }
14181
14182 // Replace all inputs, either with the truncation operand, or a
14183 // truncation or extension to the final output type.
14184 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
14185 // Constant inputs need to be replaced with the to-be-promoted nodes that
14186 // use them because they might have users outside of the cluster of
14187 // promoted nodes.
14188 if (isa<ConstantSDNode>(Inputs[i]))
14189 continue;
14190
14191 SDValue InSrc = Inputs[i].getOperand(0);
14192 if (Inputs[i].getValueType() == N->getValueType(0))
14193 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
14194 else if (N->getOpcode() == ISD::SIGN_EXTEND)
14195 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
14196 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
14197 else if (N->getOpcode() == ISD::ZERO_EXTEND)
14198 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
14199 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
14200 else
14201 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
14202 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
14203 }
14204
14205 std::list<HandleSDNode> PromOpHandles;
14206 for (auto &PromOp : PromOps)
14207 PromOpHandles.emplace_back(PromOp);
14208
14209 // Replace all operations (these are all the same, but have a different
14210 // (promoted) return type). DAG.getNode will validate that the types of
14211 // a binary operator match, so go through the list in reverse so that
14212 // we've likely promoted both operands first.
14213 while (!PromOpHandles.empty()) {
14214 SDValue PromOp = PromOpHandles.back().getValue();
14215 PromOpHandles.pop_back();
14216
14217 unsigned C;
14218 switch (PromOp.getOpcode()) {
14219 default: C = 0; break;
14220 case ISD::SELECT: C = 1; break;
14221 case ISD::SELECT_CC: C = 2; break;
14222 }
14223
14224 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
14225 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
14226 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
14227 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
14228 // The to-be-promoted operands of this node have not yet been
14229 // promoted (this should be rare because we're going through the
14230 // list backward, but if one of the operands has several users in
14231 // this cluster of to-be-promoted nodes, it is possible).
14232 PromOpHandles.emplace_front(PromOp);
14233 continue;
14234 }
14235
14236 // For SELECT and SELECT_CC nodes, we do a similar check for any
14237 // to-be-promoted comparison inputs.
14238 if (PromOp.getOpcode() == ISD::SELECT ||
14239 PromOp.getOpcode() == ISD::SELECT_CC) {
14240 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
14241 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
14242 (SelectTruncOp[1].count(PromOp.getNode()) &&
14243 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
14244 PromOpHandles.emplace_front(PromOp);
14245 continue;
14246 }
14247 }
14248
14249 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
14250 PromOp.getNode()->op_end());
14251
14252 // If this node has constant inputs, then they'll need to be promoted here.
14253 for (unsigned i = 0; i < 2; ++i) {
14254 if (!isa<ConstantSDNode>(Ops[C+i]))
14255 continue;
14256 if (Ops[C+i].getValueType() == N->getValueType(0))
14257 continue;
14258
14259 if (N->getOpcode() == ISD::SIGN_EXTEND)
14260 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
14261 else if (N->getOpcode() == ISD::ZERO_EXTEND)
14262 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
14263 else
14264 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
14265 }
14266
14267 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
14268 // truncate them again to the original value type.
14269 if (PromOp.getOpcode() == ISD::SELECT ||
14270 PromOp.getOpcode() == ISD::SELECT_CC) {
14271 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
14272 if (SI0 != SelectTruncOp[0].end())
14273 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
14274 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
14275 if (SI1 != SelectTruncOp[1].end())
14276 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
14277 }
14278
14279 DAG.ReplaceAllUsesOfValueWith(PromOp,
14280 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
14281 }
14282
14283 // Now we're left with the initial extension itself.
14284 if (!ReallyNeedsExt)
14285 return N->getOperand(0);
14286
14287 // To zero extend, just mask off everything except for the first bit (in the
14288 // i1 case).
14289 if (N->getOpcode() == ISD::ZERO_EXTEND)
14290 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
14291 DAG.getConstant(APInt::getLowBitsSet(
14292 N->getValueSizeInBits(0), PromBits),
14293 dl, N->getValueType(0)));
14294
14295 assert(N->getOpcode() == ISD::SIGN_EXTEND &&(static_cast <bool> (N->getOpcode() == ISD::SIGN_EXTEND
&& "Invalid extension type") ? void (0) : __assert_fail
("N->getOpcode() == ISD::SIGN_EXTEND && \"Invalid extension type\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14296, __extension__
__PRETTY_FUNCTION__))
14296 "Invalid extension type")(static_cast <bool> (N->getOpcode() == ISD::SIGN_EXTEND
&& "Invalid extension type") ? void (0) : __assert_fail
("N->getOpcode() == ISD::SIGN_EXTEND && \"Invalid extension type\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14296, __extension__
__PRETTY_FUNCTION__))
;
14297 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
14298 SDValue ShiftCst =
14299 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
14300 return DAG.getNode(
14301 ISD::SRA, dl, N->getValueType(0),
14302 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
14303 ShiftCst);
14304}
14305
14306SDValue PPCTargetLowering::combineSetCC(SDNode *N,
14307 DAGCombinerInfo &DCI) const {
14308 assert(N->getOpcode() == ISD::SETCC &&(static_cast <bool> (N->getOpcode() == ISD::SETCC &&
"Should be called with a SETCC node") ? void (0) : __assert_fail
("N->getOpcode() == ISD::SETCC && \"Should be called with a SETCC node\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14309, __extension__
__PRETTY_FUNCTION__))
14309 "Should be called with a SETCC node")(static_cast <bool> (N->getOpcode() == ISD::SETCC &&
"Should be called with a SETCC node") ? void (0) : __assert_fail
("N->getOpcode() == ISD::SETCC && \"Should be called with a SETCC node\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14309, __extension__
__PRETTY_FUNCTION__))
;
14310
14311 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
14312 if (CC == ISD::SETNE || CC == ISD::SETEQ) {
14313 SDValue LHS = N->getOperand(0);
14314 SDValue RHS = N->getOperand(1);
14315
14316 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
14317 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
14318 LHS.hasOneUse())
14319 std::swap(LHS, RHS);
14320
14321 // x == 0-y --> x+y == 0
14322 // x != 0-y --> x+y != 0
14323 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
14324 RHS.hasOneUse()) {
14325 SDLoc DL(N);
14326 SelectionDAG &DAG = DCI.DAG;
14327 EVT VT = N->getValueType(0);
14328 EVT OpVT = LHS.getValueType();
14329 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
14330 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
14331 }
14332 }
14333
14334 return DAGCombineTruncBoolExt(N, DCI);
14335}
14336
14337// Is this an extending load from an f32 to an f64?
14338static bool isFPExtLoad(SDValue Op) {
14339 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
14340 return LD->getExtensionType() == ISD::EXTLOAD &&
14341 Op.getValueType() == MVT::f64;
14342 return false;
14343}
14344
14345/// Reduces the number of fp-to-int conversion when building a vector.
14346///
14347/// If this vector is built out of floating to integer conversions,
14348/// transform it to a vector built out of floating point values followed by a
14349/// single floating to integer conversion of the vector.
14350/// Namely (build_vector (fptosi $A), (fptosi $B), ...)
14351/// becomes (fptosi (build_vector ($A, $B, ...)))
14352SDValue PPCTargetLowering::
14353combineElementTruncationToVectorTruncation(SDNode *N,
14354 DAGCombinerInfo &DCI) const {
14355 assert(N->getOpcode() == ISD::BUILD_VECTOR &&(static_cast <bool> (N->getOpcode() == ISD::BUILD_VECTOR
&& "Should be called with a BUILD_VECTOR node") ? void
(0) : __assert_fail ("N->getOpcode() == ISD::BUILD_VECTOR && \"Should be called with a BUILD_VECTOR node\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14356, __extension__
__PRETTY_FUNCTION__))
14356 "Should be called with a BUILD_VECTOR node")(static_cast <bool> (N->getOpcode() == ISD::BUILD_VECTOR
&& "Should be called with a BUILD_VECTOR node") ? void
(0) : __assert_fail ("N->getOpcode() == ISD::BUILD_VECTOR && \"Should be called with a BUILD_VECTOR node\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14356, __extension__
__PRETTY_FUNCTION__))
;
14357
14358 SelectionDAG &DAG = DCI.DAG;
14359 SDLoc dl(N);
14360
14361 SDValue FirstInput = N->getOperand(0);
14362 assert(FirstInput.getOpcode() == PPCISD::MFVSR &&(static_cast <bool> (FirstInput.getOpcode() == PPCISD::
MFVSR && "The input operand must be an fp-to-int conversion."
) ? void (0) : __assert_fail ("FirstInput.getOpcode() == PPCISD::MFVSR && \"The input operand must be an fp-to-int conversion.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14363, __extension__
__PRETTY_FUNCTION__))
14363 "The input operand must be an fp-to-int conversion.")(static_cast <bool> (FirstInput.getOpcode() == PPCISD::
MFVSR && "The input operand must be an fp-to-int conversion."
) ? void (0) : __assert_fail ("FirstInput.getOpcode() == PPCISD::MFVSR && \"The input operand must be an fp-to-int conversion.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14363, __extension__
__PRETTY_FUNCTION__))
;
14364
14365 // This combine happens after legalization so the fp_to_[su]i nodes are
14366 // already converted to PPCSISD nodes.
14367 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
14368 if (FirstConversion == PPCISD::FCTIDZ ||
14369 FirstConversion == PPCISD::FCTIDUZ ||
14370 FirstConversion == PPCISD::FCTIWZ ||
14371 FirstConversion == PPCISD::FCTIWUZ) {
14372 bool IsSplat = true;
14373 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
14374 FirstConversion == PPCISD::FCTIWUZ;
14375 EVT SrcVT = FirstInput.getOperand(0).getValueType();
14376 SmallVector<SDValue, 4> Ops;
14377 EVT TargetVT = N->getValueType(0);
14378 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14379 SDValue NextOp = N->getOperand(i);
14380 if (NextOp.getOpcode() != PPCISD::MFVSR)
14381 return SDValue();
14382 unsigned NextConversion = NextOp.getOperand(0).getOpcode();
14383 if (NextConversion != FirstConversion)
14384 return SDValue();
14385 // If we are converting to 32-bit integers, we need to add an FP_ROUND.
14386 // This is not valid if the input was originally double precision. It is
14387 // also not profitable to do unless this is an extending load in which
14388 // case doing this combine will allow us to combine consecutive loads.
14389 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
14390 return SDValue();
14391 if (N->getOperand(i) != FirstInput)
14392 IsSplat = false;
14393 }
14394
14395 // If this is a splat, we leave it as-is since there will be only a single
14396 // fp-to-int conversion followed by a splat of the integer. This is better
14397 // for 32-bit and smaller ints and neutral for 64-bit ints.
14398 if (IsSplat)
14399 return SDValue();
14400
14401 // Now that we know we have the right type of node, get its operands
14402 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14403 SDValue In = N->getOperand(i).getOperand(0);
14404 if (Is32Bit) {
14405 // For 32-bit values, we need to add an FP_ROUND node (if we made it
14406 // here, we know that all inputs are extending loads so this is safe).
14407 if (In.isUndef())
14408 Ops.push_back(DAG.getUNDEF(SrcVT));
14409 else {
14410 SDValue Trunc =
14411 DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, In.getOperand(0),
14412 DAG.getIntPtrConstant(1, dl, /*isTarget=*/true));
14413 Ops.push_back(Trunc);
14414 }
14415 } else
14416 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
14417 }
14418
14419 unsigned Opcode;
14420 if (FirstConversion == PPCISD::FCTIDZ ||
14421 FirstConversion == PPCISD::FCTIWZ)
14422 Opcode = ISD::FP_TO_SINT;
14423 else
14424 Opcode = ISD::FP_TO_UINT;
14425
14426 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
14427 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
14428 return DAG.getNode(Opcode, dl, TargetVT, BV);
14429 }
14430 return SDValue();
14431}
14432
14433/// Reduce the number of loads when building a vector.
14434///
14435/// Building a vector out of multiple loads can be converted to a load
14436/// of the vector type if the loads are consecutive. If the loads are
14437/// consecutive but in descending order, a shuffle is added at the end
14438/// to reorder the vector.
14439static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
14440 assert(N->getOpcode() == ISD::BUILD_VECTOR &&(static_cast <bool> (N->getOpcode() == ISD::BUILD_VECTOR
&& "Should be called with a BUILD_VECTOR node") ? void
(0) : __assert_fail ("N->getOpcode() == ISD::BUILD_VECTOR && \"Should be called with a BUILD_VECTOR node\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14441, __extension__
__PRETTY_FUNCTION__))
14441 "Should be called with a BUILD_VECTOR node")(static_cast <bool> (N->getOpcode() == ISD::BUILD_VECTOR
&& "Should be called with a BUILD_VECTOR node") ? void
(0) : __assert_fail ("N->getOpcode() == ISD::BUILD_VECTOR && \"Should be called with a BUILD_VECTOR node\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14441, __extension__
__PRETTY_FUNCTION__))
;
14442
14443 SDLoc dl(N);
14444
14445 // Return early for non byte-sized type, as they can't be consecutive.
14446 if (!N->getValueType(0).getVectorElementType().isByteSized())
14447 return SDValue();
14448
14449 bool InputsAreConsecutiveLoads = true;
14450 bool InputsAreReverseConsecutive = true;
14451 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
14452 SDValue FirstInput = N->getOperand(0);
14453 bool IsRoundOfExtLoad = false;
14454 LoadSDNode *FirstLoad = nullptr;
14455
14456 if (FirstInput.getOpcode() == ISD::FP_ROUND &&
14457 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
14458 FirstLoad = cast<LoadSDNode>(FirstInput.getOperand(0));
14459 IsRoundOfExtLoad = FirstLoad->getExtensionType() == ISD::EXTLOAD;
14460 }
14461 // Not a build vector of (possibly fp_rounded) loads.
14462 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
14463 N->getNumOperands() == 1)
14464 return SDValue();
14465
14466 if (!IsRoundOfExtLoad)
14467 FirstLoad = cast<LoadSDNode>(FirstInput);
14468
14469 SmallVector<LoadSDNode *, 4> InputLoads;
14470 InputLoads.push_back(FirstLoad);
14471 for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
14472 // If any inputs are fp_round(extload), they all must be.
14473 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
14474 return SDValue();
14475
14476 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
14477 N->getOperand(i);
14478 if (NextInput.getOpcode() != ISD::LOAD)
14479 return SDValue();
14480
14481 SDValue PreviousInput =
14482 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
14483 LoadSDNode *LD1 = cast<LoadSDNode>(PreviousInput);
14484 LoadSDNode *LD2 = cast<LoadSDNode>(NextInput);
14485
14486 // If any inputs are fp_round(extload), they all must be.
14487 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
14488 return SDValue();
14489
14490 // We only care about regular loads. The PPC-specific load intrinsics
14491 // will not lead to a merge opportunity.
14492 if (!DAG.areNonVolatileConsecutiveLoads(LD2, LD1, ElemSize, 1))
14493 InputsAreConsecutiveLoads = false;
14494 if (!DAG.areNonVolatileConsecutiveLoads(LD1, LD2, ElemSize, 1))
14495 InputsAreReverseConsecutive = false;
14496
14497 // Exit early if the loads are neither consecutive nor reverse consecutive.
14498 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
14499 return SDValue();
14500 InputLoads.push_back(LD2);
14501 }
14502
14503 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&(static_cast <bool> (!(InputsAreConsecutiveLoads &&
InputsAreReverseConsecutive) && "The loads cannot be both consecutive and reverse consecutive."
) ? void (0) : __assert_fail ("!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && \"The loads cannot be both consecutive and reverse consecutive.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14504, __extension__
__PRETTY_FUNCTION__))
14504 "The loads cannot be both consecutive and reverse consecutive.")(static_cast <bool> (!(InputsAreConsecutiveLoads &&
InputsAreReverseConsecutive) && "The loads cannot be both consecutive and reverse consecutive."
) ? void (0) : __assert_fail ("!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && \"The loads cannot be both consecutive and reverse consecutive.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14504, __extension__
__PRETTY_FUNCTION__))
;
14505
14506 SDValue WideLoad;
14507 SDValue ReturnSDVal;
14508 if (InputsAreConsecutiveLoads) {
14509 assert(FirstLoad && "Input needs to be a LoadSDNode.")(static_cast <bool> (FirstLoad && "Input needs to be a LoadSDNode."
) ? void (0) : __assert_fail ("FirstLoad && \"Input needs to be a LoadSDNode.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14509, __extension__
__PRETTY_FUNCTION__))
;
14510 WideLoad = DAG.getLoad(N->getValueType(0), dl, FirstLoad->getChain(),
14511 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
14512 FirstLoad->getAlign());
14513 ReturnSDVal = WideLoad;
14514 } else if (InputsAreReverseConsecutive) {
14515 LoadSDNode *LastLoad = InputLoads.back();
14516 assert(LastLoad && "Input needs to be a LoadSDNode.")(static_cast <bool> (LastLoad && "Input needs to be a LoadSDNode."
) ? void (0) : __assert_fail ("LastLoad && \"Input needs to be a LoadSDNode.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14516, __extension__
__PRETTY_FUNCTION__))
;
14517 WideLoad = DAG.getLoad(N->getValueType(0), dl, LastLoad->getChain(),
14518 LastLoad->getBasePtr(), LastLoad->getPointerInfo(),
14519 LastLoad->getAlign());
14520 SmallVector<int, 16> Ops;
14521 for (int i = N->getNumOperands() - 1; i >= 0; i--)
14522 Ops.push_back(i);
14523
14524 ReturnSDVal = DAG.getVectorShuffle(N->getValueType(0), dl, WideLoad,
14525 DAG.getUNDEF(N->getValueType(0)), Ops);
14526 } else
14527 return SDValue();
14528
14529 for (auto *LD : InputLoads)
14530 DAG.makeEquivalentMemoryOrdering(LD, WideLoad);
14531 return ReturnSDVal;
14532}
14533
14534// This function adds the required vector_shuffle needed to get
14535// the elements of the vector extract in the correct position
14536// as specified by the CorrectElems encoding.
14537static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
14538 SDValue Input, uint64_t Elems,
14539 uint64_t CorrectElems) {
14540 SDLoc dl(N);
14541
14542 unsigned NumElems = Input.getValueType().getVectorNumElements();
14543 SmallVector<int, 16> ShuffleMask(NumElems, -1);
14544
14545 // Knowing the element indices being extracted from the original
14546 // vector and the order in which they're being inserted, just put
14547 // them at element indices required for the instruction.
14548 for (unsigned i = 0; i < N->getNumOperands(); i++) {
14549 if (DAG.getDataLayout().isLittleEndian())
14550 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
14551 else
14552 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
14553 CorrectElems = CorrectElems >> 8;
14554 Elems = Elems >> 8;
14555 }
14556
14557 SDValue Shuffle =
14558 DAG.getVectorShuffle(Input.getValueType(), dl, Input,
14559 DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14560
14561 EVT VT = N->getValueType(0);
14562 SDValue Conv = DAG.getBitcast(VT, Shuffle);
14563
14564 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14565 Input.getValueType().getVectorElementType(),
14566 VT.getVectorNumElements());
14567 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14568 DAG.getValueType(ExtVT));
14569}
14570
14571// Look for build vector patterns where input operands come from sign
14572// extended vector_extract elements of specific indices. If the correct indices
14573// aren't used, add a vector shuffle to fix up the indices and create
14574// SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14575// during instruction selection.
14576static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14577 // This array encodes the indices that the vector sign extend instructions
14578 // extract from when extending from one type to another for both BE and LE.
14579 // The right nibble of each byte corresponds to the LE incides.
14580 // and the left nibble of each byte corresponds to the BE incides.
14581 // For example: 0x3074B8FC byte->word
14582 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14583 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14584 // For example: 0x000070F8 byte->double word
14585 // For LE: the allowed indices are: 0x0,0x8
14586 // For BE: the allowed indices are: 0x7,0xF
14587 uint64_t TargetElems[] = {
14588 0x3074B8FC, // b->w
14589 0x000070F8, // b->d
14590 0x10325476, // h->w
14591 0x00003074, // h->d
14592 0x00001032, // w->d
14593 };
14594
14595 uint64_t Elems = 0;
14596 int Index;
14597 SDValue Input;
14598
14599 auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14600 if (!Op)
14601 return false;
14602 if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14603 Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14604 return false;
14605
14606 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14607 // of the right width.
14608 SDValue Extract = Op.getOperand(0);
14609 if (Extract.getOpcode() == ISD::ANY_EXTEND)
14610 Extract = Extract.getOperand(0);
14611 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14612 return false;
14613
14614 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14615 if (!ExtOp)
14616 return false;
14617
14618 Index = ExtOp->getZExtValue();
14619 if (Input && Input != Extract.getOperand(0))
14620 return false;
14621
14622 if (!Input)
14623 Input = Extract.getOperand(0);
14624
14625 Elems = Elems << 8;
14626 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14627 Elems |= Index;
14628
14629 return true;
14630 };
14631
14632 // If the build vector operands aren't sign extended vector extracts,
14633 // of the same input vector, then return.
14634 for (unsigned i = 0; i < N->getNumOperands(); i++) {
14635 if (!isSExtOfVecExtract(N->getOperand(i))) {
14636 return SDValue();
14637 }
14638 }
14639
14640 // If the vector extract indicies are not correct, add the appropriate
14641 // vector_shuffle.
14642 int TgtElemArrayIdx;
14643 int InputSize = Input.getValueType().getScalarSizeInBits();
14644 int OutputSize = N->getValueType(0).getScalarSizeInBits();
14645 if (InputSize + OutputSize == 40)
14646 TgtElemArrayIdx = 0;
14647 else if (InputSize + OutputSize == 72)
14648 TgtElemArrayIdx = 1;
14649 else if (InputSize + OutputSize == 48)
14650 TgtElemArrayIdx = 2;
14651 else if (InputSize + OutputSize == 80)
14652 TgtElemArrayIdx = 3;
14653 else if (InputSize + OutputSize == 96)
14654 TgtElemArrayIdx = 4;
14655 else
14656 return SDValue();
14657
14658 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14659 CorrectElems = DAG.getDataLayout().isLittleEndian()
14660 ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14661 : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14662 if (Elems != CorrectElems) {
14663 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14664 }
14665
14666 // Regular lowering will catch cases where a shuffle is not needed.
14667 return SDValue();
14668}
14669
14670// Look for the pattern of a load from a narrow width to i128, feeding
14671// into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14672// (LXVRZX). This node represents a zero extending load that will be matched
14673// to the Load VSX Vector Rightmost instructions.
14674static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14675 SDLoc DL(N);
14676
14677 // This combine is only eligible for a BUILD_VECTOR of v1i128.
14678 if (N->getValueType(0) != MVT::v1i128)
14679 return SDValue();
14680
14681 SDValue Operand = N->getOperand(0);
14682 // Proceed with the transformation if the operand to the BUILD_VECTOR
14683 // is a load instruction.
14684 if (Operand.getOpcode() != ISD::LOAD)
14685 return SDValue();
14686
14687 auto *LD = cast<LoadSDNode>(Operand);
14688 EVT MemoryType = LD->getMemoryVT();
14689
14690 // This transformation is only valid if the we are loading either a byte,
14691 // halfword, word, or doubleword.
14692 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14693 MemoryType == MVT::i32 || MemoryType == MVT::i64;
14694
14695 // Ensure that the load from the narrow width is being zero extended to i128.
14696 if (!ValidLDType ||
14697 (LD->getExtensionType() != ISD::ZEXTLOAD &&
14698 LD->getExtensionType() != ISD::EXTLOAD))
14699 return SDValue();
14700
14701 SDValue LoadOps[] = {
14702 LD->getChain(), LD->getBasePtr(),
14703 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14704
14705 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14706 DAG.getVTList(MVT::v1i128, MVT::Other),
14707 LoadOps, MemoryType, LD->getMemOperand());
14708}
14709
14710SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14711 DAGCombinerInfo &DCI) const {
14712 assert(N->getOpcode() == ISD::BUILD_VECTOR &&(static_cast <bool> (N->getOpcode() == ISD::BUILD_VECTOR
&& "Should be called with a BUILD_VECTOR node") ? void
(0) : __assert_fail ("N->getOpcode() == ISD::BUILD_VECTOR && \"Should be called with a BUILD_VECTOR node\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14713, __extension__
__PRETTY_FUNCTION__))
14713 "Should be called with a BUILD_VECTOR node")(static_cast <bool> (N->getOpcode() == ISD::BUILD_VECTOR
&& "Should be called with a BUILD_VECTOR node") ? void
(0) : __assert_fail ("N->getOpcode() == ISD::BUILD_VECTOR && \"Should be called with a BUILD_VECTOR node\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14713, __extension__
__PRETTY_FUNCTION__))
;
14714
14715 SelectionDAG &DAG = DCI.DAG;
14716 SDLoc dl(N);
14717
14718 if (!Subtarget.hasVSX())
14719 return SDValue();
14720
14721 // The target independent DAG combiner will leave a build_vector of
14722 // float-to-int conversions intact. We can generate MUCH better code for
14723 // a float-to-int conversion of a vector of floats.
14724 SDValue FirstInput = N->getOperand(0);
14725 if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14726 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14727 if (Reduced)
14728 return Reduced;
14729 }
14730
14731 // If we're building a vector out of consecutive loads, just load that
14732 // vector type.
14733 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14734 if (Reduced)
14735 return Reduced;
14736
14737 // If we're building a vector out of extended elements from another vector
14738 // we have P9 vector integer extend instructions. The code assumes legal
14739 // input types (i.e. it can't handle things like v4i16) so do not run before
14740 // legalization.
14741 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14742 Reduced = combineBVOfVecSExt(N, DAG);
14743 if (Reduced)
14744 return Reduced;
14745 }
14746
14747 // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14748 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14749 // is a load from <valid narrow width> to i128.
14750 if (Subtarget.isISA3_1()) {
14751 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14752 if (BVOfZLoad)
14753 return BVOfZLoad;
14754 }
14755
14756 if (N->getValueType(0) != MVT::v2f64)
14757 return SDValue();
14758
14759 // Looking for:
14760 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14761 if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14762 FirstInput.getOpcode() != ISD::UINT_TO_FP)
14763 return SDValue();
14764 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14765 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14766 return SDValue();
14767 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14768 return SDValue();
14769
14770 SDValue Ext1 = FirstInput.getOperand(0);
14771 SDValue Ext2 = N->getOperand(1).getOperand(0);
14772 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14773 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14774 return SDValue();
14775
14776 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14777 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14778 if (!Ext1Op || !Ext2Op)
14779 return SDValue();
14780 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14781 Ext1.getOperand(0) != Ext2.getOperand(0))
14782 return SDValue();
14783
14784 int FirstElem = Ext1Op->getZExtValue();
14785 int SecondElem = Ext2Op->getZExtValue();
14786 int SubvecIdx;
14787 if (FirstElem == 0 && SecondElem == 1)
14788 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14789 else if (FirstElem == 2 && SecondElem == 3)
14790 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14791 else
14792 return SDValue();
14793
14794 SDValue SrcVec = Ext1.getOperand(0);
14795 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14796 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14797 return DAG.getNode(NodeType, dl, MVT::v2f64,
14798 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14799}
14800
14801SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14802 DAGCombinerInfo &DCI) const {
14803 assert((N->getOpcode() == ISD::SINT_TO_FP ||(static_cast <bool> ((N->getOpcode() == ISD::SINT_TO_FP
|| N->getOpcode() == ISD::UINT_TO_FP) && "Need an int -> FP conversion node here"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SINT_TO_FP || N->getOpcode() == ISD::UINT_TO_FP) && \"Need an int -> FP conversion node here\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14805, __extension__
__PRETTY_FUNCTION__))
14804 N->getOpcode() == ISD::UINT_TO_FP) &&(static_cast <bool> ((N->getOpcode() == ISD::SINT_TO_FP
|| N->getOpcode() == ISD::UINT_TO_FP) && "Need an int -> FP conversion node here"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SINT_TO_FP || N->getOpcode() == ISD::UINT_TO_FP) && \"Need an int -> FP conversion node here\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14805, __extension__
__PRETTY_FUNCTION__))
14805 "Need an int -> FP conversion node here")(static_cast <bool> ((N->getOpcode() == ISD::SINT_TO_FP
|| N->getOpcode() == ISD::UINT_TO_FP) && "Need an int -> FP conversion node here"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SINT_TO_FP || N->getOpcode() == ISD::UINT_TO_FP) && \"Need an int -> FP conversion node here\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14805, __extension__
__PRETTY_FUNCTION__))
;
14806
14807 if (useSoftFloat() || !Subtarget.has64BitSupport())
14808 return SDValue();
14809
14810 SelectionDAG &DAG = DCI.DAG;
14811 SDLoc dl(N);
14812 SDValue Op(N, 0);
14813
14814 // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14815 // from the hardware.
14816 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14817 return SDValue();
14818 if (!Op.getOperand(0).getValueType().isSimple())
14819 return SDValue();
14820 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14821 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14822 return SDValue();
14823
14824 SDValue FirstOperand(Op.getOperand(0));
14825 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14826 (FirstOperand.getValueType() == MVT::i8 ||
14827 FirstOperand.getValueType() == MVT::i16);
14828 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14829 bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14830 bool DstDouble = Op.getValueType() == MVT::f64;
14831 unsigned ConvOp = Signed ?
14832 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
14833 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14834 SDValue WidthConst =
14835 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14836 dl, false);
14837 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14838 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14839 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14840 DAG.getVTList(MVT::f64, MVT::Other),
14841 Ops, MVT::i8, LDN->getMemOperand());
14842
14843 // For signed conversion, we need to sign-extend the value in the VSR
14844 if (Signed) {
14845 SDValue ExtOps[] = { Ld, WidthConst };
14846 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14847 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14848 } else
14849 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14850 }
14851
14852
14853 // For i32 intermediate values, unfortunately, the conversion functions
14854 // leave the upper 32 bits of the value are undefined. Within the set of
14855 // scalar instructions, we have no method for zero- or sign-extending the
14856 // value. Thus, we cannot handle i32 intermediate values here.
14857 if (Op.getOperand(0).getValueType() == MVT::i32)
14858 return SDValue();
14859
14860 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&(static_cast <bool> ((Op.getOpcode() == ISD::SINT_TO_FP
|| Subtarget.hasFPCVT()) && "UINT_TO_FP is supported only with FPCVT"
) ? void (0) : __assert_fail ("(Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && \"UINT_TO_FP is supported only with FPCVT\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14861, __extension__
__PRETTY_FUNCTION__))
14861 "UINT_TO_FP is supported only with FPCVT")(static_cast <bool> ((Op.getOpcode() == ISD::SINT_TO_FP
|| Subtarget.hasFPCVT()) && "UINT_TO_FP is supported only with FPCVT"
) ? void (0) : __assert_fail ("(Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && \"UINT_TO_FP is supported only with FPCVT\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14861, __extension__
__PRETTY_FUNCTION__))
;
14862
14863 // If we have FCFIDS, then use it when converting to single-precision.
14864 // Otherwise, convert to double-precision and then round.
14865 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14866 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14867 : PPCISD::FCFIDS)
14868 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14869 : PPCISD::FCFID);
14870 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14871 ? MVT::f32
14872 : MVT::f64;
14873
14874 // If we're converting from a float, to an int, and back to a float again,
14875 // then we don't need the store/load pair at all.
14876 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14877 Subtarget.hasFPCVT()) ||
14878 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14879 SDValue Src = Op.getOperand(0).getOperand(0);
14880 if (Src.getValueType() == MVT::f32) {
14881 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14882 DCI.AddToWorklist(Src.getNode());
14883 } else if (Src.getValueType() != MVT::f64) {
14884 // Make sure that we don't pick up a ppc_fp128 source value.
14885 return SDValue();
14886 }
14887
14888 unsigned FCTOp =
14889 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14890 PPCISD::FCTIDUZ;
14891
14892 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14893 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14894
14895 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14896 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
14897 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
14898 DCI.AddToWorklist(FP.getNode());
14899 }
14900
14901 return FP;
14902 }
14903
14904 return SDValue();
14905}
14906
14907// expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14908// builtins) into loads with swaps.
14909SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14910 DAGCombinerInfo &DCI) const {
14911 // Delay VSX load for LE combine until after LegalizeOps to prioritize other
14912 // load combines.
14913 if (DCI.isBeforeLegalizeOps())
14914 return SDValue();
14915
14916 SelectionDAG &DAG = DCI.DAG;
14917 SDLoc dl(N);
14918 SDValue Chain;
14919 SDValue Base;
14920 MachineMemOperand *MMO;
14921
14922 switch (N->getOpcode()) {
14923 default:
14924 llvm_unreachable("Unexpected opcode for little endian VSX load")::llvm::llvm_unreachable_internal("Unexpected opcode for little endian VSX load"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14924)
;
14925 case ISD::LOAD: {
14926 LoadSDNode *LD = cast<LoadSDNode>(N);
14927 Chain = LD->getChain();
14928 Base = LD->getBasePtr();
14929 MMO = LD->getMemOperand();
14930 // If the MMO suggests this isn't a load of a full vector, leave
14931 // things alone. For a built-in, we have to make the change for
14932 // correctness, so if there is a size problem that will be a bug.
14933 if (MMO->getSize() < 16)
14934 return SDValue();
14935 break;
14936 }
14937 case ISD::INTRINSIC_W_CHAIN: {
14938 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14939 Chain = Intrin->getChain();
14940 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14941 // us what we want. Get operand 2 instead.
14942 Base = Intrin->getOperand(2);
14943 MMO = Intrin->getMemOperand();
14944 break;
14945 }
14946 }
14947
14948 MVT VecTy = N->getValueType(0).getSimpleVT();
14949
14950 SDValue LoadOps[] = { Chain, Base };
14951 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14952 DAG.getVTList(MVT::v2f64, MVT::Other),
14953 LoadOps, MVT::v2f64, MMO);
14954
14955 DCI.AddToWorklist(Load.getNode());
14956 Chain = Load.getValue(1);
14957 SDValue Swap = DAG.getNode(
14958 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14959 DCI.AddToWorklist(Swap.getNode());
14960
14961 // Add a bitcast if the resulting load type doesn't match v2f64.
14962 if (VecTy != MVT::v2f64) {
14963 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14964 DCI.AddToWorklist(N.getNode());
14965 // Package {bitcast value, swap's chain} to match Load's shape.
14966 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14967 N, Swap.getValue(1));
14968 }
14969
14970 return Swap;
14971}
14972
14973// expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14974// builtins) into stores with swaps.
14975SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14976 DAGCombinerInfo &DCI) const {
14977 // Delay VSX store for LE combine until after LegalizeOps to prioritize other
14978 // store combines.
14979 if (DCI.isBeforeLegalizeOps())
14980 return SDValue();
14981
14982 SelectionDAG &DAG = DCI.DAG;
14983 SDLoc dl(N);
14984 SDValue Chain;
14985 SDValue Base;
14986 unsigned SrcOpnd;
14987 MachineMemOperand *MMO;
14988
14989 switch (N->getOpcode()) {
14990 default:
14991 llvm_unreachable("Unexpected opcode for little endian VSX store")::llvm::llvm_unreachable_internal("Unexpected opcode for little endian VSX store"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 14991)
;
14992 case ISD::STORE: {
14993 StoreSDNode *ST = cast<StoreSDNode>(N);
14994 Chain = ST->getChain();
14995 Base = ST->getBasePtr();
14996 MMO = ST->getMemOperand();
14997 SrcOpnd = 1;
14998 // If the MMO suggests this isn't a store of a full vector, leave
14999 // things alone. For a built-in, we have to make the change for
15000 // correctness, so if there is a size problem that will be a bug.
15001 if (MMO->getSize() < 16)
15002 return SDValue();
15003 break;
15004 }
15005 case ISD::INTRINSIC_VOID: {
15006 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
15007 Chain = Intrin->getChain();
15008 // Intrin->getBasePtr() oddly does not get what we want.
15009 Base = Intrin->getOperand(3);
15010 MMO = Intrin->getMemOperand();
15011 SrcOpnd = 2;
15012 break;
15013 }
15014 }
15015
15016 SDValue Src = N->getOperand(SrcOpnd);
15017 MVT VecTy = Src.getValueType().getSimpleVT();
15018
15019 // All stores are done as v2f64 and possible bit cast.
15020 if (VecTy != MVT::v2f64) {
15021 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
15022 DCI.AddToWorklist(Src.getNode());
15023 }
15024
15025 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
15026 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
15027 DCI.AddToWorklist(Swap.getNode());
15028 Chain = Swap.getValue(1);
15029 SDValue StoreOps[] = { Chain, Swap, Base };
15030 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
15031 DAG.getVTList(MVT::Other),
15032 StoreOps, VecTy, MMO);
15033 DCI.AddToWorklist(Store.getNode());
15034 return Store;
15035}
15036
15037// Handle DAG combine for STORE (FP_TO_INT F).
15038SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
15039 DAGCombinerInfo &DCI) const {
15040
15041 SelectionDAG &DAG = DCI.DAG;
15042 SDLoc dl(N);
15043 unsigned Opcode = N->getOperand(1).getOpcode();
15044
15045 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)(static_cast <bool> ((Opcode == ISD::FP_TO_SINT || Opcode
== ISD::FP_TO_UINT) && "Not a FP_TO_INT Instruction!"
) ? void (0) : __assert_fail ("(Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) && \"Not a FP_TO_INT Instruction!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15046, __extension__
__PRETTY_FUNCTION__))
15046 && "Not a FP_TO_INT Instruction!")(static_cast <bool> ((Opcode == ISD::FP_TO_SINT || Opcode
== ISD::FP_TO_UINT) && "Not a FP_TO_INT Instruction!"
) ? void (0) : __assert_fail ("(Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) && \"Not a FP_TO_INT Instruction!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15046, __extension__
__PRETTY_FUNCTION__))
;
15047
15048 SDValue Val = N->getOperand(1).getOperand(0);
15049 EVT Op1VT = N->getOperand(1).getValueType();
15050 EVT ResVT = Val.getValueType();
15051
15052 if (!isTypeLegal(ResVT))
15053 return SDValue();
15054
15055 // Only perform combine for conversion to i64/i32 or power9 i16/i8.
15056 bool ValidTypeForStoreFltAsInt =
15057 (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
15058 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
15059
15060 if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
15061 return SDValue();
15062
15063 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
15064 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
15065 return SDValue();
15066
15067 // Extend f32 values to f64
15068 if (ResVT.getScalarSizeInBits() == 32) {
15069 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
15070 DCI.AddToWorklist(Val.getNode());
15071 }
15072
15073 // Set signed or unsigned conversion opcode.
15074 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
15075 PPCISD::FP_TO_SINT_IN_VSR :
15076 PPCISD::FP_TO_UINT_IN_VSR;
15077
15078 Val = DAG.getNode(ConvOpcode,
15079 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
15080 DCI.AddToWorklist(Val.getNode());
15081
15082 // Set number of bytes being converted.
15083 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
15084 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
15085 DAG.getIntPtrConstant(ByteSize, dl, false),
15086 DAG.getValueType(Op1VT) };
15087
15088 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
15089 DAG.getVTList(MVT::Other), Ops,
15090 cast<StoreSDNode>(N)->getMemoryVT(),
15091 cast<StoreSDNode>(N)->getMemOperand());
15092
15093 DCI.AddToWorklist(Val.getNode());
15094 return Val;
15095}
15096
15097static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
15098 // Check that the source of the element keeps flipping
15099 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
15100 bool PrevElemFromFirstVec = Mask[0] < NumElts;
15101 for (int i = 1, e = Mask.size(); i < e; i++) {
15102 if (PrevElemFromFirstVec && Mask[i] < NumElts)
15103 return false;
15104 if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
15105 return false;
15106 PrevElemFromFirstVec = !PrevElemFromFirstVec;
15107 }
15108 return true;
15109}
15110
15111static bool isSplatBV(SDValue Op) {
15112 if (Op.getOpcode() != ISD::BUILD_VECTOR)
15113 return false;
15114 SDValue FirstOp;
15115
15116 // Find first non-undef input.
15117 for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
15118 FirstOp = Op.getOperand(i);
15119 if (!FirstOp.isUndef())
15120 break;
15121 }
15122
15123 // All inputs are undef or the same as the first non-undef input.
15124 for (int i = 1, e = Op.getNumOperands(); i < e; i++)
15125 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
15126 return false;
15127 return true;
15128}
15129
15130static SDValue isScalarToVec(SDValue Op) {
15131 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
15132 return Op;
15133 if (Op.getOpcode() != ISD::BITCAST)
15134 return SDValue();
15135 Op = Op.getOperand(0);
15136 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
15137 return Op;
15138 return SDValue();
15139}
15140
15141// Fix up the shuffle mask to account for the fact that the result of
15142// scalar_to_vector is not in lane zero. This just takes all values in
15143// the ranges specified by the min/max indices and adds the number of
15144// elements required to ensure each element comes from the respective
15145// position in the valid lane.
15146// On little endian, that's just the corresponding element in the other
15147// half of the vector. On big endian, it is in the same half but right
15148// justified rather than left justified in that half.
15149static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
15150 int LHSMaxIdx, int RHSMinIdx,
15151 int RHSMaxIdx, int HalfVec,
15152 unsigned ValidLaneWidth,
15153 const PPCSubtarget &Subtarget) {
15154 for (int i = 0, e = ShuffV.size(); i < e; i++) {
15155 int Idx = ShuffV[i];
15156 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
15157 ShuffV[i] +=
15158 Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
15159 }
15160}
15161
15162// Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
15163// the original is:
15164// (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
15165// In such a case, just change the shuffle mask to extract the element
15166// from the permuted index.
15167static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
15168 const PPCSubtarget &Subtarget) {
15169 SDLoc dl(OrigSToV);
15170 EVT VT = OrigSToV.getValueType();
15171 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&(static_cast <bool> (OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR
&& "Expecting a SCALAR_TO_VECTOR here") ? void (0) :
__assert_fail ("OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && \"Expecting a SCALAR_TO_VECTOR here\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15172, __extension__
__PRETTY_FUNCTION__))
15172 "Expecting a SCALAR_TO_VECTOR here")(static_cast <bool> (OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR
&& "Expecting a SCALAR_TO_VECTOR here") ? void (0) :
__assert_fail ("OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && \"Expecting a SCALAR_TO_VECTOR here\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15172, __extension__
__PRETTY_FUNCTION__))
;
15173 SDValue Input = OrigSToV.getOperand(0);
15174
15175 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15176 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
15177 SDValue OrigVector = Input.getOperand(0);
15178
15179 // Can't handle non-const element indices or different vector types
15180 // for the input to the extract and the output of the scalar_to_vector.
15181 if (Idx && VT == OrigVector.getValueType()) {
15182 unsigned NumElts = VT.getVectorNumElements();
15183 assert((static_cast <bool> (NumElts > 1 && "Cannot produce a permuted scalar_to_vector for one element vector"
) ? void (0) : __assert_fail ("NumElts > 1 && \"Cannot produce a permuted scalar_to_vector for one element vector\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15185, __extension__
__PRETTY_FUNCTION__))
15184 NumElts > 1 &&(static_cast <bool> (NumElts > 1 && "Cannot produce a permuted scalar_to_vector for one element vector"
) ? void (0) : __assert_fail ("NumElts > 1 && \"Cannot produce a permuted scalar_to_vector for one element vector\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15185, __extension__
__PRETTY_FUNCTION__))
15185 "Cannot produce a permuted scalar_to_vector for one element vector")(static_cast <bool> (NumElts > 1 && "Cannot produce a permuted scalar_to_vector for one element vector"
) ? void (0) : __assert_fail ("NumElts > 1 && \"Cannot produce a permuted scalar_to_vector for one element vector\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15185, __extension__
__PRETTY_FUNCTION__))
;
15186 SmallVector<int, 16> NewMask(NumElts, -1);
15187 unsigned ResultInElt = NumElts / 2;
15188 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
15189 NewMask[ResultInElt] = Idx->getZExtValue();
15190 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
15191 }
15192 }
15193 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
15194 OrigSToV.getOperand(0));
15195}
15196
15197// On little endian subtargets, combine shuffles such as:
15198// vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
15199// into:
15200// vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
15201// because the latter can be matched to a single instruction merge.
15202// Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
15203// to put the value into element zero. Adjust the shuffle mask so that the
15204// vector can remain in permuted form (to prevent a swap prior to a shuffle).
15205// On big endian targets, this is still useful for SCALAR_TO_VECTOR
15206// nodes with elements smaller than doubleword because all the ways
15207// of getting scalar data into a vector register put the value in the
15208// rightmost element of the left half of the vector.
15209SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
15210 SelectionDAG &DAG) const {
15211 SDValue LHS = SVN->getOperand(0);
15212 SDValue RHS = SVN->getOperand(1);
15213 auto Mask = SVN->getMask();
15214 int NumElts = LHS.getValueType().getVectorNumElements();
15215 SDValue Res(SVN, 0);
15216 SDLoc dl(SVN);
15217 bool IsLittleEndian = Subtarget.isLittleEndian();
15218
15219 // On big endian targets this is only useful for subtargets with direct moves.
15220 // On little endian targets it would be useful for all subtargets with VSX.
15221 // However adding special handling for LE subtargets without direct moves
15222 // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
15223 // which includes direct moves.
15224 if (!Subtarget.hasDirectMove())
15225 return Res;
15226
15227 // If this is not a shuffle of a shuffle and the first element comes from
15228 // the second vector, canonicalize to the commuted form. This will make it
15229 // more likely to match one of the single instruction patterns.
15230 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15231 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
15232 std::swap(LHS, RHS);
15233 Res = DAG.getCommutedVectorShuffle(*SVN);
15234 Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
15235 }
15236
15237 // Adjust the shuffle mask if either input vector comes from a
15238 // SCALAR_TO_VECTOR and keep the respective input vector in permuted
15239 // form (to prevent the need for a swap).
15240 SmallVector<int, 16> ShuffV(Mask);
15241 SDValue SToVLHS = isScalarToVec(LHS);
15242 SDValue SToVRHS = isScalarToVec(RHS);
15243 if (SToVLHS || SToVRHS) {
15244 // FIXME: If both LHS and RHS are SCALAR_TO_VECTOR, but are not the
15245 // same type and have differing element sizes, then do not perform
15246 // the following transformation. The current transformation for
15247 // SCALAR_TO_VECTOR assumes that both input vectors have the same
15248 // element size. This will be updated in the future to account for
15249 // differing sizes of the LHS and RHS.
15250 if (SToVLHS && SToVRHS &&
15251 (SToVLHS.getValueType().getScalarSizeInBits() !=
15252 SToVRHS.getValueType().getScalarSizeInBits()))
15253 return Res;
15254
15255 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
15256 : SToVRHS.getValueType().getVectorNumElements();
15257 int NumEltsOut = ShuffV.size();
15258 // The width of the "valid lane" (i.e. the lane that contains the value that
15259 // is vectorized) needs to be expressed in terms of the number of elements
15260 // of the shuffle. It is thereby the ratio of the values before and after
15261 // any bitcast.
15262 unsigned ValidLaneWidth =
15263 SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
15264 LHS.getValueType().getScalarSizeInBits()
15265 : SToVRHS.getValueType().getScalarSizeInBits() /
15266 RHS.getValueType().getScalarSizeInBits();
15267
15268 // Initially assume that neither input is permuted. These will be adjusted
15269 // accordingly if either input is.
15270 int LHSMaxIdx = -1;
15271 int RHSMinIdx = -1;
15272 int RHSMaxIdx = -1;
15273 int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
15274
15275 // Get the permuted scalar to vector nodes for the source(s) that come from
15276 // ISD::SCALAR_TO_VECTOR.
15277 // On big endian systems, this only makes sense for element sizes smaller
15278 // than 64 bits since for 64-bit elements, all instructions already put
15279 // the value into element zero. Since scalar size of LHS and RHS may differ
15280 // after isScalarToVec, this should be checked using their own sizes.
15281 if (SToVLHS) {
15282 if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
15283 return Res;
15284 // Set up the values for the shuffle vector fixup.
15285 LHSMaxIdx = NumEltsOut / NumEltsIn;
15286 SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
15287 if (SToVLHS.getValueType() != LHS.getValueType())
15288 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
15289 LHS = SToVLHS;
15290 }
15291 if (SToVRHS) {
15292 if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
15293 return Res;
15294 RHSMinIdx = NumEltsOut;
15295 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
15296 SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
15297 if (SToVRHS.getValueType() != RHS.getValueType())
15298 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
15299 RHS = SToVRHS;
15300 }
15301
15302 // Fix up the shuffle mask to reflect where the desired element actually is.
15303 // The minimum and maximum indices that correspond to element zero for both
15304 // the LHS and RHS are computed and will control which shuffle mask entries
15305 // are to be changed. For example, if the RHS is permuted, any shuffle mask
15306 // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
15307 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
15308 HalfVec, ValidLaneWidth, Subtarget);
15309 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
15310
15311 // We may have simplified away the shuffle. We won't be able to do anything
15312 // further with it here.
15313 if (!isa<ShuffleVectorSDNode>(Res))
15314 return Res;
15315 Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
15316 }
15317
15318 SDValue TheSplat = IsLittleEndian ? RHS : LHS;
15319 // The common case after we commuted the shuffle is that the RHS is a splat
15320 // and we have elements coming in from the splat at indices that are not
15321 // conducive to using a merge.
15322 // Example:
15323 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
15324 if (!isSplatBV(TheSplat))
15325 return Res;
15326
15327 // We are looking for a mask such that all even elements are from
15328 // one vector and all odd elements from the other.
15329 if (!isAlternatingShuffMask(Mask, NumElts))
15330 return Res;
15331
15332 // Adjust the mask so we are pulling in the same index from the splat
15333 // as the index from the interesting vector in consecutive elements.
15334 if (IsLittleEndian) {
15335 // Example (even elements from first vector):
15336 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
15337 if (Mask[0] < NumElts)
15338 for (int i = 1, e = Mask.size(); i < e; i += 2) {
15339 if (ShuffV[i] < 0)
15340 continue;
15341 ShuffV[i] = (ShuffV[i - 1] + NumElts);
15342 }
15343 // Example (odd elements from first vector):
15344 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
15345 else
15346 for (int i = 0, e = Mask.size(); i < e; i += 2) {
15347 if (ShuffV[i] < 0)
15348 continue;
15349 ShuffV[i] = (ShuffV[i + 1] + NumElts);
15350 }
15351 } else {
15352 // Example (even elements from first vector):
15353 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
15354 if (Mask[0] < NumElts)
15355 for (int i = 0, e = Mask.size(); i < e; i += 2) {
15356 if (ShuffV[i] < 0)
15357 continue;
15358 ShuffV[i] = ShuffV[i + 1] - NumElts;
15359 }
15360 // Example (odd elements from first vector):
15361 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
15362 else
15363 for (int i = 1, e = Mask.size(); i < e; i += 2) {
15364 if (ShuffV[i] < 0)
15365 continue;
15366 ShuffV[i] = ShuffV[i - 1] - NumElts;
15367 }
15368 }
15369
15370 // If the RHS has undefs, we need to remove them since we may have created
15371 // a shuffle that adds those instead of the splat value.
15372 SDValue SplatVal =
15373 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
15374 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
15375
15376 if (IsLittleEndian)
15377 RHS = TheSplat;
15378 else
15379 LHS = TheSplat;
15380 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
15381}
15382
15383SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
15384 LSBaseSDNode *LSBase,
15385 DAGCombinerInfo &DCI) const {
15386 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&(static_cast <bool> ((ISD::isNormalLoad(LSBase) || ISD::
isNormalStore(LSBase)) && "Not a reverse memop pattern!"
) ? void (0) : __assert_fail ("(ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && \"Not a reverse memop pattern!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15387, __extension__
__PRETTY_FUNCTION__))
15387 "Not a reverse memop pattern!")(static_cast <bool> ((ISD::isNormalLoad(LSBase) || ISD::
isNormalStore(LSBase)) && "Not a reverse memop pattern!"
) ? void (0) : __assert_fail ("(ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && \"Not a reverse memop pattern!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15387, __extension__
__PRETTY_FUNCTION__))
;
15388
15389 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
15390 auto Mask = SVN->getMask();
15391 int i = 0;
15392 auto I = Mask.rbegin();
15393 auto E = Mask.rend();
15394
15395 for (; I != E; ++I) {
15396 if (*I != i)
15397 return false;
15398 i++;
15399 }
15400 return true;
15401 };
15402
15403 SelectionDAG &DAG = DCI.DAG;
15404 EVT VT = SVN->getValueType(0);
15405
15406 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
15407 return SDValue();
15408
15409 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
15410 // See comment in PPCVSXSwapRemoval.cpp.
15411 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
15412 if (!Subtarget.hasP9Vector())
15413 return SDValue();
15414
15415 if(!IsElementReverse(SVN))
15416 return SDValue();
15417
15418 if (LSBase->getOpcode() == ISD::LOAD) {
15419 // If the load return value 0 has more than one user except the
15420 // shufflevector instruction, it is not profitable to replace the
15421 // shufflevector with a reverse load.
15422 for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
15423 UI != UE; ++UI)
15424 if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
15425 return SDValue();
15426
15427 SDLoc dl(LSBase);
15428 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
15429 return DAG.getMemIntrinsicNode(
15430 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
15431 LSBase->getMemoryVT(), LSBase->getMemOperand());
15432 }
15433
15434 if (LSBase->getOpcode() == ISD::STORE) {
15435 // If there are other uses of the shuffle, the swap cannot be avoided.
15436 // Forcing the use of an X-Form (since swapped stores only have
15437 // X-Forms) without removing the swap is unprofitable.
15438 if (!SVN->hasOneUse())
15439 return SDValue();
15440
15441 SDLoc dl(LSBase);
15442 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
15443 LSBase->getBasePtr()};
15444 return DAG.getMemIntrinsicNode(
15445 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
15446 LSBase->getMemoryVT(), LSBase->getMemOperand());
15447 }
15448
15449 llvm_unreachable("Expected a load or store node here")::llvm::llvm_unreachable_internal("Expected a load or store node here"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15449)
;
15450}
15451
15452static bool isStoreConditional(SDValue Intrin, unsigned &StoreWidth) {
15453 unsigned IntrinsicID =
15454 cast<ConstantSDNode>(Intrin.getOperand(1))->getZExtValue();
15455 if (IntrinsicID == Intrinsic::ppc_stdcx)
15456 StoreWidth = 8;
15457 else if (IntrinsicID == Intrinsic::ppc_stwcx)
15458 StoreWidth = 4;
15459 else if (IntrinsicID == Intrinsic::ppc_sthcx)
15460 StoreWidth = 2;
15461 else if (IntrinsicID == Intrinsic::ppc_stbcx)
15462 StoreWidth = 1;
15463 else
15464 return false;
15465 return true;
15466}
15467
15468SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
15469 DAGCombinerInfo &DCI) const {
15470 SelectionDAG &DAG = DCI.DAG;
15471 SDLoc dl(N);
15472 switch (N->getOpcode()) {
15473 default: break;
15474 case ISD::ADD:
15475 return combineADD(N, DCI);
15476 case ISD::SHL:
15477 return combineSHL(N, DCI);
15478 case ISD::SRA:
15479 return combineSRA(N, DCI);
15480 case ISD::SRL:
15481 return combineSRL(N, DCI);
15482 case ISD::MUL:
15483 return combineMUL(N, DCI);
15484 case ISD::FMA:
15485 case PPCISD::FNMSUB:
15486 return combineFMALike(N, DCI);
15487 case PPCISD::SHL:
15488 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
15489 return N->getOperand(0);
15490 break;
15491 case PPCISD::SRL:
15492 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
15493 return N->getOperand(0);
15494 break;
15495 case PPCISD::SRA:
15496 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
15497 if (C->isZero() || // 0 >>s V -> 0.
15498 C->isAllOnes()) // -1 >>s V -> -1.
15499 return N->getOperand(0);
15500 }
15501 break;
15502 case ISD::SIGN_EXTEND:
15503 case ISD::ZERO_EXTEND:
15504 case ISD::ANY_EXTEND:
15505 return DAGCombineExtBoolTrunc(N, DCI);
15506 case ISD::TRUNCATE:
15507 return combineTRUNCATE(N, DCI);
15508 case ISD::SETCC:
15509 if (SDValue CSCC = combineSetCC(N, DCI))
15510 return CSCC;
15511 [[fallthrough]];
15512 case ISD::SELECT_CC:
15513 return DAGCombineTruncBoolExt(N, DCI);
15514 case ISD::SINT_TO_FP:
15515 case ISD::UINT_TO_FP:
15516 return combineFPToIntToFP(N, DCI);
15517 case ISD::VECTOR_SHUFFLE:
15518 if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
15519 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
15520 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
15521 }
15522 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
15523 case ISD::STORE: {
15524
15525 EVT Op1VT = N->getOperand(1).getValueType();
15526 unsigned Opcode = N->getOperand(1).getOpcode();
15527
15528 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
15529 SDValue Val= combineStoreFPToInt(N, DCI);
15530 if (Val)
15531 return Val;
15532 }
15533
15534 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
15535 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
15536 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
15537 if (Val)
15538 return Val;
15539 }
15540
15541 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
15542 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
15543 N->getOperand(1).getNode()->hasOneUse() &&
15544 (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
15545 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
15546
15547 // STBRX can only handle simple types and it makes no sense to store less
15548 // two bytes in byte-reversed order.
15549 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
15550 if (mVT.isExtended() || mVT.getSizeInBits() < 16)
15551 break;
15552
15553 SDValue BSwapOp = N->getOperand(1).getOperand(0);
15554 // Do an any-extend to 32-bits if this is a half-word input.
15555 if (BSwapOp.getValueType() == MVT::i16)
15556 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
15557
15558 // If the type of BSWAP operand is wider than stored memory width
15559 // it need to be shifted to the right side before STBRX.
15560 if (Op1VT.bitsGT(mVT)) {
15561 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
15562 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
15563 DAG.getConstant(Shift, dl, MVT::i32));
15564 // Need to truncate if this is a bswap of i64 stored as i32/i16.
15565 if (Op1VT == MVT::i64)
15566 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
15567 }
15568
15569 SDValue Ops[] = {
15570 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
15571 };
15572 return
15573 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
15574 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
15575 cast<StoreSDNode>(N)->getMemOperand());
15576 }
15577
15578 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0>
15579 // So it can increase the chance of CSE constant construction.
15580 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
15581 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
15582 // Need to sign-extended to 64-bits to handle negative values.
15583 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
15584 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
15585 MemVT.getSizeInBits());
15586 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
15587
15588 // DAG.getTruncStore() can't be used here because it doesn't accept
15589 // the general (base + offset) addressing mode.
15590 // So we use UpdateNodeOperands and setTruncatingStore instead.
15591 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
15592 N->getOperand(3));
15593 cast<StoreSDNode>(N)->setTruncatingStore(true);
15594 return SDValue(N, 0);
15595 }
15596
15597 // For little endian, VSX stores require generating xxswapd/lxvd2x.
15598 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15599 if (Op1VT.isSimple()) {
15600 MVT StoreVT = Op1VT.getSimpleVT();
15601 if (Subtarget.needsSwapsForVSXMemOps() &&
15602 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
15603 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
15604 return expandVSXStoreForLE(N, DCI);
15605 }
15606 break;
15607 }
15608 case ISD::LOAD: {
15609 LoadSDNode *LD = cast<LoadSDNode>(N);
15610 EVT VT = LD->getValueType(0);
15611
15612 // For little endian, VSX loads require generating lxvd2x/xxswapd.
15613 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15614 if (VT.isSimple()) {
15615 MVT LoadVT = VT.getSimpleVT();
15616 if (Subtarget.needsSwapsForVSXMemOps() &&
15617 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15618 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15619 return expandVSXLoadForLE(N, DCI);
15620 }
15621
15622 // We sometimes end up with a 64-bit integer load, from which we extract
15623 // two single-precision floating-point numbers. This happens with
15624 // std::complex<float>, and other similar structures, because of the way we
15625 // canonicalize structure copies. However, if we lack direct moves,
15626 // then the final bitcasts from the extracted integer values to the
15627 // floating-point numbers turn into store/load pairs. Even with direct moves,
15628 // just loading the two floating-point numbers is likely better.
15629 auto ReplaceTwoFloatLoad = [&]() {
15630 if (VT != MVT::i64)
15631 return false;
15632
15633 if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15634 LD->isVolatile())
15635 return false;
15636
15637 // We're looking for a sequence like this:
15638 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15639 // t16: i64 = srl t13, Constant:i32<32>
15640 // t17: i32 = truncate t16
15641 // t18: f32 = bitcast t17
15642 // t19: i32 = truncate t13
15643 // t20: f32 = bitcast t19
15644
15645 if (!LD->hasNUsesOfValue(2, 0))
15646 return false;
15647
15648 auto UI = LD->use_begin();
15649 while (UI.getUse().getResNo() != 0) ++UI;
15650 SDNode *Trunc = *UI++;
15651 while (UI.getUse().getResNo() != 0) ++UI;
15652 SDNode *RightShift = *UI;
15653 if (Trunc->getOpcode() != ISD::TRUNCATE)
15654 std::swap(Trunc, RightShift);
15655
15656 if (Trunc->getOpcode() != ISD::TRUNCATE ||
15657 Trunc->getValueType(0) != MVT::i32 ||
15658 !Trunc->hasOneUse())
15659 return false;
15660 if (RightShift->getOpcode() != ISD::SRL ||
15661 !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15662 RightShift->getConstantOperandVal(1) != 32 ||
15663 !RightShift->hasOneUse())
15664 return false;
15665
15666 SDNode *Trunc2 = *RightShift->use_begin();
15667 if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15668 Trunc2->getValueType(0) != MVT::i32 ||
15669 !Trunc2->hasOneUse())
15670 return false;
15671
15672 SDNode *Bitcast = *Trunc->use_begin();
15673 SDNode *Bitcast2 = *Trunc2->use_begin();
15674
15675 if (Bitcast->getOpcode() != ISD::BITCAST ||
15676 Bitcast->getValueType(0) != MVT::f32)
15677 return false;
15678 if (Bitcast2->getOpcode() != ISD::BITCAST ||
15679 Bitcast2->getValueType(0) != MVT::f32)
15680 return false;
15681
15682 if (Subtarget.isLittleEndian())
15683 std::swap(Bitcast, Bitcast2);
15684
15685 // Bitcast has the second float (in memory-layout order) and Bitcast2
15686 // has the first one.
15687
15688 SDValue BasePtr = LD->getBasePtr();
15689 if (LD->isIndexed()) {
15690 assert(LD->getAddressingMode() == ISD::PRE_INC &&(static_cast <bool> (LD->getAddressingMode() == ISD::
PRE_INC && "Non-pre-inc AM on PPC?") ? void (0) : __assert_fail
("LD->getAddressingMode() == ISD::PRE_INC && \"Non-pre-inc AM on PPC?\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15691, __extension__
__PRETTY_FUNCTION__))
15691 "Non-pre-inc AM on PPC?")(static_cast <bool> (LD->getAddressingMode() == ISD::
PRE_INC && "Non-pre-inc AM on PPC?") ? void (0) : __assert_fail
("LD->getAddressingMode() == ISD::PRE_INC && \"Non-pre-inc AM on PPC?\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 15691, __extension__
__PRETTY_FUNCTION__))
;
15692 BasePtr =
15693 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15694 LD->getOffset());
15695 }
15696
15697 auto MMOFlags =
15698 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15699 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15700 LD->getPointerInfo(), LD->getAlign(),
15701 MMOFlags, LD->getAAInfo());
15702 SDValue AddPtr =
15703 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15704 BasePtr, DAG.getIntPtrConstant(4, dl));
15705 SDValue FloatLoad2 = DAG.getLoad(
15706 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15707 LD->getPointerInfo().getWithOffset(4),
15708 commonAlignment(LD->getAlign(), 4), MMOFlags, LD->getAAInfo());
15709
15710 if (LD->isIndexed()) {
15711 // Note that DAGCombine should re-form any pre-increment load(s) from
15712 // what is produced here if that makes sense.
15713 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15714 }
15715
15716 DCI.CombineTo(Bitcast2, FloatLoad);
15717 DCI.CombineTo(Bitcast, FloatLoad2);
15718
15719 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15720 SDValue(FloatLoad2.getNode(), 1));
15721 return true;
15722 };
15723
15724 if (ReplaceTwoFloatLoad())
15725 return SDValue(N, 0);
15726
15727 EVT MemVT = LD->getMemoryVT();
15728 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15729 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15730 if (LD->isUnindexed() && VT.isVector() &&
15731 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15732 // P8 and later hardware should just use LOAD.
15733 !Subtarget.hasP8Vector() &&
15734 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15735 VT == MVT::v4f32))) &&
15736 LD->getAlign() < ABIAlignment) {
15737 // This is a type-legal unaligned Altivec load.
15738 SDValue Chain = LD->getChain();
15739 SDValue Ptr = LD->getBasePtr();
15740 bool isLittleEndian = Subtarget.isLittleEndian();
15741
15742 // This implements the loading of unaligned vectors as described in
15743 // the venerable Apple Velocity Engine overview. Specifically:
15744 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15745 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15746 //
15747 // The general idea is to expand a sequence of one or more unaligned
15748 // loads into an alignment-based permutation-control instruction (lvsl
15749 // or lvsr), a series of regular vector loads (which always truncate
15750 // their input address to an aligned address), and a series of
15751 // permutations. The results of these permutations are the requested
15752 // loaded values. The trick is that the last "extra" load is not taken
15753 // from the address you might suspect (sizeof(vector) bytes after the
15754 // last requested load), but rather sizeof(vector) - 1 bytes after the
15755 // last requested vector. The point of this is to avoid a page fault if
15756 // the base address happened to be aligned. This works because if the
15757 // base address is aligned, then adding less than a full vector length
15758 // will cause the last vector in the sequence to be (re)loaded.
15759 // Otherwise, the next vector will be fetched as you might suspect was
15760 // necessary.
15761
15762 // We might be able to reuse the permutation generation from
15763 // a different base address offset from this one by an aligned amount.
15764 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15765 // optimization later.
15766 Intrinsic::ID Intr, IntrLD, IntrPerm;
15767 MVT PermCntlTy, PermTy, LDTy;
15768 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15769 : Intrinsic::ppc_altivec_lvsl;
15770 IntrLD = Intrinsic::ppc_altivec_lvx;
15771 IntrPerm = Intrinsic::ppc_altivec_vperm;
15772 PermCntlTy = MVT::v16i8;
15773 PermTy = MVT::v4i32;
15774 LDTy = MVT::v4i32;
15775
15776 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15777
15778 // Create the new MMO for the new base load. It is like the original MMO,
15779 // but represents an area in memory almost twice the vector size centered
15780 // on the original address. If the address is unaligned, we might start
15781 // reading up to (sizeof(vector)-1) bytes below the address of the
15782 // original unaligned load.
15783 MachineFunction &MF = DAG.getMachineFunction();
15784 MachineMemOperand *BaseMMO =
15785 MF.getMachineMemOperand(LD->getMemOperand(),
15786 -(int64_t)MemVT.getStoreSize()+1,
15787 2*MemVT.getStoreSize()-1);
15788
15789 // Create the new base load.
15790 SDValue LDXIntID =
15791 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15792 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15793 SDValue BaseLoad =
15794 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15795 DAG.getVTList(PermTy, MVT::Other),
15796 BaseLoadOps, LDTy, BaseMMO);
15797
15798 // Note that the value of IncOffset (which is provided to the next
15799 // load's pointer info offset value, and thus used to calculate the
15800 // alignment), and the value of IncValue (which is actually used to
15801 // increment the pointer value) are different! This is because we
15802 // require the next load to appear to be aligned, even though it
15803 // is actually offset from the base pointer by a lesser amount.
15804 int IncOffset = VT.getSizeInBits() / 8;
15805 int IncValue = IncOffset;
15806
15807 // Walk (both up and down) the chain looking for another load at the real
15808 // (aligned) offset (the alignment of the other load does not matter in
15809 // this case). If found, then do not use the offset reduction trick, as
15810 // that will prevent the loads from being later combined (as they would
15811 // otherwise be duplicates).
15812 if (!findConsecutiveLoad(LD, DAG))
15813 --IncValue;
15814
15815 SDValue Increment =
15816 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15817 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15818
15819 MachineMemOperand *ExtraMMO =
15820 MF.getMachineMemOperand(LD->getMemOperand(),
15821 1, 2*MemVT.getStoreSize()-1);
15822 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15823 SDValue ExtraLoad =
15824 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15825 DAG.getVTList(PermTy, MVT::Other),
15826 ExtraLoadOps, LDTy, ExtraMMO);
15827
15828 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15829 BaseLoad.getValue(1), ExtraLoad.getValue(1));
15830
15831 // Because vperm has a big-endian bias, we must reverse the order
15832 // of the input vectors and complement the permute control vector
15833 // when generating little endian code. We have already handled the
15834 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15835 // and ExtraLoad here.
15836 SDValue Perm;
15837 if (isLittleEndian)
15838 Perm = BuildIntrinsicOp(IntrPerm,
15839 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15840 else
15841 Perm = BuildIntrinsicOp(IntrPerm,
15842 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15843
15844 if (VT != PermTy)
15845 Perm = Subtarget.hasAltivec()
15846 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15847 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15848 DAG.getTargetConstant(1, dl, MVT::i64));
15849 // second argument is 1 because this rounding
15850 // is always exact.
15851
15852 // The output of the permutation is our loaded result, the TokenFactor is
15853 // our new chain.
15854 DCI.CombineTo(N, Perm, TF);
15855 return SDValue(N, 0);
15856 }
15857 }
15858 break;
15859 case ISD::INTRINSIC_WO_CHAIN: {
15860 bool isLittleEndian = Subtarget.isLittleEndian();
15861 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15862 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15863 : Intrinsic::ppc_altivec_lvsl);
15864 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15865 SDValue Add = N->getOperand(1);
15866
15867 int Bits = 4 /* 16 byte alignment */;
15868
15869 if (DAG.MaskedValueIsZero(Add->getOperand(1),
15870 APInt::getAllOnes(Bits /* alignment */)
15871 .zext(Add.getScalarValueSizeInBits()))) {
15872 SDNode *BasePtr = Add->getOperand(0).getNode();
15873 for (SDNode *U : BasePtr->uses()) {
15874 if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15875 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) {
15876 // We've found another LVSL/LVSR, and this address is an aligned
15877 // multiple of that one. The results will be the same, so use the
15878 // one we've just found instead.
15879
15880 return SDValue(U, 0);
15881 }
15882 }
15883 }
15884
15885 if (isa<ConstantSDNode>(Add->getOperand(1))) {
15886 SDNode *BasePtr = Add->getOperand(0).getNode();
15887 for (SDNode *U : BasePtr->uses()) {
15888 if (U->getOpcode() == ISD::ADD &&
15889 isa<ConstantSDNode>(U->getOperand(1)) &&
15890 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15891 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) %
15892 (1ULL << Bits) ==
15893 0) {
15894 SDNode *OtherAdd = U;
15895 for (SDNode *V : OtherAdd->uses()) {
15896 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15897 cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() ==
15898 IID) {
15899 return SDValue(V, 0);
15900 }
15901 }
15902 }
15903 }
15904 }
15905 }
15906
15907 // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15908 // Expose the vabsduw/h/b opportunity for down stream
15909 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15910 (IID == Intrinsic::ppc_altivec_vmaxsw ||
15911 IID == Intrinsic::ppc_altivec_vmaxsh ||
15912 IID == Intrinsic::ppc_altivec_vmaxsb)) {
15913 SDValue V1 = N->getOperand(1);
15914 SDValue V2 = N->getOperand(2);
15915 if ((V1.getSimpleValueType() == MVT::v4i32 ||
15916 V1.getSimpleValueType() == MVT::v8i16 ||
15917 V1.getSimpleValueType() == MVT::v16i8) &&
15918 V1.getSimpleValueType() == V2.getSimpleValueType()) {
15919 // (0-a, a)
15920 if (V1.getOpcode() == ISD::SUB &&
15921 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15922 V1.getOperand(1) == V2) {
15923 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15924 }
15925 // (a, 0-a)
15926 if (V2.getOpcode() == ISD::SUB &&
15927 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15928 V2.getOperand(1) == V1) {
15929 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15930 }
15931 // (x-y, y-x)
15932 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15933 V1.getOperand(0) == V2.getOperand(1) &&
15934 V1.getOperand(1) == V2.getOperand(0)) {
15935 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15936 }
15937 }
15938 }
15939 }
15940
15941 break;
15942 case ISD::INTRINSIC_W_CHAIN:
15943 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15944 default:
15945 break;
15946 case Intrinsic::ppc_altivec_vsum4sbs:
15947 case Intrinsic::ppc_altivec_vsum4shs:
15948 case Intrinsic::ppc_altivec_vsum4ubs: {
15949 // These sum-across intrinsics only have a chain due to the side effect
15950 // that they may set the SAT bit. If we know the SAT bit will not be set
15951 // for some inputs, we can replace any uses of their chain with the input
15952 // chain.
15953 if (BuildVectorSDNode *BVN =
15954 dyn_cast<BuildVectorSDNode>(N->getOperand(3))) {
15955 APInt APSplatBits, APSplatUndef;
15956 unsigned SplatBitSize;
15957 bool HasAnyUndefs;
15958 bool BVNIsConstantSplat = BVN->isConstantSplat(
15959 APSplatBits, APSplatUndef, SplatBitSize, HasAnyUndefs, 0,
15960 !Subtarget.isLittleEndian());
15961 // If the constant splat vector is 0, the SAT bit will not be set.
15962 if (BVNIsConstantSplat && APSplatBits == 0)
15963 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), N->getOperand(0));
15964 }
15965 return SDValue();
15966 }
15967 case Intrinsic::ppc_vsx_lxvw4x:
15968 case Intrinsic::ppc_vsx_lxvd2x:
15969 // For little endian, VSX loads require generating lxvd2x/xxswapd.
15970 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15971 if (Subtarget.needsSwapsForVSXMemOps())
15972 return expandVSXLoadForLE(N, DCI);
15973 break;
15974 }
15975 break;
15976 case ISD::INTRINSIC_VOID:
15977 // For little endian, VSX stores require generating xxswapd/stxvd2x.
15978 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15979 if (Subtarget.needsSwapsForVSXMemOps()) {
15980 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15981 default:
15982 break;
15983 case Intrinsic::ppc_vsx_stxvw4x:
15984 case Intrinsic::ppc_vsx_stxvd2x:
15985 return expandVSXStoreForLE(N, DCI);
15986 }
15987 }
15988 break;
15989 case ISD::BSWAP: {
15990 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15991 // For subtargets without LDBRX, we can still do better than the default
15992 // expansion even for 64-bit BSWAP (LOAD).
15993 bool Is64BitBswapOn64BitTgt =
15994 Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15995 bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15996 N->getOperand(0).hasOneUse();
15997 if (IsSingleUseNormalLd &&
15998 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15999 (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
16000 SDValue Load = N->getOperand(0);
16001 LoadSDNode *LD = cast<LoadSDNode>(Load);
16002 // Create the byte-swapping load.
16003 SDValue Ops[] = {
16004 LD->getChain(), // Chain
16005 LD->getBasePtr(), // Ptr
16006 DAG.getValueType(N->getValueType(0)) // VT
16007 };
16008 SDValue BSLoad =
16009 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
16010 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
16011 MVT::i64 : MVT::i32, MVT::Other),
16012 Ops, LD->getMemoryVT(), LD->getMemOperand());
16013
16014 // If this is an i16 load, insert the truncate.
16015 SDValue ResVal = BSLoad;
16016 if (N->getValueType(0) == MVT::i16)
16017 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
16018
16019 // First, combine the bswap away. This makes the value produced by the
16020 // load dead.
16021 DCI.CombineTo(N, ResVal);
16022
16023 // Next, combine the load away, we give it a bogus result value but a real
16024 // chain result. The result value is dead because the bswap is dead.
16025 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
16026
16027 // Return N so it doesn't get rechecked!
16028 return SDValue(N, 0);
16029 }
16030 // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
16031 // before legalization so that the BUILD_PAIR is handled correctly.
16032 if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
16033 !IsSingleUseNormalLd)
16034 return SDValue();
16035 LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
16036
16037 // Can't split volatile or atomic loads.
16038 if (!LD->isSimple())
16039 return SDValue();
16040 SDValue BasePtr = LD->getBasePtr();
16041 SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
16042 LD->getPointerInfo(), LD->getAlign());
16043 Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
16044 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
16045 DAG.getIntPtrConstant(4, dl));
16046 MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
16047 LD->getMemOperand(), 4, 4);
16048 SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
16049 Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
16050 SDValue Res;
16051 if (Subtarget.isLittleEndian())
16052 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
16053 else
16054 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
16055 SDValue TF =
16056 DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16057 Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
16058 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
16059 return Res;
16060 }
16061 case PPCISD::VCMP:
16062 // If a VCMP_rec node already exists with exactly the same operands as this
16063 // node, use its result instead of this node (VCMP_rec computes both a CR6
16064 // and a normal output).
16065 //
16066 if (!N->getOperand(0).hasOneUse() &&
16067 !N->getOperand(1).hasOneUse() &&
16068 !N->getOperand(2).hasOneUse()) {
16069
16070 // Scan all of the users of the LHS, looking for VCMP_rec's that match.
16071 SDNode *VCMPrecNode = nullptr;
16072
16073 SDNode *LHSN = N->getOperand(0).getNode();
16074 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
16075 UI != E; ++UI)
16076 if (UI->getOpcode() == PPCISD::VCMP_rec &&
16077 UI->getOperand(1) == N->getOperand(1) &&
16078 UI->getOperand(2) == N->getOperand(2) &&
16079 UI->getOperand(0) == N->getOperand(0)) {
16080 VCMPrecNode = *UI;
16081 break;
16082 }
16083
16084 // If there is no VCMP_rec node, or if the flag value has a single use,
16085 // don't transform this.
16086 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
16087 break;
16088
16089 // Look at the (necessarily single) use of the flag value. If it has a
16090 // chain, this transformation is more complex. Note that multiple things
16091 // could use the value result, which we should ignore.
16092 SDNode *FlagUser = nullptr;
16093 for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
16094 FlagUser == nullptr; ++UI) {
16095 assert(UI != VCMPrecNode->use_end() && "Didn't find user!")(static_cast <bool> (UI != VCMPrecNode->use_end() &&
"Didn't find user!") ? void (0) : __assert_fail ("UI != VCMPrecNode->use_end() && \"Didn't find user!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 16095, __extension__
__PRETTY_FUNCTION__))
;
16096 SDNode *User = *UI;
16097 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
16098 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
16099 FlagUser = User;
16100 break;
16101 }
16102 }
16103 }
16104
16105 // If the user is a MFOCRF instruction, we know this is safe.
16106 // Otherwise we give up for right now.
16107 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
16108 return SDValue(VCMPrecNode, 0);
16109 }
16110 break;
16111 case ISD::BR_CC: {
16112 // If this is a branch on an altivec predicate comparison, lower this so
16113 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
16114 // lowering is done pre-legalize, because the legalizer lowers the predicate
16115 // compare down to code that is difficult to reassemble.
16116 // This code also handles branches that depend on the result of a store
16117 // conditional.
16118 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
16119 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
16120
16121 int CompareOpc;
16122 bool isDot;
16123
16124 if (!isa<ConstantSDNode>(RHS) || (CC != ISD::SETEQ && CC != ISD::SETNE))
16125 break;
16126
16127 // Since we are doing this pre-legalize, the RHS can be a constant of
16128 // arbitrary bitwidth which may cause issues when trying to get the value
16129 // from the underlying APInt.
16130 auto RHSAPInt = cast<ConstantSDNode>(RHS)->getAPIntValue();
16131 if (!RHSAPInt.isIntN(64))
16132 break;
16133
16134 unsigned Val = RHSAPInt.getZExtValue();
16135 auto isImpossibleCompare = [&]() {
16136 // If this is a comparison against something other than 0/1, then we know
16137 // that the condition is never/always true.
16138 if (Val != 0 && Val != 1) {
16139 if (CC == ISD::SETEQ) // Cond never true, remove branch.
16140 return N->getOperand(0);
16141 // Always !=, turn it into an unconditional branch.
16142 return DAG.getNode(ISD::BR, dl, MVT::Other,
16143 N->getOperand(0), N->getOperand(4));
16144 }
16145 return SDValue();
16146 };
16147 // Combine branches fed by store conditional instructions (st[bhwd]cx).
16148 unsigned StoreWidth = 0;
16149 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
16150 isStoreConditional(LHS, StoreWidth)) {
16151 if (SDValue Impossible = isImpossibleCompare())
16152 return Impossible;
16153 PPC::Predicate CompOpc;
16154 // eq 0 => ne
16155 // ne 0 => eq
16156 // eq 1 => eq
16157 // ne 1 => ne
16158 if (Val == 0)
16159 CompOpc = CC == ISD::SETEQ ? PPC::PRED_NE : PPC::PRED_EQ;
16160 else
16161 CompOpc = CC == ISD::SETEQ ? PPC::PRED_EQ : PPC::PRED_NE;
16162
16163 SDValue Ops[] = {LHS.getOperand(0), LHS.getOperand(2), LHS.getOperand(3),
16164 DAG.getConstant(StoreWidth, dl, MVT::i32)};
16165 auto *MemNode = cast<MemSDNode>(LHS);
16166 SDValue ConstSt = DAG.getMemIntrinsicNode(
16167 PPCISD::STORE_COND, dl,
16168 DAG.getVTList(MVT::i32, MVT::Other, MVT::Glue), Ops,
16169 MemNode->getMemoryVT(), MemNode->getMemOperand());
16170
16171 SDValue InChain;
16172 // Unchain the branch from the original store conditional.
16173 if (N->getOperand(0) == LHS.getValue(1))
16174 InChain = LHS.getOperand(0);
16175 else if (N->getOperand(0).getOpcode() == ISD::TokenFactor) {
16176 SmallVector<SDValue, 4> InChains;
16177 SDValue InTF = N->getOperand(0);
16178 for (int i = 0, e = InTF.getNumOperands(); i < e; i++)
16179 if (InTF.getOperand(i) != LHS.getValue(1))
16180 InChains.push_back(InTF.getOperand(i));
16181 InChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, InChains);
16182 }
16183
16184 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, InChain,
16185 DAG.getConstant(CompOpc, dl, MVT::i32),
16186 DAG.getRegister(PPC::CR0, MVT::i32), N->getOperand(4),
16187 ConstSt.getValue(2));
16188 }
16189
16190 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
16191 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
16192 assert(isDot && "Can't compare against a vector result!")(static_cast <bool> (isDot && "Can't compare against a vector result!"
) ? void (0) : __assert_fail ("isDot && \"Can't compare against a vector result!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 16192, __extension__
__PRETTY_FUNCTION__))
;
16193
16194 if (SDValue Impossible = isImpossibleCompare())
16195 return Impossible;
16196
16197 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
16198 // Create the PPCISD altivec 'dot' comparison node.
16199 SDValue Ops[] = {
16200 LHS.getOperand(2), // LHS of compare
16201 LHS.getOperand(3), // RHS of compare
16202 DAG.getConstant(CompareOpc, dl, MVT::i32)
16203 };
16204 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
16205 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
16206
16207 // Unpack the result based on how the target uses it.
16208 PPC::Predicate CompOpc;
16209 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
16210 default: // Can't happen, don't crash on invalid number though.
16211 case 0: // Branch on the value of the EQ bit of CR6.
16212 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
16213 break;
16214 case 1: // Branch on the inverted value of the EQ bit of CR6.
16215 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
16216 break;
16217 case 2: // Branch on the value of the LT bit of CR6.
16218 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
16219 break;
16220 case 3: // Branch on the inverted value of the LT bit of CR6.
16221 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
16222 break;
16223 }
16224
16225 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
16226 DAG.getConstant(CompOpc, dl, MVT::i32),
16227 DAG.getRegister(PPC::CR6, MVT::i32),
16228 N->getOperand(4), CompNode.getValue(1));
16229 }
16230 break;
16231 }
16232 case ISD::BUILD_VECTOR:
16233 return DAGCombineBuildVector(N, DCI);
16234 }
16235
16236 return SDValue();
16237}
16238
16239SDValue
16240PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
16241 SelectionDAG &DAG,
16242 SmallVectorImpl<SDNode *> &Created) const {
16243 // fold (sdiv X, pow2)
16244 EVT VT = N->getValueType(0);
16245 if (VT == MVT::i64 && !Subtarget.isPPC64())
16246 return SDValue();
16247 if ((VT != MVT::i32 && VT != MVT::i64) ||
16248 !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
16249 return SDValue();
16250
16251 SDLoc DL(N);
16252 SDValue N0 = N->getOperand(0);
16253
16254 bool IsNegPow2 = Divisor.isNegatedPowerOf2();
16255 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countr_zero();
16256 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
16257
16258 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
16259 Created.push_back(Op.getNode());
16260
16261 if (IsNegPow2) {
16262 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
16263 Created.push_back(Op.getNode());
16264 }
16265
16266 return Op;
16267}
16268
16269//===----------------------------------------------------------------------===//
16270// Inline Assembly Support
16271//===----------------------------------------------------------------------===//
16272
16273void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
16274 KnownBits &Known,
16275 const APInt &DemandedElts,
16276 const SelectionDAG &DAG,
16277 unsigned Depth) const {
16278 Known.resetAll();
16279 switch (Op.getOpcode()) {
16280 default: break;
16281 case PPCISD::LBRX: {
16282 // lhbrx is known to have the top bits cleared out.
16283 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
16284 Known.Zero = 0xFFFF0000;
16285 break;
16286 }
16287 case ISD::INTRINSIC_WO_CHAIN: {
16288 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
16289 default: break;
16290 case Intrinsic::ppc_altivec_vcmpbfp_p:
16291 case Intrinsic::ppc_altivec_vcmpeqfp_p:
16292 case Intrinsic::ppc_altivec_vcmpequb_p:
16293 case Intrinsic::ppc_altivec_vcmpequh_p:
16294 case Intrinsic::ppc_altivec_vcmpequw_p:
16295 case Intrinsic::ppc_altivec_vcmpequd_p:
16296 case Intrinsic::ppc_altivec_vcmpequq_p:
16297 case Intrinsic::ppc_altivec_vcmpgefp_p:
16298 case Intrinsic::ppc_altivec_vcmpgtfp_p:
16299 case Intrinsic::ppc_altivec_vcmpgtsb_p:
16300 case Intrinsic::ppc_altivec_vcmpgtsh_p:
16301 case Intrinsic::ppc_altivec_vcmpgtsw_p:
16302 case Intrinsic::ppc_altivec_vcmpgtsd_p:
16303 case Intrinsic::ppc_altivec_vcmpgtsq_p:
16304 case Intrinsic::ppc_altivec_vcmpgtub_p:
16305 case Intrinsic::ppc_altivec_vcmpgtuh_p:
16306 case Intrinsic::ppc_altivec_vcmpgtuw_p:
16307 case Intrinsic::ppc_altivec_vcmpgtud_p:
16308 case Intrinsic::ppc_altivec_vcmpgtuq_p:
16309 Known.Zero = ~1U; // All bits but the low one are known to be zero.
16310 break;
16311 }
16312 break;
16313 }
16314 case ISD::INTRINSIC_W_CHAIN: {
16315 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
16316 default:
16317 break;
16318 case Intrinsic::ppc_load2r:
16319 // Top bits are cleared for load2r (which is the same as lhbrx).
16320 Known.Zero = 0xFFFF0000;
16321 break;
16322 }
16323 break;
16324 }
16325 }
16326}
16327
16328Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
16329 switch (Subtarget.getCPUDirective()) {
16330 default: break;
16331 case PPC::DIR_970:
16332 case PPC::DIR_PWR4:
16333 case PPC::DIR_PWR5:
16334 case PPC::DIR_PWR5X:
16335 case PPC::DIR_PWR6:
16336 case PPC::DIR_PWR6X:
16337 case PPC::DIR_PWR7:
16338 case PPC::DIR_PWR8:
16339 case PPC::DIR_PWR9:
16340 case PPC::DIR_PWR10:
16341 case PPC::DIR_PWR_FUTURE: {
16342 if (!ML)
16343 break;
16344
16345 if (!DisableInnermostLoopAlign32) {
16346 // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
16347 // so that we can decrease cache misses and branch-prediction misses.
16348 // Actual alignment of the loop will depend on the hotness check and other
16349 // logic in alignBlocks.
16350 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
16351 return Align(32);
16352 }
16353
16354 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
16355
16356 // For small loops (between 5 and 8 instructions), align to a 32-byte
16357 // boundary so that the entire loop fits in one instruction-cache line.
16358 uint64_t LoopSize = 0;
16359 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
16360 for (const MachineInstr &J : **I) {
16361 LoopSize += TII->getInstSizeInBytes(J);
16362 if (LoopSize > 32)
16363 break;
16364 }
16365
16366 if (LoopSize > 16 && LoopSize <= 32)
16367 return Align(32);
16368
16369 break;
16370 }
16371 }
16372
16373 return TargetLowering::getPrefLoopAlignment(ML);
16374}
16375
16376/// getConstraintType - Given a constraint, return the type of
16377/// constraint it is for this target.
16378PPCTargetLowering::ConstraintType
16379PPCTargetLowering::getConstraintType(StringRef Constraint) const {
16380 if (Constraint.size() == 1) {
16381 switch (Constraint[0]) {
16382 default: break;
16383 case 'b':
16384 case 'r':
16385 case 'f':
16386 case 'd':
16387 case 'v':
16388 case 'y':
16389 return C_RegisterClass;
16390 case 'Z':
16391 // FIXME: While Z does indicate a memory constraint, it specifically
16392 // indicates an r+r address (used in conjunction with the 'y' modifier
16393 // in the replacement string). Currently, we're forcing the base
16394 // register to be r0 in the asm printer (which is interpreted as zero)
16395 // and forming the complete address in the second register. This is
16396 // suboptimal.
16397 return C_Memory;
16398 }
16399 } else if (Constraint == "wc") { // individual CR bits.
16400 return C_RegisterClass;
16401 } else if (Constraint == "wa" || Constraint == "wd" ||
16402 Constraint == "wf" || Constraint == "ws" ||
16403 Constraint == "wi" || Constraint == "ww") {
16404 return C_RegisterClass; // VSX registers.
16405 }
16406 return TargetLowering::getConstraintType(Constraint);
16407}
16408
16409/// Examine constraint type and operand type and determine a weight value.
16410/// This object must already have been set up with the operand type
16411/// and the current alternative constraint selected.
16412TargetLowering::ConstraintWeight
16413PPCTargetLowering::getSingleConstraintMatchWeight(
16414 AsmOperandInfo &info, const char *constraint) const {
16415 ConstraintWeight weight = CW_Invalid;
16416 Value *CallOperandVal = info.CallOperandVal;
16417 // If we don't have a value, we can't do a match,
16418 // but allow it at the lowest weight.
16419 if (!CallOperandVal)
16420 return CW_Default;
16421 Type *type = CallOperandVal->getType();
16422
16423 // Look at the constraint type.
16424 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
16425 return CW_Register; // an individual CR bit.
16426 else if ((StringRef(constraint) == "wa" ||
16427 StringRef(constraint) == "wd" ||
16428 StringRef(constraint) == "wf") &&
16429 type->isVectorTy())
16430 return CW_Register;
16431 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
16432 return CW_Register; // just hold 64-bit integers data.
16433 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
16434 return CW_Register;
16435 else if (StringRef(constraint) == "ww" && type->isFloatTy())
16436 return CW_Register;
16437
16438 switch (*constraint) {
16439 default:
16440 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16441 break;
16442 case 'b':
16443 if (type->isIntegerTy())
16444 weight = CW_Register;
16445 break;
16446 case 'f':
16447 if (type->isFloatTy())
16448 weight = CW_Register;
16449 break;
16450 case 'd':
16451 if (type->isDoubleTy())
16452 weight = CW_Register;
16453 break;
16454 case 'v':
16455 if (type->isVectorTy())
16456 weight = CW_Register;
16457 break;
16458 case 'y':
16459 weight = CW_Register;
16460 break;
16461 case 'Z':
16462 weight = CW_Memory;
16463 break;
16464 }
16465 return weight;
16466}
16467
16468std::pair<unsigned, const TargetRegisterClass *>
16469PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
16470 StringRef Constraint,
16471 MVT VT) const {
16472 if (Constraint.size() == 1) {
16473 // GCC RS6000 Constraint Letters
16474 switch (Constraint[0]) {
16475 case 'b': // R1-R31
16476 if (VT == MVT::i64 && Subtarget.isPPC64())
16477 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
16478 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
16479 case 'r': // R0-R31
16480 if (VT == MVT::i64 && Subtarget.isPPC64())
16481 return std::make_pair(0U, &PPC::G8RCRegClass);
16482 return std::make_pair(0U, &PPC::GPRCRegClass);
16483 // 'd' and 'f' constraints are both defined to be "the floating point
16484 // registers", where one is for 32-bit and the other for 64-bit. We don't
16485 // really care overly much here so just give them all the same reg classes.
16486 case 'd':
16487 case 'f':
16488 if (Subtarget.hasSPE()) {
16489 if (VT == MVT::f32 || VT == MVT::i32)
16490 return std::make_pair(0U, &PPC::GPRCRegClass);
16491 if (VT == MVT::f64 || VT == MVT::i64)
16492 return std::make_pair(0U, &PPC::SPERCRegClass);
16493 } else {
16494 if (VT == MVT::f32 || VT == MVT::i32)
16495 return std::make_pair(0U, &PPC::F4RCRegClass);
16496 if (VT == MVT::f64 || VT == MVT::i64)
16497 return std::make_pair(0U, &PPC::F8RCRegClass);
16498 }
16499 break;
16500 case 'v':
16501 if (Subtarget.hasAltivec() && VT.isVector())
16502 return std::make_pair(0U, &PPC::VRRCRegClass);
16503 else if (Subtarget.hasVSX())
16504 // Scalars in Altivec registers only make sense with VSX.
16505 return std::make_pair(0U, &PPC::VFRCRegClass);
16506 break;
16507 case 'y': // crrc
16508 return std::make_pair(0U, &PPC::CRRCRegClass);
16509 }
16510 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
16511 // An individual CR bit.
16512 return std::make_pair(0U, &PPC::CRBITRCRegClass);
16513 } else if ((Constraint == "wa" || Constraint == "wd" ||
16514 Constraint == "wf" || Constraint == "wi") &&
16515 Subtarget.hasVSX()) {
16516 // A VSX register for either a scalar (FP) or vector. There is no
16517 // support for single precision scalars on subtargets prior to Power8.
16518 if (VT.isVector())
16519 return std::make_pair(0U, &PPC::VSRCRegClass);
16520 if (VT == MVT::f32 && Subtarget.hasP8Vector())
16521 return std::make_pair(0U, &PPC::VSSRCRegClass);
16522 return std::make_pair(0U, &PPC::VSFRCRegClass);
16523 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
16524 if (VT == MVT::f32 && Subtarget.hasP8Vector())
16525 return std::make_pair(0U, &PPC::VSSRCRegClass);
16526 else
16527 return std::make_pair(0U, &PPC::VSFRCRegClass);
16528 } else if (Constraint == "lr") {
16529 if (VT == MVT::i64)
16530 return std::make_pair(0U, &PPC::LR8RCRegClass);
16531 else
16532 return std::make_pair(0U, &PPC::LRRCRegClass);
16533 }
16534
16535 // Handle special cases of physical registers that are not properly handled
16536 // by the base class.
16537 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
16538 // If we name a VSX register, we can't defer to the base class because it
16539 // will not recognize the correct register (their names will be VSL{0-31}
16540 // and V{0-31} so they won't match). So we match them here.
16541 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
16542 int VSNum = atoi(Constraint.data() + 3);
16543 assert(VSNum >= 0 && VSNum <= 63 &&(static_cast <bool> (VSNum >= 0 && VSNum <=
63 && "Attempted to access a vsr out of range") ? void
(0) : __assert_fail ("VSNum >= 0 && VSNum <= 63 && \"Attempted to access a vsr out of range\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 16544, __extension__
__PRETTY_FUNCTION__))
16544 "Attempted to access a vsr out of range")(static_cast <bool> (VSNum >= 0 && VSNum <=
63 && "Attempted to access a vsr out of range") ? void
(0) : __assert_fail ("VSNum >= 0 && VSNum <= 63 && \"Attempted to access a vsr out of range\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 16544, __extension__
__PRETTY_FUNCTION__))
;
16545 if (VSNum < 32)
16546 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
16547 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
16548 }
16549
16550 // For float registers, we can't defer to the base class as it will match
16551 // the SPILLTOVSRRC class.
16552 if (Constraint.size() > 3 && Constraint[1] == 'f') {
16553 int RegNum = atoi(Constraint.data() + 2);
16554 if (RegNum > 31 || RegNum < 0)
16555 report_fatal_error("Invalid floating point register number");
16556 if (VT == MVT::f32 || VT == MVT::i32)
16557 return Subtarget.hasSPE()
16558 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
16559 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
16560 if (VT == MVT::f64 || VT == MVT::i64)
16561 return Subtarget.hasSPE()
16562 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
16563 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
16564 }
16565 }
16566
16567 std::pair<unsigned, const TargetRegisterClass *> R =
16568 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16569
16570 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
16571 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
16572 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
16573 // register.
16574 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
16575 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
16576 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
16577 PPC::GPRCRegClass.contains(R.first))
16578 return std::make_pair(TRI->getMatchingSuperReg(R.first,
16579 PPC::sub_32, &PPC::G8RCRegClass),
16580 &PPC::G8RCRegClass);
16581
16582 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
16583 if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
16584 R.first = PPC::CR0;
16585 R.second = &PPC::CRRCRegClass;
16586 }
16587 // FIXME: This warning should ideally be emitted in the front end.
16588 const auto &TM = getTargetMachine();
16589 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
16590 if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
16591 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
16592 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
16593 errs() << "warning: vector registers 20 to 32 are reserved in the "
16594 "default AIX AltiVec ABI and cannot be used\n";
16595 }
16596
16597 return R;
16598}
16599
16600/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16601/// vector. If it is invalid, don't add anything to Ops.
16602void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16603 std::string &Constraint,
16604 std::vector<SDValue>&Ops,
16605 SelectionDAG &DAG) const {
16606 SDValue Result;
16607
16608 // Only support length 1 constraints.
16609 if (Constraint.length() > 1) return;
16610
16611 char Letter = Constraint[0];
16612 switch (Letter) {
16613 default: break;
16614 case 'I':
16615 case 'J':
16616 case 'K':
16617 case 'L':
16618 case 'M':
16619 case 'N':
16620 case 'O':
16621 case 'P': {
16622 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
16623 if (!CST) return; // Must be an immediate to match.
16624 SDLoc dl(Op);
16625 int64_t Value = CST->getSExtValue();
16626 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
16627 // numbers are printed as such.
16628 switch (Letter) {
16629 default: llvm_unreachable("Unknown constraint letter!")::llvm::llvm_unreachable_internal("Unknown constraint letter!"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 16629)
;
16630 case 'I': // "I" is a signed 16-bit constant.
16631 if (isInt<16>(Value))
16632 Result = DAG.getTargetConstant(Value, dl, TCVT);
16633 break;
16634 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
16635 if (isShiftedUInt<16, 16>(Value))
16636 Result = DAG.getTargetConstant(Value, dl, TCVT);
16637 break;
16638 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
16639 if (isShiftedInt<16, 16>(Value))
16640 Result = DAG.getTargetConstant(Value, dl, TCVT);
16641 break;
16642 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
16643 if (isUInt<16>(Value))
16644 Result = DAG.getTargetConstant(Value, dl, TCVT);
16645 break;
16646 case 'M': // "M" is a constant that is greater than 31.
16647 if (Value > 31)
16648 Result = DAG.getTargetConstant(Value, dl, TCVT);
16649 break;
16650 case 'N': // "N" is a positive constant that is an exact power of two.
16651 if (Value > 0 && isPowerOf2_64(Value))
16652 Result = DAG.getTargetConstant(Value, dl, TCVT);
16653 break;
16654 case 'O': // "O" is the constant zero.
16655 if (Value == 0)
16656 Result = DAG.getTargetConstant(Value, dl, TCVT);
16657 break;
16658 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
16659 if (isInt<16>(-Value))
16660 Result = DAG.getTargetConstant(Value, dl, TCVT);
16661 break;
16662 }
16663 break;
16664 }
16665 }
16666
16667 if (Result.getNode()) {
16668 Ops.push_back(Result);
16669 return;
16670 }
16671
16672 // Handle standard constraint letters.
16673 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16674}
16675
16676void PPCTargetLowering::CollectTargetIntrinsicOperands(const CallInst &I,
16677 SmallVectorImpl<SDValue> &Ops,
16678 SelectionDAG &DAG) const {
16679 if (I.getNumOperands() <= 1)
16680 return;
16681 if (!isa<ConstantSDNode>(Ops[1].getNode()))
16682 return;
16683 auto IntrinsicID = cast<ConstantSDNode>(Ops[1].getNode())->getZExtValue();
16684 if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw &&
16685 IntrinsicID != Intrinsic::ppc_trapd && IntrinsicID != Intrinsic::ppc_trap)
16686 return;
16687
16688 if (I.hasMetadata("annotation")) {
16689 MDNode *MDN = I.getMetadata("annotation");
16690 Ops.push_back(DAG.getMDNode(MDN));
16691 }
16692}
16693
16694// isLegalAddressingMode - Return true if the addressing mode represented
16695// by AM is legal for this target, for a load/store of the specified type.
16696bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16697 const AddrMode &AM, Type *Ty,
16698 unsigned AS,
16699 Instruction *I) const {
16700 // Vector type r+i form is supported since power9 as DQ form. We don't check
16701 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16702 // imm form is preferred and the offset can be adjusted to use imm form later
16703 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16704 // max offset to check legal addressing mode, we should be a little aggressive
16705 // to contain other offsets for that LSRUse.
16706 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16707 return false;
16708
16709 // PPC allows a sign-extended 16-bit immediate field.
16710 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16711 return false;
16712
16713 // No global is ever allowed as a base.
16714 if (AM.BaseGV)
16715 return false;
16716
16717 // PPC only support r+r,
16718 switch (AM.Scale) {
16719 case 0: // "r+i" or just "i", depending on HasBaseReg.
16720 break;
16721 case 1:
16722 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
16723 return false;
16724 // Otherwise we have r+r or r+i.
16725 break;
16726 case 2:
16727 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
16728 return false;
16729 // Allow 2*r as r+r.
16730 break;
16731 default:
16732 // No other scales are supported.
16733 return false;
16734 }
16735
16736 return true;
16737}
16738
16739SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16740 SelectionDAG &DAG) const {
16741 MachineFunction &MF = DAG.getMachineFunction();
16742 MachineFrameInfo &MFI = MF.getFrameInfo();
16743 MFI.setReturnAddressIsTaken(true);
16744
16745 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16746 return SDValue();
16747
16748 SDLoc dl(Op);
16749 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16750
16751 // Make sure the function does not optimize away the store of the RA to
16752 // the stack.
16753 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16754 FuncInfo->setLRStoreRequired();
16755 bool isPPC64 = Subtarget.isPPC64();
16756 auto PtrVT = getPointerTy(MF.getDataLayout());
16757
16758 if (Depth > 0) {
16759 // The link register (return address) is saved in the caller's frame
16760 // not the callee's stack frame. So we must get the caller's frame
16761 // address and load the return address at the LR offset from there.
16762 SDValue FrameAddr =
16763 DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16764 LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16765 SDValue Offset =
16766 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16767 isPPC64 ? MVT::i64 : MVT::i32);
16768 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16769 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16770 MachinePointerInfo());
16771 }
16772
16773 // Just load the return address off the stack.
16774 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16775 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16776 MachinePointerInfo());
16777}
16778
16779SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16780 SelectionDAG &DAG) const {
16781 SDLoc dl(Op);
16782 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16783
16784 MachineFunction &MF = DAG.getMachineFunction();
16785 MachineFrameInfo &MFI = MF.getFrameInfo();
16786 MFI.setFrameAddressIsTaken(true);
16787
16788 EVT PtrVT = getPointerTy(MF.getDataLayout());
16789 bool isPPC64 = PtrVT == MVT::i64;
16790
16791 // Naked functions never have a frame pointer, and so we use r1. For all
16792 // other functions, this decision must be delayed until during PEI.
16793 unsigned FrameReg;
16794 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16795 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16796 else
16797 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16798
16799 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16800 PtrVT);
16801 while (Depth--)
16802 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16803 FrameAddr, MachinePointerInfo());
16804 return FrameAddr;
16805}
16806
16807// FIXME? Maybe this could be a TableGen attribute on some registers and
16808// this table could be generated automatically from RegInfo.
16809Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16810 const MachineFunction &MF) const {
16811 bool isPPC64 = Subtarget.isPPC64();
16812
16813 bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16814 if (!is64Bit && VT != LLT::scalar(32))
16815 report_fatal_error("Invalid register global variable type");
16816
16817 Register Reg = StringSwitch<Register>(RegName)
16818 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16819 .Case("r2", isPPC64 ? Register() : PPC::R2)
16820 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16821 .Default(Register());
16822
16823 if (Reg)
16824 return Reg;
16825 report_fatal_error("Invalid register name global variable");
16826}
16827
16828bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16829 // 32-bit SVR4 ABI access everything as got-indirect.
16830 if (Subtarget.is32BitELFABI())
16831 return true;
16832
16833 // AIX accesses everything indirectly through the TOC, which is similar to
16834 // the GOT.
16835 if (Subtarget.isAIXABI())
16836 return true;
16837
16838 CodeModel::Model CModel = getTargetMachine().getCodeModel();
16839 // If it is small or large code model, module locals are accessed
16840 // indirectly by loading their address from .toc/.got.
16841 if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16842 return true;
16843
16844 // JumpTable and BlockAddress are accessed as got-indirect.
16845 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16846 return true;
16847
16848 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16849 return Subtarget.isGVIndirectSymbol(G->getGlobal());
16850
16851 return false;
16852}
16853
16854bool
16855PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16856 // The PowerPC target isn't yet aware of offsets.
16857 return false;
16858}
16859
16860bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16861 const CallInst &I,
16862 MachineFunction &MF,
16863 unsigned Intrinsic) const {
16864 switch (Intrinsic) {
16865 case Intrinsic::ppc_atomicrmw_xchg_i128:
16866 case Intrinsic::ppc_atomicrmw_add_i128:
16867 case Intrinsic::ppc_atomicrmw_sub_i128:
16868 case Intrinsic::ppc_atomicrmw_nand_i128:
16869 case Intrinsic::ppc_atomicrmw_and_i128:
16870 case Intrinsic::ppc_atomicrmw_or_i128:
16871 case Intrinsic::ppc_atomicrmw_xor_i128:
16872 case Intrinsic::ppc_cmpxchg_i128:
16873 Info.opc = ISD::INTRINSIC_W_CHAIN;
16874 Info.memVT = MVT::i128;
16875 Info.ptrVal = I.getArgOperand(0);
16876 Info.offset = 0;
16877 Info.align = Align(16);
16878 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16879 MachineMemOperand::MOVolatile;
16880 return true;
16881 case Intrinsic::ppc_atomic_load_i128:
16882 Info.opc = ISD::INTRINSIC_W_CHAIN;
16883 Info.memVT = MVT::i128;
16884 Info.ptrVal = I.getArgOperand(0);
16885 Info.offset = 0;
16886 Info.align = Align(16);
16887 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16888 return true;
16889 case Intrinsic::ppc_atomic_store_i128:
16890 Info.opc = ISD::INTRINSIC_VOID;
16891 Info.memVT = MVT::i128;
16892 Info.ptrVal = I.getArgOperand(2);
16893 Info.offset = 0;
16894 Info.align = Align(16);
16895 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16896 return true;
16897 case Intrinsic::ppc_altivec_lvx:
16898 case Intrinsic::ppc_altivec_lvxl:
16899 case Intrinsic::ppc_altivec_lvebx:
16900 case Intrinsic::ppc_altivec_lvehx:
16901 case Intrinsic::ppc_altivec_lvewx:
16902 case Intrinsic::ppc_vsx_lxvd2x:
16903 case Intrinsic::ppc_vsx_lxvw4x:
16904 case Intrinsic::ppc_vsx_lxvd2x_be:
16905 case Intrinsic::ppc_vsx_lxvw4x_be:
16906 case Intrinsic::ppc_vsx_lxvl:
16907 case Intrinsic::ppc_vsx_lxvll: {
16908 EVT VT;
16909 switch (Intrinsic) {
16910 case Intrinsic::ppc_altivec_lvebx:
16911 VT = MVT::i8;
16912 break;
16913 case Intrinsic::ppc_altivec_lvehx:
16914 VT = MVT::i16;
16915 break;
16916 case Intrinsic::ppc_altivec_lvewx:
16917 VT = MVT::i32;
16918 break;
16919 case Intrinsic::ppc_vsx_lxvd2x:
16920 case Intrinsic::ppc_vsx_lxvd2x_be:
16921 VT = MVT::v2f64;
16922 break;
16923 default:
16924 VT = MVT::v4i32;
16925 break;
16926 }
16927
16928 Info.opc = ISD::INTRINSIC_W_CHAIN;
16929 Info.memVT = VT;
16930 Info.ptrVal = I.getArgOperand(0);
16931 Info.offset = -VT.getStoreSize()+1;
16932 Info.size = 2*VT.getStoreSize()-1;
16933 Info.align = Align(1);
16934 Info.flags = MachineMemOperand::MOLoad;
16935 return true;
16936 }
16937 case Intrinsic::ppc_altivec_stvx:
16938 case Intrinsic::ppc_altivec_stvxl:
16939 case Intrinsic::ppc_altivec_stvebx:
16940 case Intrinsic::ppc_altivec_stvehx:
16941 case Intrinsic::ppc_altivec_stvewx:
16942 case Intrinsic::ppc_vsx_stxvd2x:
16943 case Intrinsic::ppc_vsx_stxvw4x:
16944 case Intrinsic::ppc_vsx_stxvd2x_be:
16945 case Intrinsic::ppc_vsx_stxvw4x_be:
16946 case Intrinsic::ppc_vsx_stxvl:
16947 case Intrinsic::ppc_vsx_stxvll: {
16948 EVT VT;
16949 switch (Intrinsic) {
16950 case Intrinsic::ppc_altivec_stvebx:
16951 VT = MVT::i8;
16952 break;
16953 case Intrinsic::ppc_altivec_stvehx:
16954 VT = MVT::i16;
16955 break;
16956 case Intrinsic::ppc_altivec_stvewx:
16957 VT = MVT::i32;
16958 break;
16959 case Intrinsic::ppc_vsx_stxvd2x:
16960 case Intrinsic::ppc_vsx_stxvd2x_be:
16961 VT = MVT::v2f64;
16962 break;
16963 default:
16964 VT = MVT::v4i32;
16965 break;
16966 }
16967
16968 Info.opc = ISD::INTRINSIC_VOID;
16969 Info.memVT = VT;
16970 Info.ptrVal = I.getArgOperand(1);
16971 Info.offset = -VT.getStoreSize()+1;
16972 Info.size = 2*VT.getStoreSize()-1;
16973 Info.align = Align(1);
16974 Info.flags = MachineMemOperand::MOStore;
16975 return true;
16976 }
16977 case Intrinsic::ppc_stdcx:
16978 case Intrinsic::ppc_stwcx:
16979 case Intrinsic::ppc_sthcx:
16980 case Intrinsic::ppc_stbcx: {
16981 EVT VT;
16982 auto Alignment = Align(8);
16983 switch (Intrinsic) {
16984 case Intrinsic::ppc_stdcx:
16985 VT = MVT::i64;
16986 break;
16987 case Intrinsic::ppc_stwcx:
16988 VT = MVT::i32;
16989 Alignment = Align(4);
16990 break;
16991 case Intrinsic::ppc_sthcx:
16992 VT = MVT::i16;
16993 Alignment = Align(2);
16994 break;
16995 case Intrinsic::ppc_stbcx:
16996 VT = MVT::i8;
16997 Alignment = Align(1);
16998 break;
16999 }
17000 Info.opc = ISD::INTRINSIC_W_CHAIN;
17001 Info.memVT = VT;
17002 Info.ptrVal = I.getArgOperand(0);
17003 Info.offset = 0;
17004 Info.align = Alignment;
17005 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
17006 return true;
17007 }
17008 default:
17009 break;
17010 }
17011
17012 return false;
17013}
17014
17015/// It returns EVT::Other if the type should be determined using generic
17016/// target-independent logic.
17017EVT PPCTargetLowering::getOptimalMemOpType(
17018 const MemOp &Op, const AttributeList &FuncAttributes) const {
17019 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
17020 // We should use Altivec/VSX loads and stores when available. For unaligned
17021 // addresses, unaligned VSX loads are only fast starting with the P8.
17022 if (Subtarget.hasAltivec() && Op.size() >= 16 &&
17023 (Op.isAligned(Align(16)) ||
17024 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
17025 return MVT::v4i32;
17026 }
17027
17028 if (Subtarget.isPPC64()) {
17029 return MVT::i64;
17030 }
17031
17032 return MVT::i32;
17033}
17034
17035/// Returns true if it is beneficial to convert a load of a constant
17036/// to just the constant itself.
17037bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
17038 Type *Ty) const {
17039 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 17039, __extension__ __PRETTY_FUNCTION__))
;
17040
17041 unsigned BitSize = Ty->getPrimitiveSizeInBits();
17042 return !(BitSize == 0 || BitSize > 64);
17043}
17044
17045bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17046 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17047 return false;
17048 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17049 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17050 return NumBits1 == 64 && NumBits2 == 32;
17051}
17052
17053bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17054 if (!VT1.isInteger() || !VT2.isInteger())
17055 return false;
17056 unsigned NumBits1 = VT1.getSizeInBits();
17057 unsigned NumBits2 = VT2.getSizeInBits();
17058 return NumBits1 == 64 && NumBits2 == 32;
17059}
17060
17061bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17062 // Generally speaking, zexts are not free, but they are free when they can be
17063 // folded with other operations.
17064 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
17065 EVT MemVT = LD->getMemoryVT();
17066 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
17067 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
17068 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
17069 LD->getExtensionType() == ISD::ZEXTLOAD))
17070 return true;
17071 }
17072
17073 // FIXME: Add other cases...
17074 // - 32-bit shifts with a zext to i64
17075 // - zext after ctlz, bswap, etc.
17076 // - zext after and by a constant mask
17077
17078 return TargetLowering::isZExtFree(Val, VT2);
17079}
17080
17081bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
17082 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&(static_cast <bool> (DestVT.isFloatingPoint() &&
SrcVT.isFloatingPoint() && "invalid fpext types") ? void
(0) : __assert_fail ("DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && \"invalid fpext types\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 17083, __extension__
__PRETTY_FUNCTION__))
17083 "invalid fpext types")(static_cast <bool> (DestVT.isFloatingPoint() &&
SrcVT.isFloatingPoint() && "invalid fpext types") ? void
(0) : __assert_fail ("DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && \"invalid fpext types\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 17083, __extension__
__PRETTY_FUNCTION__))
;
17084 // Extending to float128 is not free.
17085 if (DestVT == MVT::f128)
17086 return false;
17087 return true;
17088}
17089
17090bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17091 return isInt<16>(Imm) || isUInt<16>(Imm);
17092}
17093
17094bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
17095 return isInt<16>(Imm) || isUInt<16>(Imm);
17096}
17097
17098bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
17099 MachineMemOperand::Flags,
17100 unsigned *Fast) const {
17101 if (DisablePPCUnaligned)
17102 return false;
17103
17104 // PowerPC supports unaligned memory access for simple non-vector types.
17105 // Although accessing unaligned addresses is not as efficient as accessing
17106 // aligned addresses, it is generally more efficient than manual expansion,
17107 // and generally only traps for software emulation when crossing page
17108 // boundaries.
17109
17110 if (!VT.isSimple())
17111 return false;
17112
17113 if (VT.isFloatingPoint() && !VT.isVector() &&
17114 !Subtarget.allowsUnalignedFPAccess())
17115 return false;
17116
17117 if (VT.getSimpleVT().isVector()) {
17118 if (Subtarget.hasVSX()) {
17119 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
17120 VT != MVT::v4f32 && VT != MVT::v4i32)
17121 return false;
17122 } else {
17123 return false;
17124 }
17125 }
17126
17127 if (VT == MVT::ppcf128)
17128 return false;
17129
17130 if (Fast)
17131 *Fast = 1;
17132
17133 return true;
17134}
17135
17136bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
17137 SDValue C) const {
17138 // Check integral scalar types.
17139 if (!VT.isScalarInteger())
17140 return false;
17141 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
17142 if (!ConstNode->getAPIntValue().isSignedIntN(64))
17143 return false;
17144 // This transformation will generate >= 2 operations. But the following
17145 // cases will generate <= 2 instructions during ISEL. So exclude them.
17146 // 1. If the constant multiplier fits 16 bits, it can be handled by one
17147 // HW instruction, ie. MULLI
17148 // 2. If the multiplier after shifted fits 16 bits, an extra shift
17149 // instruction is needed than case 1, ie. MULLI and RLDICR
17150 int64_t Imm = ConstNode->getSExtValue();
17151 unsigned Shift = llvm::countr_zero<uint64_t>(Imm);
17152 Imm >>= Shift;
17153 if (isInt<16>(Imm))
17154 return false;
17155 uint64_t UImm = static_cast<uint64_t>(Imm);
17156 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
17157 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
17158 return true;
17159 }
17160 return false;
17161}
17162
17163bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
17164 EVT VT) const {
17165 return isFMAFasterThanFMulAndFAdd(
17166 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
17167}
17168
17169bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
17170 Type *Ty) const {
17171 if (Subtarget.hasSPE())
17172 return false;
17173 switch (Ty->getScalarType()->getTypeID()) {
17174 case Type::FloatTyID:
17175 case Type::DoubleTyID:
17176 return true;
17177 case Type::FP128TyID:
17178 return Subtarget.hasP9Vector();
17179 default:
17180 return false;
17181 }
17182}
17183
17184// FIXME: add more patterns which are not profitable to hoist.
17185bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
17186 if (!I->hasOneUse())
17187 return true;
17188
17189 Instruction *User = I->user_back();
17190 assert(User && "A single use instruction with no uses.")(static_cast <bool> (User && "A single use instruction with no uses."
) ? void (0) : __assert_fail ("User && \"A single use instruction with no uses.\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 17190, __extension__
__PRETTY_FUNCTION__))
;
17191
17192 switch (I->getOpcode()) {
17193 case Instruction::FMul: {
17194 // Don't break FMA, PowerPC prefers FMA.
17195 if (User->getOpcode() != Instruction::FSub &&
17196 User->getOpcode() != Instruction::FAdd)
17197 return true;
17198
17199 const TargetOptions &Options = getTargetMachine().Options;
17200 const Function *F = I->getFunction();
17201 const DataLayout &DL = F->getParent()->getDataLayout();
17202 Type *Ty = User->getOperand(0)->getType();
17203
17204 return !(
17205 isFMAFasterThanFMulAndFAdd(*F, Ty) &&
17206 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
17207 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
17208 }
17209 case Instruction::Load: {
17210 // Don't break "store (load float*)" pattern, this pattern will be combined
17211 // to "store (load int32)" in later InstCombine pass. See function
17212 // combineLoadToOperationType. On PowerPC, loading a float point takes more
17213 // cycles than loading a 32 bit integer.
17214 LoadInst *LI = cast<LoadInst>(I);
17215 // For the loads that combineLoadToOperationType does nothing, like
17216 // ordered load, it should be profitable to hoist them.
17217 // For swifterror load, it can only be used for pointer to pointer type, so
17218 // later type check should get rid of this case.
17219 if (!LI->isUnordered())
17220 return true;
17221
17222 if (User->getOpcode() != Instruction::Store)
17223 return true;
17224
17225 if (I->getType()->getTypeID() != Type::FloatTyID)
17226 return true;
17227
17228 return false;
17229 }
17230 default:
17231 return true;
17232 }
17233 return true;
17234}
17235
17236const MCPhysReg *
17237PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
17238 // LR is a callee-save register, but we must treat it as clobbered by any call
17239 // site. Hence we include LR in the scratch registers, which are in turn added
17240 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
17241 // to CTR, which is used by any indirect call.
17242 static const MCPhysReg ScratchRegs[] = {
17243 PPC::X12, PPC::LR8, PPC::CTR8, 0
17244 };
17245
17246 return ScratchRegs;
17247}
17248
17249Register PPCTargetLowering::getExceptionPointerRegister(
17250 const Constant *PersonalityFn) const {
17251 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
17252}
17253
17254Register PPCTargetLowering::getExceptionSelectorRegister(
17255 const Constant *PersonalityFn) const {
17256 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
17257}
17258
17259bool
17260PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
17261 EVT VT , unsigned DefinedValues) const {
17262 if (VT == MVT::v2i64)
17263 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
17264
17265 if (Subtarget.hasVSX())
17266 return true;
17267
17268 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
17269}
17270
17271Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
17272 if (DisableILPPref || Subtarget.enableMachineScheduler())
17273 return TargetLowering::getSchedulingPreference(N);
17274
17275 return Sched::ILP;
17276}
17277
17278// Create a fast isel object.
17279FastISel *
17280PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
17281 const TargetLibraryInfo *LibInfo) const {
17282 return PPC::createFastISel(FuncInfo, LibInfo);
17283}
17284
17285// 'Inverted' means the FMA opcode after negating one multiplicand.
17286// For example, (fma -a b c) = (fnmsub a b c)
17287static unsigned invertFMAOpcode(unsigned Opc) {
17288 switch (Opc) {
17289 default:
17290 llvm_unreachable("Invalid FMA opcode for PowerPC!")::llvm::llvm_unreachable_internal("Invalid FMA opcode for PowerPC!"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 17290)
;
17291 case ISD::FMA:
17292 return PPCISD::FNMSUB;
17293 case PPCISD::FNMSUB:
17294 return ISD::FMA;
17295 }
17296}
17297
17298SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
17299 bool LegalOps, bool OptForSize,
17300 NegatibleCost &Cost,
17301 unsigned Depth) const {
17302 if (Depth > SelectionDAG::MaxRecursionDepth)
17303 return SDValue();
17304
17305 unsigned Opc = Op.getOpcode();
17306 EVT VT = Op.getValueType();
17307 SDNodeFlags Flags = Op.getNode()->getFlags();
17308
17309 switch (Opc) {
17310 case PPCISD::FNMSUB:
17311 if (!Op.hasOneUse() || !isTypeLegal(VT))
17312 break;
17313
17314 const TargetOptions &Options = getTargetMachine().Options;
17315 SDValue N0 = Op.getOperand(0);
17316 SDValue N1 = Op.getOperand(1);
17317 SDValue N2 = Op.getOperand(2);
17318 SDLoc Loc(Op);
17319
17320 NegatibleCost N2Cost = NegatibleCost::Expensive;
17321 SDValue NegN2 =
17322 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
17323
17324 if (!NegN2)
17325 return SDValue();
17326
17327 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
17328 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
17329 // These transformations may change sign of zeroes. For example,
17330 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
17331 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
17332 // Try and choose the cheaper one to negate.
17333 NegatibleCost N0Cost = NegatibleCost::Expensive;
17334 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
17335 N0Cost, Depth + 1);
17336
17337 NegatibleCost N1Cost = NegatibleCost::Expensive;
17338 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
17339 N1Cost, Depth + 1);
17340
17341 if (NegN0 && N0Cost <= N1Cost) {
17342 Cost = std::min(N0Cost, N2Cost);
17343 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
17344 } else if (NegN1) {
17345 Cost = std::min(N1Cost, N2Cost);
17346 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
17347 }
17348 }
17349
17350 // (fneg (fnmsub a b c)) => (fma a b (fneg c))
17351 if (isOperationLegal(ISD::FMA, VT)) {
17352 Cost = N2Cost;
17353 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
17354 }
17355
17356 break;
17357 }
17358
17359 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
17360 Cost, Depth);
17361}
17362
17363// Override to enable LOAD_STACK_GUARD lowering on Linux.
17364bool PPCTargetLowering::useLoadStackGuardNode() const {
17365 if (!Subtarget.isTargetLinux())
17366 return TargetLowering::useLoadStackGuardNode();
17367 return true;
17368}
17369
17370// Override to disable global variable loading on Linux and insert AIX canary
17371// word declaration.
17372void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
17373 if (Subtarget.isAIXABI()) {
17374 M.getOrInsertGlobal(AIXSSPCanaryWordName,
17375 Type::getInt8PtrTy(M.getContext()));
17376 return;
17377 }
17378 if (!Subtarget.isTargetLinux())
17379 return TargetLowering::insertSSPDeclarations(M);
17380}
17381
17382Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
17383 if (Subtarget.isAIXABI())
17384 return M.getGlobalVariable(AIXSSPCanaryWordName);
17385 return TargetLowering::getSDagStackGuard(M);
17386}
17387
17388bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
17389 bool ForCodeSize) const {
17390 if (!VT.isSimple() || !Subtarget.hasVSX())
17391 return false;
17392
17393 switch(VT.getSimpleVT().SimpleTy) {
17394 default:
17395 // For FP types that are currently not supported by PPC backend, return
17396 // false. Examples: f16, f80.
17397 return false;
17398 case MVT::f32:
17399 case MVT::f64: {
17400 if (Subtarget.hasPrefixInstrs()) {
17401 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
17402 return true;
17403 }
17404 bool IsExact;
17405 APSInt IntResult(16, false);
17406 // The rounding mode doesn't really matter because we only care about floats
17407 // that can be converted to integers exactly.
17408 Imm.convertToInteger(IntResult, APFloat::rmTowardZero, &IsExact);
17409 // For exact values in the range [-16, 15] we can materialize the float.
17410 if (IsExact && IntResult <= 15 && IntResult >= -16)
17411 return true;
17412 return Imm.isZero();
17413 }
17414 case MVT::ppcf128:
17415 return Imm.isPosZero();
17416 }
17417}
17418
17419// For vector shift operation op, fold
17420// (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
17421static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
17422 SelectionDAG &DAG) {
17423 SDValue N0 = N->getOperand(0);
17424 SDValue N1 = N->getOperand(1);
17425 EVT VT = N0.getValueType();
17426 unsigned OpSizeInBits = VT.getScalarSizeInBits();
17427 unsigned Opcode = N->getOpcode();
17428 unsigned TargetOpcode;
17429
17430 switch (Opcode) {
17431 default:
17432 llvm_unreachable("Unexpected shift operation")::llvm::llvm_unreachable_internal("Unexpected shift operation"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 17432)
;
17433 case ISD::SHL:
17434 TargetOpcode = PPCISD::SHL;
17435 break;
17436 case ISD::SRL:
17437 TargetOpcode = PPCISD::SRL;
17438 break;
17439 case ISD::SRA:
17440 TargetOpcode = PPCISD::SRA;
17441 break;
17442 }
17443
17444 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
17445 N1->getOpcode() == ISD::AND)
17446 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
17447 if (Mask->getZExtValue() == OpSizeInBits - 1)
17448 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
17449
17450 return SDValue();
17451}
17452
17453SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
17454 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
17455 return Value;
17456
17457 SDValue N0 = N->getOperand(0);
17458 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
17459 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
17460 N0.getOpcode() != ISD::SIGN_EXTEND ||
17461 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
17462 N->getValueType(0) != MVT::i64)
17463 return SDValue();
17464
17465 // We can't save an operation here if the value is already extended, and
17466 // the existing shift is easier to combine.
17467 SDValue ExtsSrc = N0.getOperand(0);
17468 if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
17469 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
17470 return SDValue();
17471
17472 SDLoc DL(N0);
17473 SDValue ShiftBy = SDValue(CN1, 0);
17474 // We want the shift amount to be i32 on the extswli, but the shift could
17475 // have an i64.
17476 if (ShiftBy.getValueType() == MVT::i64)
17477 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
17478
17479 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
17480 ShiftBy);
17481}
17482
17483SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
17484 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
17485 return Value;
17486
17487 return SDValue();
17488}
17489
17490SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
17491 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
17492 return Value;
17493
17494 return SDValue();
17495}
17496
17497// Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
17498// Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
17499// When C is zero, the equation (addi Z, -C) can be simplified to Z
17500// Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
17501static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
17502 const PPCSubtarget &Subtarget) {
17503 if (!Subtarget.isPPC64())
17504 return SDValue();
17505
17506 SDValue LHS = N->getOperand(0);
17507 SDValue RHS = N->getOperand(1);
17508
17509 auto isZextOfCompareWithConstant = [](SDValue Op) {
17510 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
17511 Op.getValueType() != MVT::i64)
17512 return false;
17513
17514 SDValue Cmp = Op.getOperand(0);
17515 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
17516 Cmp.getOperand(0).getValueType() != MVT::i64)
17517 return false;
17518
17519 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
17520 int64_t NegConstant = 0 - Constant->getSExtValue();
17521 // Due to the limitations of the addi instruction,
17522 // -C is required to be [-32768, 32767].
17523 return isInt<16>(NegConstant);
17524 }
17525
17526 return false;
17527 };
17528
17529 bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
17530 bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
17531
17532 // If there is a pattern, canonicalize a zext operand to the RHS.
17533 if (LHSHasPattern && !RHSHasPattern)
17534 std::swap(LHS, RHS);
17535 else if (!LHSHasPattern && !RHSHasPattern)
17536 return SDValue();
17537
17538 SDLoc DL(N);
17539 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
17540 SDValue Cmp = RHS.getOperand(0);
17541 SDValue Z = Cmp.getOperand(0);
17542 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
17543 int64_t NegConstant = 0 - Constant->getSExtValue();
17544
17545 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
17546 default: break;
17547 case ISD::SETNE: {
17548 // when C == 0
17549 // --> addze X, (addic Z, -1).carry
17550 // /
17551 // add X, (zext(setne Z, C))--
17552 // \ when -32768 <= -C <= 32767 && C != 0
17553 // --> addze X, (addic (addi Z, -C), -1).carry
17554 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17555 DAG.getConstant(NegConstant, DL, MVT::i64));
17556 SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17557 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17558 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
17559 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17560 SDValue(Addc.getNode(), 1));
17561 }
17562 case ISD::SETEQ: {
17563 // when C == 0
17564 // --> addze X, (subfic Z, 0).carry
17565 // /
17566 // add X, (zext(sete Z, C))--
17567 // \ when -32768 <= -C <= 32767 && C != 0
17568 // --> addze X, (subfic (addi Z, -C), 0).carry
17569 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17570 DAG.getConstant(NegConstant, DL, MVT::i64));
17571 SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17572 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17573 DAG.getConstant(0, DL, MVT::i64), AddOrZ);
17574 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17575 SDValue(Subc.getNode(), 1));
17576 }
17577 }
17578
17579 return SDValue();
17580}
17581
17582// Transform
17583// (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
17584// (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
17585// In this case both C1 and C2 must be known constants.
17586// C1+C2 must fit into a 34 bit signed integer.
17587static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
17588 const PPCSubtarget &Subtarget) {
17589 if (!Subtarget.isUsingPCRelativeCalls())
17590 return SDValue();
17591
17592 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
17593 // If we find that node try to cast the Global Address and the Constant.
17594 SDValue LHS = N->getOperand(0);
17595 SDValue RHS = N->getOperand(1);
17596
17597 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17598 std::swap(LHS, RHS);
17599
17600 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17601 return SDValue();
17602
17603 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
17604 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
17605 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
17606
17607 // Check that both casts succeeded.
17608 if (!GSDN || !ConstNode)
17609 return SDValue();
17610
17611 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
17612 SDLoc DL(GSDN);
17613
17614 // The signed int offset needs to fit in 34 bits.
17615 if (!isInt<34>(NewOffset))
17616 return SDValue();
17617
17618 // The new global address is a copy of the old global address except
17619 // that it has the updated Offset.
17620 SDValue GA =
17621 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
17622 NewOffset, GSDN->getTargetFlags());
17623 SDValue MatPCRel =
17624 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
17625 return MatPCRel;
17626}
17627
17628SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
17629 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
17630 return Value;
17631
17632 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
17633 return Value;
17634
17635 return SDValue();
17636}
17637
17638// Detect TRUNCATE operations on bitcasts of float128 values.
17639// What we are looking for here is the situtation where we extract a subset
17640// of bits from a 128 bit float.
17641// This can be of two forms:
17642// 1) BITCAST of f128 feeding TRUNCATE
17643// 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
17644// The reason this is required is because we do not have a legal i128 type
17645// and so we want to prevent having to store the f128 and then reload part
17646// of it.
17647SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
17648 DAGCombinerInfo &DCI) const {
17649 // If we are using CRBits then try that first.
17650 if (Subtarget.useCRBits()) {
17651 // Check if CRBits did anything and return that if it did.
17652 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
17653 return CRTruncValue;
17654 }
17655
17656 SDLoc dl(N);
17657 SDValue Op0 = N->getOperand(0);
17658
17659 // Looking for a truncate of i128 to i64.
17660 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
17661 return SDValue();
17662
17663 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
17664
17665 // SRL feeding TRUNCATE.
17666 if (Op0.getOpcode() == ISD::SRL) {
17667 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
17668 // The right shift has to be by 64 bits.
17669 if (!ConstNode || ConstNode->getZExtValue() != 64)
17670 return SDValue();
17671
17672 // Switch the element number to extract.
17673 EltToExtract = EltToExtract ? 0 : 1;
17674 // Update Op0 past the SRL.
17675 Op0 = Op0.getOperand(0);
17676 }
17677
17678 // BITCAST feeding a TRUNCATE possibly via SRL.
17679 if (Op0.getOpcode() == ISD::BITCAST &&
17680 Op0.getValueType() == MVT::i128 &&
17681 Op0.getOperand(0).getValueType() == MVT::f128) {
17682 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
17683 return DCI.DAG.getNode(
17684 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17685 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17686 }
17687 return SDValue();
17688}
17689
17690SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17691 SelectionDAG &DAG = DCI.DAG;
17692
17693 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17694 if (!ConstOpOrElement)
17695 return SDValue();
17696
17697 // An imul is usually smaller than the alternative sequence for legal type.
17698 if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17699 isOperationLegal(ISD::MUL, N->getValueType(0)))
17700 return SDValue();
17701
17702 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17703 switch (this->Subtarget.getCPUDirective()) {
17704 default:
17705 // TODO: enhance the condition for subtarget before pwr8
17706 return false;
17707 case PPC::DIR_PWR8:
17708 // type mul add shl
17709 // scalar 4 1 1
17710 // vector 7 2 2
17711 return true;
17712 case PPC::DIR_PWR9:
17713 case PPC::DIR_PWR10:
17714 case PPC::DIR_PWR_FUTURE:
17715 // type mul add shl
17716 // scalar 5 2 2
17717 // vector 7 2 2
17718
17719 // The cycle RATIO of related operations are showed as a table above.
17720 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17721 // scalar and vector type. For 2 instrs patterns, add/sub + shl
17722 // are 4, it is always profitable; but for 3 instrs patterns
17723 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17724 // So we should only do it for vector type.
17725 return IsAddOne && IsNeg ? VT.isVector() : true;
17726 }
17727 };
17728
17729 EVT VT = N->getValueType(0);
17730 SDLoc DL(N);
17731
17732 const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17733 bool IsNeg = MulAmt.isNegative();
17734 APInt MulAmtAbs = MulAmt.abs();
17735
17736 if ((MulAmtAbs - 1).isPowerOf2()) {
17737 // (mul x, 2^N + 1) => (add (shl x, N), x)
17738 // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17739
17740 if (!IsProfitable(IsNeg, true, VT))
17741 return SDValue();
17742
17743 SDValue Op0 = N->getOperand(0);
17744 SDValue Op1 =
17745 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17746 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17747 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17748
17749 if (!IsNeg)
17750 return Res;
17751
17752 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17753 } else if ((MulAmtAbs + 1).isPowerOf2()) {
17754 // (mul x, 2^N - 1) => (sub (shl x, N), x)
17755 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17756
17757 if (!IsProfitable(IsNeg, false, VT))
17758 return SDValue();
17759
17760 SDValue Op0 = N->getOperand(0);
17761 SDValue Op1 =
17762 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17763 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17764
17765 if (!IsNeg)
17766 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17767 else
17768 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17769
17770 } else {
17771 return SDValue();
17772 }
17773}
17774
17775// Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17776// in combiner since we need to check SD flags and other subtarget features.
17777SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17778 DAGCombinerInfo &DCI) const {
17779 SDValue N0 = N->getOperand(0);
17780 SDValue N1 = N->getOperand(1);
17781 SDValue N2 = N->getOperand(2);
17782 SDNodeFlags Flags = N->getFlags();
17783 EVT VT = N->getValueType(0);
17784 SelectionDAG &DAG = DCI.DAG;
17785 const TargetOptions &Options = getTargetMachine().Options;
17786 unsigned Opc = N->getOpcode();
17787 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17788 bool LegalOps = !DCI.isBeforeLegalizeOps();
17789 SDLoc Loc(N);
17790
17791 if (!isOperationLegal(ISD::FMA, VT))
17792 return SDValue();
17793
17794 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17795 // since (fnmsub a b c)=-0 while c-ab=+0.
17796 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17797 return SDValue();
17798
17799 // (fma (fneg a) b c) => (fnmsub a b c)
17800 // (fnmsub (fneg a) b c) => (fma a b c)
17801 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17802 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17803
17804 // (fma a (fneg b) c) => (fnmsub a b c)
17805 // (fnmsub a (fneg b) c) => (fma a b c)
17806 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17807 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17808
17809 return SDValue();
17810}
17811
17812bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17813 // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17814 if (!Subtarget.is64BitELFABI())
17815 return false;
17816
17817 // If not a tail call then no need to proceed.
17818 if (!CI->isTailCall())
17819 return false;
17820
17821 // If sibling calls have been disabled and tail-calls aren't guaranteed
17822 // there is no reason to duplicate.
17823 auto &TM = getTargetMachine();
17824 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17825 return false;
17826
17827 // Can't tail call a function called indirectly, or if it has variadic args.
17828 const Function *Callee = CI->getCalledFunction();
17829 if (!Callee || Callee->isVarArg())
17830 return false;
17831
17832 // Make sure the callee and caller calling conventions are eligible for tco.
17833 const Function *Caller = CI->getParent()->getParent();
17834 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17835 CI->getCallingConv()))
17836 return false;
17837
17838 // If the function is local then we have a good chance at tail-calling it
17839 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17840}
17841
17842bool PPCTargetLowering::
17843isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17844 const Value *Mask = AndI.getOperand(1);
17845 // If the mask is suitable for andi. or andis. we should sink the and.
17846 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17847 // Can't handle constants wider than 64-bits.
17848 if (CI->getBitWidth() > 64)
17849 return false;
17850 int64_t ConstVal = CI->getZExtValue();
17851 return isUInt<16>(ConstVal) ||
17852 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17853 }
17854
17855 // For non-constant masks, we can always use the record-form and.
17856 return true;
17857}
17858
17859/// getAddrModeForFlags - Based on the set of address flags, select the most
17860/// optimal instruction format to match by.
17861PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17862 // This is not a node we should be handling here.
17863 if (Flags == PPC::MOF_None)
17864 return PPC::AM_None;
17865 // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17866 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17867 if ((Flags & FlagSet) == FlagSet)
17868 return PPC::AM_DForm;
17869 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17870 if ((Flags & FlagSet) == FlagSet)
17871 return PPC::AM_DSForm;
17872 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17873 if ((Flags & FlagSet) == FlagSet)
17874 return PPC::AM_DQForm;
17875 for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17876 if ((Flags & FlagSet) == FlagSet)
17877 return PPC::AM_PrefixDForm;
17878 // If no other forms are selected, return an X-Form as it is the most
17879 // general addressing mode.
17880 return PPC::AM_XForm;
17881}
17882
17883/// Set alignment flags based on whether or not the Frame Index is aligned.
17884/// Utilized when computing flags for address computation when selecting
17885/// load and store instructions.
17886static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17887 SelectionDAG &DAG) {
17888 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17889 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17890 if (!FI)
17891 return;
17892 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17893 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17894 // If this is (add $FI, $S16Imm), the alignment flags are already set
17895 // based on the immediate. We just need to clear the alignment flags
17896 // if the FI alignment is weaker.
17897 if ((FrameIndexAlign % 4) != 0)
17898 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17899 if ((FrameIndexAlign % 16) != 0)
17900 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17901 // If the address is a plain FrameIndex, set alignment flags based on
17902 // FI alignment.
17903 if (!IsAdd) {
17904 if ((FrameIndexAlign % 4) == 0)
17905 FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17906 if ((FrameIndexAlign % 16) == 0)
17907 FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17908 }
17909}
17910
17911/// Given a node, compute flags that are used for address computation when
17912/// selecting load and store instructions. The flags computed are stored in
17913/// FlagSet. This function takes into account whether the node is a constant,
17914/// an ADD, OR, or a constant, and computes the address flags accordingly.
17915static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17916 SelectionDAG &DAG) {
17917 // Set the alignment flags for the node depending on if the node is
17918 // 4-byte or 16-byte aligned.
17919 auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17920 if ((Imm & 0x3) == 0)
17921 FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17922 if ((Imm & 0xf) == 0)
17923 FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17924 };
17925
17926 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17927 // All 32-bit constants can be computed as LIS + Disp.
17928 const APInt &ConstImm = CN->getAPIntValue();
17929 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17930 FlagSet |= PPC::MOF_AddrIsSImm32;
17931 SetAlignFlagsForImm(ConstImm.getZExtValue());
17932 setAlignFlagsForFI(N, FlagSet, DAG);
17933 }
17934 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17935 FlagSet |= PPC::MOF_RPlusSImm34;
17936 else // Let constant materialization handle large constants.
17937 FlagSet |= PPC::MOF_NotAddNorCst;
17938 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17939 // This address can be represented as an addition of:
17940 // - Register + Imm16 (possibly a multiple of 4/16)
17941 // - Register + Imm34
17942 // - Register + PPCISD::Lo
17943 // - Register + Register
17944 // In any case, we won't have to match this as Base + Zero.
17945 SDValue RHS = N.getOperand(1);
17946 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17947 const APInt &ConstImm = CN->getAPIntValue();
17948 if (ConstImm.isSignedIntN(16)) {
17949 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17950 SetAlignFlagsForImm(ConstImm.getZExtValue());
17951 setAlignFlagsForFI(N, FlagSet, DAG);
17952 }
17953 if (ConstImm.isSignedIntN(34))
17954 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17955 else
17956 FlagSet |= PPC::MOF_RPlusR; // Register.
17957 } else if (RHS.getOpcode() == PPCISD::Lo &&
17958 !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17959 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17960 else
17961 FlagSet |= PPC::MOF_RPlusR;
17962 } else { // The address computation is not a constant or an addition.
17963 setAlignFlagsForFI(N, FlagSet, DAG);
17964 FlagSet |= PPC::MOF_NotAddNorCst;
17965 }
17966}
17967
17968static bool isPCRelNode(SDValue N) {
17969 return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17970 isValidPCRelNode<ConstantPoolSDNode>(N) ||
17971 isValidPCRelNode<GlobalAddressSDNode>(N) ||
17972 isValidPCRelNode<JumpTableSDNode>(N) ||
17973 isValidPCRelNode<BlockAddressSDNode>(N));
17974}
17975
17976/// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17977/// the address flags of the load/store instruction that is to be matched.
17978unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17979 SelectionDAG &DAG) const {
17980 unsigned FlagSet = PPC::MOF_None;
17981
17982 // Compute subtarget flags.
17983 if (!Subtarget.hasP9Vector())
17984 FlagSet |= PPC::MOF_SubtargetBeforeP9;
17985 else {
17986 FlagSet |= PPC::MOF_SubtargetP9;
17987 if (Subtarget.hasPrefixInstrs())
17988 FlagSet |= PPC::MOF_SubtargetP10;
17989 }
17990 if (Subtarget.hasSPE())
17991 FlagSet |= PPC::MOF_SubtargetSPE;
17992
17993 // Check if we have a PCRel node and return early.
17994 if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17995 return FlagSet;
17996
17997 // If the node is the paired load/store intrinsics, compute flags for
17998 // address computation and return early.
17999 unsigned ParentOp = Parent->getOpcode();
18000 if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
18001 (ParentOp == ISD::INTRINSIC_VOID))) {
18002 unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
18003 if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
18004 SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
18005 ? Parent->getOperand(2)
18006 : Parent->getOperand(3);
18007 computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
18008 FlagSet |= PPC::MOF_Vector;
18009 return FlagSet;
18010 }
18011 }
18012
18013 // Mark this as something we don't want to handle here if it is atomic
18014 // or pre-increment instruction.
18015 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
18016 if (LSB->isIndexed())
18017 return PPC::MOF_None;
18018
18019 // Compute in-memory type flags. This is based on if there are scalars,
18020 // floats or vectors.
18021 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
18022 assert(MN && "Parent should be a MemSDNode!")(static_cast <bool> (MN && "Parent should be a MemSDNode!"
) ? void (0) : __assert_fail ("MN && \"Parent should be a MemSDNode!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18022, __extension__
__PRETTY_FUNCTION__))
;
18023 EVT MemVT = MN->getMemoryVT();
18024 unsigned Size = MemVT.getSizeInBits();
18025 if (MemVT.isScalarInteger()) {
18026 assert(Size <= 128 &&(static_cast <bool> (Size <= 128 && "Not expecting scalar integers larger than 16 bytes!"
) ? void (0) : __assert_fail ("Size <= 128 && \"Not expecting scalar integers larger than 16 bytes!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18027, __extension__
__PRETTY_FUNCTION__))
18027 "Not expecting scalar integers larger than 16 bytes!")(static_cast <bool> (Size <= 128 && "Not expecting scalar integers larger than 16 bytes!"
) ? void (0) : __assert_fail ("Size <= 128 && \"Not expecting scalar integers larger than 16 bytes!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18027, __extension__
__PRETTY_FUNCTION__))
;
18028 if (Size < 32)
18029 FlagSet |= PPC::MOF_SubWordInt;
18030 else if (Size == 32)
18031 FlagSet |= PPC::MOF_WordInt;
18032 else
18033 FlagSet |= PPC::MOF_DoubleWordInt;
18034 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
18035 if (Size == 128)
18036 FlagSet |= PPC::MOF_Vector;
18037 else if (Size == 256) {
18038 assert(Subtarget.pairedVectorMemops() &&(static_cast <bool> (Subtarget.pairedVectorMemops() &&
"256-bit vectors are only available when paired vector memops is "
"enabled!") ? void (0) : __assert_fail ("Subtarget.pairedVectorMemops() && \"256-bit vectors are only available when paired vector memops is \" \"enabled!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18040, __extension__
__PRETTY_FUNCTION__))
18039 "256-bit vectors are only available when paired vector memops is "(static_cast <bool> (Subtarget.pairedVectorMemops() &&
"256-bit vectors are only available when paired vector memops is "
"enabled!") ? void (0) : __assert_fail ("Subtarget.pairedVectorMemops() && \"256-bit vectors are only available when paired vector memops is \" \"enabled!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18040, __extension__
__PRETTY_FUNCTION__))
18040 "enabled!")(static_cast <bool> (Subtarget.pairedVectorMemops() &&
"256-bit vectors are only available when paired vector memops is "
"enabled!") ? void (0) : __assert_fail ("Subtarget.pairedVectorMemops() && \"256-bit vectors are only available when paired vector memops is \" \"enabled!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18040, __extension__
__PRETTY_FUNCTION__))
;
18041 FlagSet |= PPC::MOF_Vector;
18042 } else
18043 llvm_unreachable("Not expecting illegal vectors!")::llvm::llvm_unreachable_internal("Not expecting illegal vectors!"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18043)
;
18044 } else { // Floating point type: can be scalar, f128 or vector types.
18045 if (Size == 32 || Size == 64)
18046 FlagSet |= PPC::MOF_ScalarFloat;
18047 else if (MemVT == MVT::f128 || MemVT.isVector())
18048 FlagSet |= PPC::MOF_Vector;
18049 else
18050 llvm_unreachable("Not expecting illegal scalar floats!")::llvm::llvm_unreachable_internal("Not expecting illegal scalar floats!"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18050)
;
18051 }
18052
18053 // Compute flags for address computation.
18054 computeFlagsForAddressComputation(N, FlagSet, DAG);
18055
18056 // Compute type extension flags.
18057 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
18058 switch (LN->getExtensionType()) {
18059 case ISD::SEXTLOAD:
18060 FlagSet |= PPC::MOF_SExt;
18061 break;
18062 case ISD::EXTLOAD:
18063 case ISD::ZEXTLOAD:
18064 FlagSet |= PPC::MOF_ZExt;
18065 break;
18066 case ISD::NON_EXTLOAD:
18067 FlagSet |= PPC::MOF_NoExt;
18068 break;
18069 }
18070 } else
18071 FlagSet |= PPC::MOF_NoExt;
18072
18073 // For integers, no extension is the same as zero extension.
18074 // We set the extension mode to zero extension so we don't have
18075 // to add separate entries in AddrModesMap for loads and stores.
18076 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
18077 FlagSet |= PPC::MOF_ZExt;
18078 FlagSet &= ~PPC::MOF_NoExt;
18079 }
18080
18081 // If we don't have prefixed instructions, 34-bit constants should be
18082 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
18083 bool IsNonP1034BitConst =
18084 ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
18085 FlagSet) == PPC::MOF_RPlusSImm34;
18086 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
18087 IsNonP1034BitConst)
18088 FlagSet |= PPC::MOF_NotAddNorCst;
18089
18090 return FlagSet;
18091}
18092
18093/// SelectForceXFormMode - Given the specified address, force it to be
18094/// represented as an indexed [r+r] operation (an XForm instruction).
18095PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
18096 SDValue &Base,
18097 SelectionDAG &DAG) const {
18098
18099 PPC::AddrMode Mode = PPC::AM_XForm;
18100 int16_t ForceXFormImm = 0;
18101 if (provablyDisjointOr(DAG, N) &&
18102 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
18103 Disp = N.getOperand(0);
18104 Base = N.getOperand(1);
18105 return Mode;
18106 }
18107
18108 // If the address is the result of an add, we will utilize the fact that the
18109 // address calculation includes an implicit add. However, we can reduce
18110 // register pressure if we do not materialize a constant just for use as the
18111 // index register. We only get rid of the add if it is not an add of a
18112 // value and a 16-bit signed constant and both have a single use.
18113 if (N.getOpcode() == ISD::ADD &&
18114 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
18115 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
18116 Disp = N.getOperand(0);
18117 Base = N.getOperand(1);
18118 return Mode;
18119 }
18120
18121 // Otherwise, use R0 as the base register.
18122 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
18123 N.getValueType());
18124 Base = N;
18125
18126 return Mode;
18127}
18128
18129bool PPCTargetLowering::splitValueIntoRegisterParts(
18130 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
18131 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
18132 EVT ValVT = Val.getValueType();
18133 // If we are splitting a scalar integer into f64 parts (i.e. so they
18134 // can be placed into VFRC registers), we need to zero extend and
18135 // bitcast the values. This will ensure the value is placed into a
18136 // VSR using direct moves or stack operations as needed.
18137 if (PartVT == MVT::f64 &&
18138 (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
18139 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
18140 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
18141 Parts[0] = Val;
18142 return true;
18143 }
18144 return false;
18145}
18146
18147SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
18148 SelectionDAG &DAG) const {
18149 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18150 TargetLowering::CallLoweringInfo CLI(DAG);
18151 EVT RetVT = Op.getValueType();
18152 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
18153 SDValue Callee =
18154 DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
18155 bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false);
18156 TargetLowering::ArgListTy Args;
18157 TargetLowering::ArgListEntry Entry;
18158 for (const SDValue &N : Op->op_values()) {
18159 EVT ArgVT = N.getValueType();
18160 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18161 Entry.Node = N;
18162 Entry.Ty = ArgTy;
18163 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend);
18164 Entry.IsZExt = !Entry.IsSExt;
18165 Args.push_back(Entry);
18166 }
18167
18168 SDValue InChain = DAG.getEntryNode();
18169 SDValue TCChain = InChain;
18170 const Function &F = DAG.getMachineFunction().getFunction();
18171 bool isTailCall =
18172 TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
18173 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
18174 if (isTailCall)
18175 InChain = TCChain;
18176 CLI.setDebugLoc(SDLoc(Op))
18177 .setChain(InChain)
18178 .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args))
18179 .setTailCall(isTailCall)
18180 .setSExtResult(SignExtend)
18181 .setZExtResult(!SignExtend)
18182 .setIsPostTypeLegalization(true);
18183 return TLI.LowerCallTo(CLI).first;
18184}
18185
18186SDValue PPCTargetLowering::lowerLibCallBasedOnType(
18187 const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
18188 SelectionDAG &DAG) const {
18189 if (Op.getValueType() == MVT::f32)
18190 return lowerToLibCall(LibCallFloatName, Op, DAG);
18191
18192 if (Op.getValueType() == MVT::f64)
18193 return lowerToLibCall(LibCallDoubleName, Op, DAG);
18194
18195 return SDValue();
18196}
18197
18198bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
18199 SDNodeFlags Flags = Op.getNode()->getFlags();
18200 return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
18201 Flags.hasNoNaNs() && Flags.hasNoInfs();
18202}
18203
18204bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
18205 return Op.getNode()->getFlags().hasApproximateFuncs();
18206}
18207
18208bool PPCTargetLowering::isScalarMASSConversionEnabled() const {
18209 return getTargetMachine().Options.PPCGenScalarMASSEntries;
18210}
18211
18212SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
18213 const char *LibCallFloatName,
18214 const char *LibCallDoubleNameFinite,
18215 const char *LibCallFloatNameFinite,
18216 SDValue Op,
18217 SelectionDAG &DAG) const {
18218 if (!isScalarMASSConversionEnabled() || !isLowringToMASSSafe(Op))
18219 return SDValue();
18220
18221 if (!isLowringToMASSFiniteSafe(Op))
18222 return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
18223 DAG);
18224
18225 return lowerLibCallBasedOnType(LibCallFloatNameFinite,
18226 LibCallDoubleNameFinite, Op, DAG);
18227}
18228
18229SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
18230 return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
18231 "__xl_powf_finite", Op, DAG);
18232}
18233
18234SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
18235 return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
18236 "__xl_sinf_finite", Op, DAG);
18237}
18238
18239SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
18240 return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
18241 "__xl_cosf_finite", Op, DAG);
18242}
18243
18244SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
18245 return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
18246 "__xl_logf_finite", Op, DAG);
18247}
18248
18249SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
18250 return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
18251 "__xl_log10f_finite", Op, DAG);
18252}
18253
18254SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
18255 return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
18256 "__xl_expf_finite", Op, DAG);
18257}
18258
18259// If we happen to match to an aligned D-Form, check if the Frame Index is
18260// adequately aligned. If it is not, reset the mode to match to X-Form.
18261static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
18262 PPC::AddrMode &Mode) {
18263 if (!isa<FrameIndexSDNode>(N))
18264 return;
18265 if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
18266 (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
18267 Mode = PPC::AM_XForm;
18268}
18269
18270/// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
18271/// compute the address flags of the node, get the optimal address mode based
18272/// on the flags, and set the Base and Disp based on the address mode.
18273PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
18274 SDValue N, SDValue &Disp,
18275 SDValue &Base,
18276 SelectionDAG &DAG,
18277 MaybeAlign Align) const {
18278 SDLoc DL(Parent);
18279
18280 // Compute the address flags.
18281 unsigned Flags = computeMOFlags(Parent, N, DAG);
18282
18283 // Get the optimal address mode based on the Flags.
18284 PPC::AddrMode Mode = getAddrModeForFlags(Flags);
18285
18286 // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
18287 // Select an X-Form load if it is not.
18288 setXFormForUnalignedFI(N, Flags, Mode);
18289
18290 // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
18291 if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
18292 assert(Subtarget.isUsingPCRelativeCalls() &&(static_cast <bool> (Subtarget.isUsingPCRelativeCalls()
&& "Must be using PC-Relative calls when a valid PC-Relative node is "
"present!") ? void (0) : __assert_fail ("Subtarget.isUsingPCRelativeCalls() && \"Must be using PC-Relative calls when a valid PC-Relative node is \" \"present!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18294, __extension__
__PRETTY_FUNCTION__))
18293 "Must be using PC-Relative calls when a valid PC-Relative node is "(static_cast <bool> (Subtarget.isUsingPCRelativeCalls()
&& "Must be using PC-Relative calls when a valid PC-Relative node is "
"present!") ? void (0) : __assert_fail ("Subtarget.isUsingPCRelativeCalls() && \"Must be using PC-Relative calls when a valid PC-Relative node is \" \"present!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18294, __extension__
__PRETTY_FUNCTION__))
18294 "present!")(static_cast <bool> (Subtarget.isUsingPCRelativeCalls()
&& "Must be using PC-Relative calls when a valid PC-Relative node is "
"present!") ? void (0) : __assert_fail ("Subtarget.isUsingPCRelativeCalls() && \"Must be using PC-Relative calls when a valid PC-Relative node is \" \"present!\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18294, __extension__
__PRETTY_FUNCTION__))
;
18295 Mode = PPC::AM_PCRel;
18296 }
18297
18298 // Set Base and Disp accordingly depending on the address mode.
18299 switch (Mode) {
18300 case PPC::AM_DForm:
18301 case PPC::AM_DSForm:
18302 case PPC::AM_DQForm: {
18303 // This is a register plus a 16-bit immediate. The base will be the
18304 // register and the displacement will be the immediate unless it
18305 // isn't sufficiently aligned.
18306 if (Flags & PPC::MOF_RPlusSImm16) {
18307 SDValue Op0 = N.getOperand(0);
18308 SDValue Op1 = N.getOperand(1);
18309 int16_t Imm = cast<ConstantSDNode>(Op1)->getZExtValue();
18310 if (!Align || isAligned(*Align, Imm)) {
18311 Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
18312 Base = Op0;
18313 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
18314 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
18315 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
18316 }
18317 break;
18318 }
18319 }
18320 // This is a register plus the @lo relocation. The base is the register
18321 // and the displacement is the global address.
18322 else if (Flags & PPC::MOF_RPlusLo) {
18323 Disp = N.getOperand(1).getOperand(0); // The global address.
18324 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", 18327, __extension__
__PRETTY_FUNCTION__))
18325 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", 18327, __extension__
__PRETTY_FUNCTION__))
18326 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", 18327, __extension__
__PRETTY_FUNCTION__))
18327 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", 18327, __extension__
__PRETTY_FUNCTION__))
;
18328 Base = N.getOperand(0);
18329 break;
18330 }
18331 // This is a constant address at most 32 bits. The base will be
18332 // zero or load-immediate-shifted and the displacement will be
18333 // the low 16 bits of the address.
18334 else if (Flags & PPC::MOF_AddrIsSImm32) {
18335 auto *CN = cast<ConstantSDNode>(N);
18336 EVT CNType = CN->getValueType(0);
18337 uint64_t CNImm = CN->getZExtValue();
18338 // If this address fits entirely in a 16-bit sext immediate field, codegen
18339 // this as "d, 0".
18340 int16_t Imm;
18341 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
18342 Disp = DAG.getTargetConstant(Imm, DL, CNType);
18343 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
18344 CNType);
18345 break;
18346 }
18347 // Handle 32-bit sext immediate with LIS + Addr mode.
18348 if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
18349 (!Align || isAligned(*Align, CNImm))) {
18350 int32_t Addr = (int32_t)CNImm;
18351 // Otherwise, break this down into LIS + Disp.
18352 Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
18353 Base =
18354 DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
18355 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
18356 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
18357 break;
18358 }
18359 }
18360 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
18361 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
18362 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
18363 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
18364 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
18365 } else
18366 Base = N;
18367 break;
18368 }
18369 case PPC::AM_PrefixDForm: {
18370 int64_t Imm34 = 0;
18371 unsigned Opcode = N.getOpcode();
18372 if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
18373 (isIntS34Immediate(N.getOperand(1), Imm34))) {
18374 // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
18375 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
18376 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
18377 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
18378 else
18379 Base = N.getOperand(0);
18380 } else if (isIntS34Immediate(N, Imm34)) {
18381 // The address is a 34-bit signed immediate.
18382 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
18383 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
18384 }
18385 break;
18386 }
18387 case PPC::AM_PCRel: {
18388 // When selecting PC-Relative instructions, "Base" is not utilized as
18389 // we select the address as [PC+imm].
18390 Disp = N;
18391 break;
18392 }
18393 case PPC::AM_None:
18394 break;
18395 default: { // By default, X-Form is always available to be selected.
18396 // When a frame index is not aligned, we also match by XForm.
18397 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
18398 Base = FI ? N : N.getOperand(1);
18399 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
18400 N.getValueType())
18401 : N.getOperand(0);
18402 break;
18403 }
18404 }
18405 return Mode;
18406}
18407
18408CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
18409 bool Return,
18410 bool IsVarArg) const {
18411 switch (CC) {
18412 case CallingConv::Cold:
18413 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF);
18414 default:
18415 return CC_PPC64_ELF;
18416 }
18417}
18418
18419bool PPCTargetLowering::shouldInlineQuadwordAtomics() const {
18420 // TODO: 16-byte atomic type support for AIX is in progress; we should be able
18421 // to inline 16-byte atomic ops on AIX too in the future.
18422 return Subtarget.isPPC64() &&
18423 (EnableQuadwordAtomics || !Subtarget.getTargetTriple().isOSAIX()) &&
18424 Subtarget.hasQuadwordAtomics();
18425}
18426
18427TargetLowering::AtomicExpansionKind
18428PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18429 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18430 if (shouldInlineQuadwordAtomics() && Size == 128)
18431 return AtomicExpansionKind::MaskedIntrinsic;
18432
18433 switch (AI->getOperation()) {
18434 case AtomicRMWInst::UIncWrap:
18435 case AtomicRMWInst::UDecWrap:
18436 return AtomicExpansionKind::CmpXChg;
18437 default:
18438 return TargetLowering::shouldExpandAtomicRMWInIR(AI);
18439 }
18440
18441 llvm_unreachable("unreachable atomicrmw operation")::llvm::llvm_unreachable_internal("unreachable atomicrmw operation"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18441)
;
18442}
18443
18444TargetLowering::AtomicExpansionKind
18445PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18446 unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
18447 if (shouldInlineQuadwordAtomics() && Size == 128)
18448 return AtomicExpansionKind::MaskedIntrinsic;
18449 return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
18450}
18451
18452static Intrinsic::ID
18453getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
18454 switch (BinOp) {
18455 default:
18456 llvm_unreachable("Unexpected AtomicRMW BinOp")::llvm::llvm_unreachable_internal("Unexpected AtomicRMW BinOp"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18456)
;
18457 case AtomicRMWInst::Xchg:
18458 return Intrinsic::ppc_atomicrmw_xchg_i128;
18459 case AtomicRMWInst::Add:
18460 return Intrinsic::ppc_atomicrmw_add_i128;
18461 case AtomicRMWInst::Sub:
18462 return Intrinsic::ppc_atomicrmw_sub_i128;
18463 case AtomicRMWInst::And:
18464 return Intrinsic::ppc_atomicrmw_and_i128;
18465 case AtomicRMWInst::Or:
18466 return Intrinsic::ppc_atomicrmw_or_i128;
18467 case AtomicRMWInst::Xor:
18468 return Intrinsic::ppc_atomicrmw_xor_i128;
18469 case AtomicRMWInst::Nand:
18470 return Intrinsic::ppc_atomicrmw_nand_i128;
18471 }
18472}
18473
18474Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
18475 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
18476 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
18477 assert(shouldInlineQuadwordAtomics() && "Only support quadword now")(static_cast <bool> (shouldInlineQuadwordAtomics() &&
"Only support quadword now") ? void (0) : __assert_fail ("shouldInlineQuadwordAtomics() && \"Only support quadword now\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18477, __extension__
__PRETTY_FUNCTION__))
;
18478 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18479 Type *ValTy = Incr->getType();
18480 assert(ValTy->getPrimitiveSizeInBits() == 128)(static_cast <bool> (ValTy->getPrimitiveSizeInBits()
== 128) ? void (0) : __assert_fail ("ValTy->getPrimitiveSizeInBits() == 128"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18480, __extension__
__PRETTY_FUNCTION__))
;
18481 Function *RMW = Intrinsic::getDeclaration(
18482 M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
18483 Type *Int64Ty = Type::getInt64Ty(M->getContext());
18484 Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
18485 Value *IncrHi =
18486 Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
18487 Value *Addr =
18488 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18489 Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
18490 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18491 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18492 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18493 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18494 return Builder.CreateOr(
18495 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18496}
18497
18498Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
18499 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
18500 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
18501 assert(shouldInlineQuadwordAtomics() && "Only support quadword now")(static_cast <bool> (shouldInlineQuadwordAtomics() &&
"Only support quadword now") ? void (0) : __assert_fail ("shouldInlineQuadwordAtomics() && \"Only support quadword now\""
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18501, __extension__
__PRETTY_FUNCTION__))
;
18502 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18503 Type *ValTy = CmpVal->getType();
18504 assert(ValTy->getPrimitiveSizeInBits() == 128)(static_cast <bool> (ValTy->getPrimitiveSizeInBits()
== 128) ? void (0) : __assert_fail ("ValTy->getPrimitiveSizeInBits() == 128"
, "llvm/lib/Target/PowerPC/PPCISelLowering.cpp", 18504, __extension__
__PRETTY_FUNCTION__))
;
18505 Function *IntCmpXchg =
18506 Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
18507 Type *Int64Ty = Type::getInt64Ty(M->getContext());
18508 Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
18509 Value *CmpHi =
18510 Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
18511 Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
18512 Value *NewHi =
18513 Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
18514 Value *Addr =
18515 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18516 emitLeadingFence(Builder, CI, Ord);
18517 Value *LoHi =
18518 Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
18519 emitTrailingFence(Builder, CI, Ord);
18520 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18521 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18522 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18523 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18524 return Builder.CreateOr(
18525 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18526}