Bug Summary

File: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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -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~svn374877/build-llvm/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-10~svn374877/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/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~svn374877/build-llvm/lib/Target/PowerPC -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -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-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/lib/Target/PowerPC/PPCISelLowering.cpp

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