Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/PowerPC/PPCISelLowering.cpp

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