1//===- StackSafetyAnalysis.cpp - Stack memory safety analysis -------------===//
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//===----------------------------------------------------------------------===//
10
11#include "llvm/Analysis/StackSafetyAnalysis.h"
12#include "llvm/ADT/APInt.h"
13#include "llvm/ADT/SmallPtrSet.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/ADT/Statistic.h"
16#include "llvm/Analysis/ModuleSummaryAnalysis.h"
17#include "llvm/Analysis/ScalarEvolution.h"
18#include "llvm/Analysis/StackLifetime.h"
19#include "llvm/IR/ConstantRange.h"
20#include "llvm/IR/DerivedTypes.h"
21#include "llvm/IR/GlobalValue.h"
22#include "llvm/IR/InstIterator.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/IntrinsicInst.h"
26#include "llvm/IR/ModuleSummaryIndex.h"
27#include "llvm/InitializePasses.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/FormatVariadic.h"
31#include "llvm/Support/raw_ostream.h"
32#include <algorithm>
33#include <tuple>
34
35using namespace llvm;
36
37#define DEBUG_TYPE "stack-safety"
38
39STATISTIC(NumAllocaStackSafe, "Number of safe allocas");
40STATISTIC(NumAllocaTotal, "Number of total allocas");
41
42STATISTIC(NumCombinedCalleeLookupTotal,
43 "Number of total callee lookups on combined index.");
44STATISTIC(NumCombinedCalleeLookupFailed,
45 "Number of failed callee lookups on combined index.");
46STATISTIC(NumModuleCalleeLookupTotal,
47 "Number of total callee lookups on module index.");
48STATISTIC(NumModuleCalleeLookupFailed,
49 "Number of failed callee lookups on module index.");
50STATISTIC(NumCombinedParamAccessesBefore,
51 "Number of total param accesses before generateParamAccessSummary.");
52STATISTIC(NumCombinedParamAccessesAfter,
53 "Number of total param accesses after generateParamAccessSummary.");
54STATISTIC(NumCombinedDataFlowNodes,
55 "Number of total nodes in combined index for dataflow processing.");
56STATISTIC(NumIndexCalleeUnhandled, "Number of index callee which are unhandled.");
57STATISTIC(NumIndexCalleeMultipleWeak, "Number of index callee non-unique weak.");
58STATISTIC(NumIndexCalleeMultipleExternal, "Number of index callee non-unique external.");
59
60
61static cl::opt<int> StackSafetyMaxIterations("stack-safety-max-iterations",
62 cl::init(Val: 20), cl::Hidden);
63
64static cl::opt<bool> StackSafetyPrint("stack-safety-print", cl::init(Val: false),
65 cl::Hidden);
66
67static cl::opt<bool> StackSafetyRun("stack-safety-run", cl::init(Val: false),
68 cl::Hidden);
69
70namespace {
71
72// Check if we should bailout for such ranges.
73bool isUnsafe(const ConstantRange &R) {
74 return R.isEmptySet() || R.isFullSet() || R.isUpperSignWrapped();
75}
76
77ConstantRange addOverflowNever(const ConstantRange &L, const ConstantRange &R) {
78 assert(!L.isSignWrappedSet());
79 assert(!R.isSignWrappedSet());
80 if (L.signedAddMayOverflow(Other: R) !=
81 ConstantRange::OverflowResult::NeverOverflows)
82 return ConstantRange::getFull(BitWidth: L.getBitWidth());
83 ConstantRange Result = L.add(Other: R);
84 assert(!Result.isSignWrappedSet());
85 return Result;
86}
87
88ConstantRange unionNoWrap(const ConstantRange &L, const ConstantRange &R) {
89 assert(!L.isSignWrappedSet());
90 assert(!R.isSignWrappedSet());
91 auto Result = L.unionWith(CR: R);
92 // Two non-wrapped sets can produce wrapped.
93 if (Result.isSignWrappedSet())
94 Result = ConstantRange::getFull(BitWidth: Result.getBitWidth());
95 return Result;
96}
97
98/// Describes use of address in as a function call argument.
99template <typename CalleeTy> struct CallInfo {
100 /// Function being called.
101 const CalleeTy *Callee = nullptr;
102 /// Index of argument which pass address.
103 size_t ParamNo = 0;
104
105 CallInfo(const CalleeTy *Callee, size_t ParamNo)
106 : Callee(Callee), ParamNo(ParamNo) {}
107
108 struct Less {
109 bool operator()(const CallInfo &L, const CallInfo &R) const {
110 return std::tie(L.ParamNo, L.Callee) < std::tie(R.ParamNo, R.Callee);
111 }
112 };
113};
114
115/// Describe uses of address (alloca or parameter) inside of the function.
116template <typename CalleeTy> struct UseInfo {
117 // Access range if the address (alloca or parameters).
118 // It is allowed to be empty-set when there are no known accesses.
119 ConstantRange Range;
120 std::set<const Instruction *> UnsafeAccesses;
121
122 // List of calls which pass address as an argument.
123 // Value is offset range of address from base address (alloca or calling
124 // function argument). Range should never set to empty-set, that is an invalid
125 // access range that can cause empty-set to be propagated with
126 // ConstantRange::add
127 using CallsTy = std::map<CallInfo<CalleeTy>, ConstantRange,
128 typename CallInfo<CalleeTy>::Less>;
129 CallsTy Calls;
130
131 UseInfo(unsigned PointerSize) : Range{PointerSize, false} {}
132
133 void updateRange(const ConstantRange &R) { Range = unionNoWrap(L: Range, R); }
134 void addRange(const Instruction *I, const ConstantRange &R, bool IsSafe) {
135 if (!IsSafe)
136 UnsafeAccesses.insert(x: I);
137 updateRange(R);
138 }
139};
140
141template <typename CalleeTy>
142raw_ostream &operator<<(raw_ostream &OS, const UseInfo<CalleeTy> &U) {
143 OS << U.Range;
144 for (auto &Call : U.Calls)
145 OS << ", "
146 << "@" << Call.first.Callee->getName() << "(arg" << Call.first.ParamNo
147 << ", " << Call.second << ")";
148 return OS;
149}
150
151/// Calculate the allocation size of a given alloca. Returns empty range
152// in case of confution.
153ConstantRange getStaticAllocaSizeRange(const AllocaInst &AI) {
154 const DataLayout &DL = AI.getDataLayout();
155 TypeSize TS = AI.getAllocationBaseSize(DL);
156 unsigned PointerSize = DL.getPointerTypeSizeInBits(AI.getType());
157 // Fallback to empty range for alloca size.
158 ConstantRange R = ConstantRange::getEmpty(BitWidth: PointerSize);
159 if (TS.isScalable())
160 return R;
161 APInt APSize(PointerSize, TS.getFixedValue(), true);
162 if (APSize.isNonPositive())
163 return R;
164 if (AI.isArrayAllocation()) {
165 const auto *C = dyn_cast<ConstantInt>(Val: AI.getArraySize());
166 if (!C)
167 return R;
168 bool Overflow = false;
169 APInt Mul = C->getValue();
170 if (Mul.isNonPositive())
171 return R;
172 Mul = Mul.sextOrTrunc(width: PointerSize);
173 APSize = APSize.smul_ov(RHS: Mul, Overflow);
174 if (Overflow)
175 return R;
176 }
177 R = ConstantRange(APInt::getZero(numBits: PointerSize), APSize);
178 assert(!isUnsafe(R));
179 return R;
180}
181
182template <typename CalleeTy> struct FunctionInfo {
183 std::map<const AllocaInst *, UseInfo<CalleeTy>> Allocas;
184 std::map<uint32_t, UseInfo<CalleeTy>> Params;
185 // TODO: describe return value as depending on one or more of its arguments.
186
187 // StackSafetyDataFlowAnalysis counter stored here for faster access.
188 int UpdateCount = 0;
189
190 void print(raw_ostream &O, StringRef Name, const Function *F) const {
191 // TODO: Consider different printout format after
192 // StackSafetyDataFlowAnalysis. Calls and parameters are irrelevant then.
193 O << " @" << Name << ((F && F->isDSOLocal()) ? "" : " dso_preemptable")
194 << ((F && F->isInterposable()) ? " interposable" : "") << "\n";
195
196 O << " args uses:\n";
197 for (auto &KV : Params) {
198 O << " ";
199 if (F)
200 O << F->getArg(i: KV.first)->getName();
201 else
202 O << formatv("arg{0}", KV.first);
203 O << "[]: " << KV.second << "\n";
204 }
205
206 O << " allocas uses:\n";
207 if (F) {
208 for (const auto &I : instructions(F)) {
209 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: &I)) {
210 auto &AS = Allocas.find(AI)->second;
211 O << " " << AI->getName() << "["
212 << getStaticAllocaSizeRange(AI: *AI).getUpper() << "]: " << AS << "\n";
213 }
214 }
215 } else {
216 assert(Allocas.empty());
217 }
218 }
219};
220
221using GVToSSI = std::map<const GlobalValue *, FunctionInfo<GlobalValue>>;
222
223} // namespace
224
225struct StackSafetyInfo::InfoTy {
226 FunctionInfo<GlobalValue> Info;
227};
228
229struct StackSafetyGlobalInfo::InfoTy {
230 GVToSSI Info;
231 SmallPtrSet<const AllocaInst *, 8> SafeAllocas;
232 std::set<const Instruction *> UnsafeAccesses;
233};
234
235namespace {
236
237class StackSafetyLocalAnalysis {
238 Function &F;
239 const DataLayout &DL;
240 ScalarEvolution &SE;
241 unsigned PointerSize = 0;
242
243 const ConstantRange UnknownRange;
244
245 /// FIXME: This function is a bandaid, it's only needed
246 /// because this pass doesn't handle address spaces of different pointer
247 /// sizes.
248 ///
249 /// \returns \p Val's SCEV as a pointer of AS zero, or nullptr if it can't be
250 /// converted to AS 0.
251 const SCEV *getSCEVAsPointer(Value *Val);
252
253 ConstantRange offsetFrom(Value *Addr, Value *Base);
254 ConstantRange getAccessRange(Value *Addr, Value *Base,
255 const ConstantRange &SizeRange);
256 ConstantRange getAccessRange(Value *Addr, Value *Base, TypeSize Size);
257 ConstantRange getMemIntrinsicAccessRange(const MemIntrinsic *MI, const Use &U,
258 Value *Base);
259
260 void analyzeAllUses(Value *Ptr, UseInfo<GlobalValue> &AS,
261 const StackLifetime &SL);
262
263
264 bool isSafeAccess(const Use &U, AllocaInst *AI, const SCEV *AccessSize);
265 bool isSafeAccess(const Use &U, AllocaInst *AI, Value *V);
266 bool isSafeAccess(const Use &U, AllocaInst *AI, TypeSize AccessSize);
267
268public:
269 StackSafetyLocalAnalysis(Function &F, ScalarEvolution &SE)
270 : F(F), DL(F.getDataLayout()), SE(SE),
271 PointerSize(DL.getPointerSizeInBits()),
272 UnknownRange(PointerSize, true) {}
273
274 // Run the transformation on the associated function.
275 FunctionInfo<GlobalValue> run();
276};
277
278const SCEV *StackSafetyLocalAnalysis::getSCEVAsPointer(Value *Val) {
279 Type *ValTy = Val->getType();
280
281 // We don't handle targets with multiple address spaces.
282 if (!ValTy->isPointerTy()) {
283 auto *PtrTy = PointerType::getUnqual(C&: SE.getContext());
284 return SE.getTruncateOrZeroExtend(V: SE.getSCEV(V: Val), Ty: PtrTy);
285 }
286
287 if (ValTy->getPointerAddressSpace() != 0)
288 return nullptr;
289 return SE.getSCEV(V: Val);
290}
291
292ConstantRange StackSafetyLocalAnalysis::offsetFrom(Value *Addr, Value *Base) {
293 if (!SE.isSCEVable(Ty: Addr->getType()) || !SE.isSCEVable(Ty: Base->getType()))
294 return UnknownRange;
295
296 const SCEV *AddrExp = getSCEVAsPointer(Val: Addr);
297 const SCEV *BaseExp = getSCEVAsPointer(Val: Base);
298 if (!AddrExp || !BaseExp)
299 return UnknownRange;
300
301 const SCEV *Diff = SE.getMinusSCEV(LHS: AddrExp, RHS: BaseExp);
302 if (isa<SCEVCouldNotCompute>(Val: Diff))
303 return UnknownRange;
304
305 ConstantRange Offset = SE.getSignedRange(S: Diff);
306 if (isUnsafe(R: Offset))
307 return UnknownRange;
308 return Offset.sextOrTrunc(BitWidth: PointerSize);
309}
310
311ConstantRange
312StackSafetyLocalAnalysis::getAccessRange(Value *Addr, Value *Base,
313 const ConstantRange &SizeRange) {
314 // Zero-size loads and stores do not access memory.
315 if (SizeRange.isEmptySet())
316 return ConstantRange::getEmpty(BitWidth: PointerSize);
317 assert(!isUnsafe(SizeRange));
318
319 ConstantRange Offsets = offsetFrom(Addr, Base);
320 if (isUnsafe(R: Offsets))
321 return UnknownRange;
322
323 Offsets = addOverflowNever(L: Offsets, R: SizeRange);
324 if (isUnsafe(R: Offsets))
325 return UnknownRange;
326 return Offsets;
327}
328
329ConstantRange StackSafetyLocalAnalysis::getAccessRange(Value *Addr, Value *Base,
330 TypeSize Size) {
331 if (Size.isScalable())
332 return UnknownRange;
333 APInt APSize(PointerSize, Size.getFixedValue(), true);
334 if (APSize.isNegative())
335 return UnknownRange;
336 return getAccessRange(Addr, Base,
337 SizeRange: ConstantRange(APInt::getZero(numBits: PointerSize), APSize));
338}
339
340ConstantRange StackSafetyLocalAnalysis::getMemIntrinsicAccessRange(
341 const MemIntrinsic *MI, const Use &U, Value *Base) {
342 if (const auto *MTI = dyn_cast<MemTransferInst>(Val: MI)) {
343 if (MTI->getRawSource() != U && MTI->getRawDest() != U)
344 return ConstantRange::getEmpty(BitWidth: PointerSize);
345 } else {
346 if (MI->getRawDest() != U)
347 return ConstantRange::getEmpty(BitWidth: PointerSize);
348 }
349
350 auto *CalculationTy = IntegerType::getIntNTy(C&: SE.getContext(), N: PointerSize);
351 if (!SE.isSCEVable(Ty: MI->getLength()->getType()))
352 return UnknownRange;
353
354 const SCEV *Expr =
355 SE.getTruncateOrZeroExtend(V: SE.getSCEV(V: MI->getLength()), Ty: CalculationTy);
356 ConstantRange Sizes = SE.getSignedRange(S: Expr);
357 if (!Sizes.getUpper().isStrictlyPositive() || isUnsafe(R: Sizes))
358 return UnknownRange;
359 Sizes = Sizes.sextOrTrunc(BitWidth: PointerSize);
360 ConstantRange SizeRange(APInt::getZero(numBits: PointerSize), Sizes.getUpper() - 1);
361 return getAccessRange(Addr: U, Base, SizeRange);
362}
363
364bool StackSafetyLocalAnalysis::isSafeAccess(const Use &U, AllocaInst *AI,
365 Value *V) {
366 return isSafeAccess(U, AI, AccessSize: SE.getSCEV(V));
367}
368
369bool StackSafetyLocalAnalysis::isSafeAccess(const Use &U, AllocaInst *AI,
370 TypeSize TS) {
371 if (TS.isScalable())
372 return false;
373 auto *CalculationTy = IntegerType::getIntNTy(C&: SE.getContext(), N: PointerSize);
374 const SCEV *SV = SE.getConstant(Ty: CalculationTy, V: TS.getFixedValue());
375 return isSafeAccess(U, AI, AccessSize: SV);
376}
377
378bool StackSafetyLocalAnalysis::isSafeAccess(const Use &U, AllocaInst *AI,
379 const SCEV *AccessSize) {
380
381 if (!AI)
382 return true; // This only judges whether it is a safe *stack* access.
383 if (isa<SCEVCouldNotCompute>(Val: AccessSize))
384 return false;
385
386 const auto *I = cast<Instruction>(Val: U.getUser());
387
388 const SCEV *AddrExp = getSCEVAsPointer(Val: U.get());
389 const SCEV *BaseExp = getSCEVAsPointer(Val: AI);
390 if (!AddrExp || !BaseExp)
391 return false;
392
393 const SCEV *Diff = SE.getMinusSCEV(LHS: AddrExp, RHS: BaseExp);
394 if (isa<SCEVCouldNotCompute>(Val: Diff))
395 return false;
396
397 auto Size = getStaticAllocaSizeRange(AI: *AI);
398
399 auto *CalculationTy = IntegerType::getIntNTy(C&: SE.getContext(), N: PointerSize);
400 auto ToDiffTy = [&](const SCEV *V) {
401 return SE.getTruncateOrZeroExtend(V, Ty: CalculationTy);
402 };
403 const SCEV *Min = ToDiffTy(SE.getConstant(Val: Size.getLower()));
404 const SCEV *Max = SE.getMinusSCEV(LHS: ToDiffTy(SE.getConstant(Val: Size.getUpper())),
405 RHS: ToDiffTy(AccessSize));
406 return SE.evaluatePredicateAt(Pred: ICmpInst::Predicate::ICMP_SGE, LHS: Diff, RHS: Min, CtxI: I)
407 .value_or(u: false) &&
408 SE.evaluatePredicateAt(Pred: ICmpInst::Predicate::ICMP_SLE, LHS: Diff, RHS: Max, CtxI: I)
409 .value_or(u: false);
410}
411
412/// The function analyzes all local uses of Ptr (alloca or argument) and
413/// calculates local access range and all function calls where it was used.
414void StackSafetyLocalAnalysis::analyzeAllUses(Value *Ptr,
415 UseInfo<GlobalValue> &US,
416 const StackLifetime &SL) {
417 SmallPtrSet<const Value *, 16> Visited;
418 SmallVector<const Value *, 8> WorkList;
419 WorkList.push_back(Elt: Ptr);
420 AllocaInst *AI = dyn_cast<AllocaInst>(Val: Ptr);
421
422 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
423 while (!WorkList.empty()) {
424 const Value *V = WorkList.pop_back_val();
425 for (const Use &UI : V->uses()) {
426 const auto *I = cast<Instruction>(Val: UI.getUser());
427 if (!SL.isReachable(I))
428 continue;
429
430 assert(V == UI.get());
431
432 auto RecordStore = [&](const Value* StoredVal) {
433 if (V == StoredVal) {
434 // Stored the pointer - conservatively assume it may be unsafe.
435 US.addRange(I, R: UnknownRange, /*IsSafe=*/false);
436 return;
437 }
438 if (AI && !SL.isAliveAfter(AI, I)) {
439 US.addRange(I, R: UnknownRange, /*IsSafe=*/false);
440 return;
441 }
442 auto TypeSize = DL.getTypeStoreSize(Ty: StoredVal->getType());
443 auto AccessRange = getAccessRange(Addr: UI, Base: Ptr, Size: TypeSize);
444 bool Safe = isSafeAccess(U: UI, AI, TS: TypeSize);
445 US.addRange(I, R: AccessRange, IsSafe: Safe);
446 return;
447 };
448
449 switch (I->getOpcode()) {
450 case Instruction::Load: {
451 if (AI && !SL.isAliveAfter(AI, I)) {
452 US.addRange(I, R: UnknownRange, /*IsSafe=*/false);
453 break;
454 }
455 auto TypeSize = DL.getTypeStoreSize(Ty: I->getType());
456 auto AccessRange = getAccessRange(Addr: UI, Base: Ptr, Size: TypeSize);
457 bool Safe = isSafeAccess(U: UI, AI, TS: TypeSize);
458 US.addRange(I, R: AccessRange, IsSafe: Safe);
459 break;
460 }
461
462 case Instruction::VAArg:
463 // "va-arg" from a pointer is safe.
464 break;
465 case Instruction::Store:
466 RecordStore(cast<StoreInst>(Val: I)->getValueOperand());
467 break;
468 case Instruction::AtomicCmpXchg:
469 RecordStore(cast<AtomicCmpXchgInst>(Val: I)->getNewValOperand());
470 break;
471 case Instruction::AtomicRMW:
472 RecordStore(cast<AtomicRMWInst>(Val: I)->getValOperand());
473 break;
474
475 case Instruction::Ret:
476 // Information leak.
477 // FIXME: Process parameters correctly. This is a leak only if we return
478 // alloca.
479 US.addRange(I, R: UnknownRange, /*IsSafe=*/false);
480 break;
481
482 case Instruction::Call:
483 case Instruction::Invoke: {
484 if (I->isLifetimeStartOrEnd())
485 break;
486
487 if (AI && !SL.isAliveAfter(AI, I)) {
488 US.addRange(I, R: UnknownRange, /*IsSafe=*/false);
489 break;
490 }
491 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Val: I)) {
492 auto AccessRange = getMemIntrinsicAccessRange(MI, U: UI, Base: Ptr);
493 bool Safe = false;
494 if (const auto *MTI = dyn_cast<MemTransferInst>(Val: MI)) {
495 if (MTI->getRawSource() != UI && MTI->getRawDest() != UI)
496 Safe = true;
497 } else if (MI->getRawDest() != UI) {
498 Safe = true;
499 }
500 Safe = Safe || isSafeAccess(U: UI, AI, V: MI->getLength());
501 US.addRange(I, R: AccessRange, IsSafe: Safe);
502 break;
503 }
504
505 const auto &CB = cast<CallBase>(Val: *I);
506 if (CB.getReturnedArgOperand() == V) {
507 if (Visited.insert(Ptr: I).second)
508 WorkList.push_back(Elt: cast<const Instruction>(Val: I));
509 }
510
511 if (!CB.isArgOperand(U: &UI)) {
512 US.addRange(I, R: UnknownRange, /*IsSafe=*/false);
513 break;
514 }
515
516 unsigned ArgNo = CB.getArgOperandNo(U: &UI);
517 if (CB.isByValArgument(ArgNo)) {
518 auto TypeSize = DL.getTypeStoreSize(Ty: CB.getParamByValType(ArgNo));
519 auto AccessRange = getAccessRange(Addr: UI, Base: Ptr, Size: TypeSize);
520 bool Safe = isSafeAccess(U: UI, AI, TS: TypeSize);
521 US.addRange(I, R: AccessRange, IsSafe: Safe);
522 break;
523 }
524
525 // FIXME: consult devirt?
526 // Do not follow aliases, otherwise we could inadvertently follow
527 // dso_preemptable aliases or aliases with interposable linkage.
528 const GlobalValue *Callee =
529 dyn_cast<GlobalValue>(Val: CB.getCalledOperand()->stripPointerCasts());
530 if (!Callee || isa<GlobalIFunc>(Val: Callee) ||
531 isa<GlobalVariable>(Val: Callee)) {
532 US.addRange(I, R: UnknownRange, /*IsSafe=*/false);
533 break;
534 }
535
536 assert(isa<Function>(Callee) || isa<GlobalAlias>(Callee));
537 ConstantRange Offsets = offsetFrom(Addr: UI, Base: Ptr);
538 auto Insert =
539 US.Calls.emplace(args: CallInfo<GlobalValue>(Callee, ArgNo), args&: Offsets);
540 if (!Insert.second)
541 Insert.first->second = Insert.first->second.unionWith(CR: Offsets);
542 break;
543 }
544
545 default:
546 if (Visited.insert(Ptr: I).second)
547 WorkList.push_back(Elt: cast<const Instruction>(Val: I));
548 }
549 }
550 }
551}
552
553FunctionInfo<GlobalValue> StackSafetyLocalAnalysis::run() {
554 FunctionInfo<GlobalValue> Info;
555 assert(!F.isDeclaration() &&
556 "Can't run StackSafety on a function declaration");
557
558 LLVM_DEBUG(dbgs() << "[StackSafety] " << F.getName() << "\n");
559
560 SmallVector<AllocaInst *, 64> Allocas;
561 for (auto &I : instructions(F))
562 if (auto *AI = dyn_cast<AllocaInst>(Val: &I))
563 Allocas.push_back(Elt: AI);
564 StackLifetime SL(F, Allocas, StackLifetime::LivenessType::Must);
565 SL.run();
566
567 for (auto *AI : Allocas) {
568 auto &UI = Info.Allocas.emplace(args&: AI, args&: PointerSize).first->second;
569 analyzeAllUses(Ptr: AI, US&: UI, SL);
570 }
571
572 for (Argument &A : F.args()) {
573 // Non pointers and bypass arguments are not going to be used in any global
574 // processing.
575 if (A.getType()->isPointerTy() && !A.hasByValAttr()) {
576 auto &UI = Info.Params.emplace(args: A.getArgNo(), args&: PointerSize).first->second;
577 analyzeAllUses(Ptr: &A, US&: UI, SL);
578 }
579 }
580
581 LLVM_DEBUG(Info.print(dbgs(), F.getName(), &F));
582 LLVM_DEBUG(dbgs() << "\n[StackSafety] done\n");
583 return Info;
584}
585
586template <typename CalleeTy> class StackSafetyDataFlowAnalysis {
587 using FunctionMap = std::map<const CalleeTy *, FunctionInfo<CalleeTy>>;
588
589 FunctionMap Functions;
590 const ConstantRange UnknownRange;
591
592 // Callee-to-Caller multimap.
593 DenseMap<const CalleeTy *, SmallVector<const CalleeTy *, 4>> Callers;
594 SetVector<const CalleeTy *> WorkList;
595
596 bool updateOneUse(UseInfo<CalleeTy> &US, bool UpdateToFullSet);
597 void updateOneNode(const CalleeTy *Callee, FunctionInfo<CalleeTy> &FS);
598 void updateOneNode(const CalleeTy *Callee) {
599 updateOneNode(Callee, Functions.find(Callee)->second);
600 }
601 void updateAllNodes() {
602 for (auto &F : Functions)
603 updateOneNode(F.first, F.second);
604 }
605 void runDataFlow();
606#ifndef NDEBUG
607 void verifyFixedPoint();
608#endif
609
610public:
611 StackSafetyDataFlowAnalysis(uint32_t PointerBitWidth, FunctionMap Functions)
612 : Functions(std::move(Functions)),
613 UnknownRange(ConstantRange::getFull(PointerBitWidth)) {}
614
615 const FunctionMap &run();
616
617 ConstantRange getArgumentAccessRange(const CalleeTy *Callee, unsigned ParamNo,
618 const ConstantRange &Offsets) const;
619};
620
621template <typename CalleeTy>
622ConstantRange StackSafetyDataFlowAnalysis<CalleeTy>::getArgumentAccessRange(
623 const CalleeTy *Callee, unsigned ParamNo,
624 const ConstantRange &Offsets) const {
625 auto FnIt = Functions.find(Callee);
626 // Unknown callee (outside of LTO domain or an indirect call).
627 if (FnIt == Functions.end())
628 return UnknownRange;
629 auto &FS = FnIt->second;
630 auto ParamIt = FS.Params.find(ParamNo);
631 if (ParamIt == FS.Params.end())
632 return UnknownRange;
633 auto &Access = ParamIt->second.Range;
634 if (Access.isEmptySet())
635 return Access;
636 if (Access.isFullSet())
637 return UnknownRange;
638 return addOverflowNever(Access, Offsets);
639}
640
641template <typename CalleeTy>
642bool StackSafetyDataFlowAnalysis<CalleeTy>::updateOneUse(UseInfo<CalleeTy> &US,
643 bool UpdateToFullSet) {
644 bool Changed = false;
645 for (auto &KV : US.Calls) {
646 assert(!KV.second.isEmptySet() &&
647 "Param range can't be empty-set, invalid offset range");
648
649 ConstantRange CalleeRange =
650 getArgumentAccessRange(Callee: KV.first.Callee, ParamNo: KV.first.ParamNo, Offsets: KV.second);
651 if (!US.Range.contains(CalleeRange)) {
652 Changed = true;
653 if (UpdateToFullSet)
654 US.Range = UnknownRange;
655 else
656 US.updateRange(CalleeRange);
657 }
658 }
659 return Changed;
660}
661
662template <typename CalleeTy>
663void StackSafetyDataFlowAnalysis<CalleeTy>::updateOneNode(
664 const CalleeTy *Callee, FunctionInfo<CalleeTy> &FS) {
665 bool UpdateToFullSet = FS.UpdateCount > StackSafetyMaxIterations;
666 bool Changed = false;
667 for (auto &KV : FS.Params)
668 Changed |= updateOneUse(US&: KV.second, UpdateToFullSet);
669
670 if (Changed) {
671 LLVM_DEBUG(dbgs() << "=== update [" << FS.UpdateCount
672 << (UpdateToFullSet ? ", full-set" : "") << "] " << &FS
673 << "\n");
674 // Callers of this function may need updating.
675 WorkList.insert_range(Callers[Callee]);
676
677 ++FS.UpdateCount;
678 }
679}
680
681template <typename CalleeTy>
682void StackSafetyDataFlowAnalysis<CalleeTy>::runDataFlow() {
683 SmallVector<const CalleeTy *, 16> Callees;
684 for (auto &F : Functions) {
685 Callees.clear();
686 auto &FS = F.second;
687 for (auto &KV : FS.Params)
688 for (auto &CS : KV.second.Calls)
689 Callees.push_back(CS.first.Callee);
690
691 llvm::sort(Callees);
692 Callees.erase(llvm::unique(Callees), Callees.end());
693
694 for (auto &Callee : Callees)
695 Callers[Callee].push_back(F.first);
696 }
697
698 updateAllNodes();
699
700 while (!WorkList.empty()) {
701 const CalleeTy *Callee = WorkList.pop_back_val();
702 updateOneNode(Callee);
703 }
704}
705
706#ifndef NDEBUG
707template <typename CalleeTy>
708void StackSafetyDataFlowAnalysis<CalleeTy>::verifyFixedPoint() {
709 WorkList.clear();
710 updateAllNodes();
711 assert(WorkList.empty());
712}
713#endif
714
715template <typename CalleeTy>
716const typename StackSafetyDataFlowAnalysis<CalleeTy>::FunctionMap &
717StackSafetyDataFlowAnalysis<CalleeTy>::run() {
718 runDataFlow();
719 LLVM_DEBUG(verifyFixedPoint());
720 return Functions;
721}
722
723FunctionSummary *findCalleeFunctionSummary(ValueInfo VI, StringRef ModuleId) {
724 if (!VI)
725 return nullptr;
726 auto SummaryList = VI.getSummaryList();
727 GlobalValueSummary* S = nullptr;
728 for (const auto& GVS : SummaryList) {
729 if (!GVS->isLive())
730 continue;
731 if (const AliasSummary *AS = dyn_cast<AliasSummary>(Val: GVS.get()))
732 if (!AS->hasAliasee())
733 continue;
734 if (!isa<FunctionSummary>(Val: GVS->getBaseObject()))
735 continue;
736 if (GlobalValue::isLocalLinkage(Linkage: GVS->linkage())) {
737 if (GVS->modulePath() == ModuleId) {
738 S = GVS.get();
739 break;
740 }
741 } else if (GlobalValue::isExternalLinkage(Linkage: GVS->linkage())) {
742 if (S) {
743 ++NumIndexCalleeMultipleExternal;
744 return nullptr;
745 }
746 S = GVS.get();
747 } else if (GlobalValue::isWeakLinkage(Linkage: GVS->linkage())) {
748 if (S) {
749 ++NumIndexCalleeMultipleWeak;
750 return nullptr;
751 }
752 S = GVS.get();
753 } else if (GlobalValue::isAvailableExternallyLinkage(Linkage: GVS->linkage()) ||
754 GlobalValue::isLinkOnceLinkage(Linkage: GVS->linkage())) {
755 if (SummaryList.size() == 1)
756 S = GVS.get();
757 // According thinLTOResolvePrevailingGUID these are unlikely prevailing.
758 } else {
759 ++NumIndexCalleeUnhandled;
760 }
761 };
762 while (S) {
763 if (!S->isLive() || !S->isDSOLocal())
764 return nullptr;
765 if (FunctionSummary *FS = dyn_cast<FunctionSummary>(Val: S))
766 return FS;
767 AliasSummary *AS = dyn_cast<AliasSummary>(Val: S);
768 if (!AS || !AS->hasAliasee())
769 return nullptr;
770 S = AS->getBaseObject();
771 if (S == AS)
772 return nullptr;
773 }
774 return nullptr;
775}
776
777const Function *findCalleeInModule(const GlobalValue *GV) {
778 while (GV) {
779 if (GV->isDeclaration() || GV->isInterposable() || !GV->isDSOLocal())
780 return nullptr;
781 if (const Function *F = dyn_cast<Function>(Val: GV))
782 return F;
783 const GlobalAlias *A = dyn_cast<GlobalAlias>(Val: GV);
784 if (!A)
785 return nullptr;
786 GV = A->getAliaseeObject();
787 if (GV == A)
788 return nullptr;
789 }
790 return nullptr;
791}
792
793const ConstantRange *findParamAccess(const FunctionSummary &FS,
794 uint32_t ParamNo) {
795 assert(FS.isLive());
796 assert(FS.isDSOLocal());
797 for (const auto &PS : FS.paramAccesses())
798 if (ParamNo == PS.ParamNo)
799 return &PS.Use;
800 return nullptr;
801}
802
803void resolveAllCalls(UseInfo<GlobalValue> &Use,
804 const ModuleSummaryIndex *Index) {
805 ConstantRange FullSet(Use.Range.getBitWidth(), true);
806 // Move Use.Calls to a temp storage and repopulate - don't use std::move as it
807 // leaves Use.Calls in an undefined state.
808 UseInfo<GlobalValue>::CallsTy TmpCalls;
809 std::swap(x&: TmpCalls, y&: Use.Calls);
810 for (const auto &C : TmpCalls) {
811 const Function *F = findCalleeInModule(GV: C.first.Callee);
812 if (F) {
813 Use.Calls.emplace(args: CallInfo<GlobalValue>(F, C.first.ParamNo), args: C.second);
814 continue;
815 }
816
817 if (!Index)
818 return Use.updateRange(R: FullSet);
819 FunctionSummary *FS =
820 findCalleeFunctionSummary(VI: Index->getValueInfo(GUID: C.first.Callee->getGUID()),
821 ModuleId: C.first.Callee->getParent()->getModuleIdentifier());
822 ++NumModuleCalleeLookupTotal;
823 if (!FS) {
824 ++NumModuleCalleeLookupFailed;
825 return Use.updateRange(R: FullSet);
826 }
827 const ConstantRange *Found = findParamAccess(FS: *FS, ParamNo: C.first.ParamNo);
828 if (!Found || Found->isFullSet())
829 return Use.updateRange(R: FullSet);
830 ConstantRange Access = Found->sextOrTrunc(BitWidth: Use.Range.getBitWidth());
831 if (!Access.isEmptySet())
832 Use.updateRange(R: addOverflowNever(L: Access, R: C.second));
833 }
834}
835
836GVToSSI createGlobalStackSafetyInfo(
837 std::map<const GlobalValue *, FunctionInfo<GlobalValue>> Functions,
838 const ModuleSummaryIndex *Index) {
839 GVToSSI SSI;
840 if (Functions.empty())
841 return SSI;
842
843 // FIXME: Simplify printing and remove copying here.
844 auto Copy = Functions;
845
846 for (auto &FnKV : Copy)
847 for (auto &KV : FnKV.second.Params) {
848 resolveAllCalls(Use&: KV.second, Index);
849 if (KV.second.Range.isFullSet())
850 KV.second.Calls.clear();
851 }
852
853 uint32_t PointerSize =
854 Copy.begin()->first->getDataLayout().getPointerSizeInBits();
855 StackSafetyDataFlowAnalysis<GlobalValue> SSDFA(PointerSize, std::move(Copy));
856
857 for (const auto &F : SSDFA.run()) {
858 auto FI = F.second;
859 auto &SrcF = Functions[F.first];
860 for (auto &KV : FI.Allocas) {
861 auto &A = KV.second;
862 resolveAllCalls(Use&: A, Index);
863 for (auto &C : A.Calls) {
864 A.updateRange(R: SSDFA.getArgumentAccessRange(Callee: C.first.Callee,
865 ParamNo: C.first.ParamNo, Offsets: C.second));
866 }
867 // FIXME: This is needed only to preserve calls in print() results.
868 A.Calls = SrcF.Allocas.find(x: KV.first)->second.Calls;
869 }
870 for (auto &KV : FI.Params) {
871 auto &P = KV.second;
872 P.Calls = SrcF.Params.find(x: KV.first)->second.Calls;
873 }
874 SSI[F.first] = std::move(FI);
875 }
876
877 return SSI;
878}
879
880} // end anonymous namespace
881
882StackSafetyInfo::StackSafetyInfo() = default;
883
884StackSafetyInfo::StackSafetyInfo(Function *F,
885 std::function<ScalarEvolution &()> GetSE)
886 : F(F), GetSE(GetSE) {}
887
888StackSafetyInfo::StackSafetyInfo(StackSafetyInfo &&) = default;
889
890StackSafetyInfo &StackSafetyInfo::operator=(StackSafetyInfo &&) = default;
891
892StackSafetyInfo::~StackSafetyInfo() = default;
893
894const StackSafetyInfo::InfoTy &StackSafetyInfo::getInfo() const {
895 if (!Info) {
896 StackSafetyLocalAnalysis SSLA(*F, GetSE());
897 Info.reset(p: new InfoTy{.Info: SSLA.run()});
898 }
899 return *Info;
900}
901
902void StackSafetyInfo::print(raw_ostream &O) const {
903 getInfo().Info.print(O, Name: F->getName(), F);
904 O << "\n";
905}
906
907const StackSafetyGlobalInfo::InfoTy &StackSafetyGlobalInfo::getInfo() const {
908 if (!Info) {
909 std::map<const GlobalValue *, FunctionInfo<GlobalValue>> Functions;
910 for (auto &F : M->functions()) {
911 if (!F.isDeclaration()) {
912 auto FI = GetSSI(F).getInfo().Info;
913 Functions.emplace(args: &F, args: std::move(FI));
914 }
915 }
916 Info.reset(p: new InfoTy{
917 .Info: createGlobalStackSafetyInfo(Functions: std::move(Functions), Index), .SafeAllocas: {}, .UnsafeAccesses: {}});
918
919 for (auto &FnKV : Info->Info) {
920 for (auto &KV : FnKV.second.Allocas) {
921 ++NumAllocaTotal;
922 const AllocaInst *AI = KV.first;
923 auto AIRange = getStaticAllocaSizeRange(AI: *AI);
924 if (AIRange.contains(CR: KV.second.Range)) {
925 Info->SafeAllocas.insert(Ptr: AI);
926 ++NumAllocaStackSafe;
927 }
928 Info->UnsafeAccesses.insert(first: KV.second.UnsafeAccesses.begin(),
929 last: KV.second.UnsafeAccesses.end());
930 }
931 }
932
933 if (StackSafetyPrint)
934 print(O&: errs());
935 }
936 return *Info;
937}
938
939std::vector<FunctionSummary::ParamAccess>
940StackSafetyInfo::getParamAccesses(ModuleSummaryIndex &Index) const {
941 // Implementation transforms internal representation of parameter information
942 // into FunctionSummary format.
943 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
944 for (const auto &KV : getInfo().Info.Params) {
945 auto &PS = KV.second;
946 // Parameter accessed by any or unknown offset, represented as FullSet by
947 // StackSafety, is handled as the parameter for which we have no
948 // StackSafety info at all. So drop it to reduce summary size.
949 if (PS.Range.isFullSet())
950 continue;
951
952 ParamAccesses.emplace_back(args: KV.first, args: PS.Range);
953 FunctionSummary::ParamAccess &Param = ParamAccesses.back();
954
955 Param.Calls.reserve(n: PS.Calls.size());
956 for (const auto &C : PS.Calls) {
957 // Parameter forwarded into another function by any or unknown offset
958 // will make ParamAccess::Range as FullSet anyway. So we can drop the
959 // entire parameter like we did above.
960 // TODO(vitalybuka): Return already filtered parameters from getInfo().
961 if (C.second.isFullSet()) {
962 ParamAccesses.pop_back();
963 break;
964 }
965 Param.Calls.emplace_back(args: C.first.ParamNo,
966 args: Index.getOrInsertValueInfo(GV: C.first.Callee),
967 args: C.second);
968 }
969 }
970 for (FunctionSummary::ParamAccess &Param : ParamAccesses) {
971 sort(C&: Param.Calls, Comp: [](const FunctionSummary::ParamAccess::Call &L,
972 const FunctionSummary::ParamAccess::Call &R) {
973 return std::tie(args: L.ParamNo, args: L.Callee) < std::tie(args: R.ParamNo, args: R.Callee);
974 });
975 }
976 return ParamAccesses;
977}
978
979StackSafetyGlobalInfo::StackSafetyGlobalInfo() = default;
980
981StackSafetyGlobalInfo::StackSafetyGlobalInfo(
982 Module *M, std::function<const StackSafetyInfo &(Function &F)> GetSSI,
983 const ModuleSummaryIndex *Index)
984 : M(M), GetSSI(GetSSI), Index(Index) {
985 if (StackSafetyRun)
986 getInfo();
987}
988
989StackSafetyGlobalInfo::StackSafetyGlobalInfo(StackSafetyGlobalInfo &&) =
990 default;
991
992StackSafetyGlobalInfo &
993StackSafetyGlobalInfo::operator=(StackSafetyGlobalInfo &&) = default;
994
995StackSafetyGlobalInfo::~StackSafetyGlobalInfo() = default;
996
997bool StackSafetyGlobalInfo::isSafe(const AllocaInst &AI) const {
998 const auto &Info = getInfo();
999 return Info.SafeAllocas.count(Ptr: &AI);
1000}
1001
1002bool StackSafetyGlobalInfo::stackAccessIsSafe(const Instruction &I) const {
1003 const auto &Info = getInfo();
1004 return Info.UnsafeAccesses.find(x: &I) == Info.UnsafeAccesses.end();
1005}
1006
1007void StackSafetyGlobalInfo::print(raw_ostream &O) const {
1008 auto &SSI = getInfo().Info;
1009 if (SSI.empty())
1010 return;
1011 const Module &M = *SSI.begin()->first->getParent();
1012 for (const auto &F : M.functions()) {
1013 if (!F.isDeclaration()) {
1014 SSI.find(x: &F)->second.print(O, Name: F.getName(), F: &F);
1015 O << " safe accesses:"
1016 << "\n";
1017 for (const auto &I : instructions(F)) {
1018 const CallInst *Call = dyn_cast<CallInst>(Val: &I);
1019 if ((isa<StoreInst>(Val: I) || isa<LoadInst>(Val: I) || isa<MemIntrinsic>(Val: I) ||
1020 isa<AtomicCmpXchgInst>(Val: I) || isa<AtomicRMWInst>(Val: I) ||
1021 (Call && Call->hasByValArgument())) &&
1022 stackAccessIsSafe(I)) {
1023 O << " " << I << "\n";
1024 }
1025 }
1026 O << "\n";
1027 }
1028 }
1029}
1030
1031LLVM_DUMP_METHOD void StackSafetyGlobalInfo::dump() const { print(O&: dbgs()); }
1032
1033AnalysisKey StackSafetyAnalysis::Key;
1034
1035StackSafetyInfo StackSafetyAnalysis::run(Function &F,
1036 FunctionAnalysisManager &AM) {
1037 return StackSafetyInfo(&F, [&AM, &F]() -> ScalarEvolution & {
1038 return AM.getResult<ScalarEvolutionAnalysis>(IR&: F);
1039 });
1040}
1041
1042PreservedAnalyses StackSafetyPrinterPass::run(Function &F,
1043 FunctionAnalysisManager &AM) {
1044 OS << "'Stack Safety Local Analysis' for function '" << F.getName() << "'\n";
1045 AM.getResult<StackSafetyAnalysis>(IR&: F).print(O&: OS);
1046 return PreservedAnalyses::all();
1047}
1048
1049char StackSafetyInfoWrapperPass::ID = 0;
1050
1051StackSafetyInfoWrapperPass::StackSafetyInfoWrapperPass() : FunctionPass(ID) {}
1052
1053void StackSafetyInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1054 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
1055 AU.setPreservesAll();
1056}
1057
1058void StackSafetyInfoWrapperPass::print(raw_ostream &O, const Module *M) const {
1059 SSI.print(O);
1060}
1061
1062bool StackSafetyInfoWrapperPass::runOnFunction(Function &F) {
1063 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1064 SSI = {&F, [SE]() -> ScalarEvolution & { return *SE; }};
1065 return false;
1066}
1067
1068AnalysisKey StackSafetyGlobalAnalysis::Key;
1069
1070StackSafetyGlobalInfo
1071StackSafetyGlobalAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
1072 FunctionAnalysisManager &FAM =
1073 AM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
1074 const ModuleSummaryIndex *Index = nullptr;
1075 if (auto *IndexPass =
1076 AM.getCachedResult<ImmutableModuleSummaryIndexAnalysis>(IR&: M))
1077 Index = IndexPass->getIndex();
1078 return {&M,
1079 [&FAM](Function &F) -> const StackSafetyInfo & {
1080 return FAM.getResult<StackSafetyAnalysis>(IR&: F);
1081 },
1082 Index};
1083}
1084
1085PreservedAnalyses StackSafetyGlobalPrinterPass::run(Module &M,
1086 ModuleAnalysisManager &AM) {
1087 OS << "'Stack Safety Analysis' for module '" << M.getName() << "'\n";
1088 AM.getResult<StackSafetyGlobalAnalysis>(IR&: M).print(O&: OS);
1089 return PreservedAnalyses::all();
1090}
1091
1092char StackSafetyGlobalInfoWrapperPass::ID = 0;
1093
1094StackSafetyGlobalInfoWrapperPass::StackSafetyGlobalInfoWrapperPass()
1095 : ModulePass(ID) {}
1096
1097StackSafetyGlobalInfoWrapperPass::~StackSafetyGlobalInfoWrapperPass() = default;
1098
1099void StackSafetyGlobalInfoWrapperPass::print(raw_ostream &O,
1100 const Module *M) const {
1101 SSGI.print(O);
1102}
1103
1104void StackSafetyGlobalInfoWrapperPass::getAnalysisUsage(
1105 AnalysisUsage &AU) const {
1106 AU.setPreservesAll();
1107 AU.addRequired<StackSafetyInfoWrapperPass>();
1108}
1109
1110bool StackSafetyGlobalInfoWrapperPass::runOnModule(Module &M) {
1111 const ModuleSummaryIndex *ImportSummary = nullptr;
1112 if (auto *IndexWrapperPass =
1113 getAnalysisIfAvailable<ImmutableModuleSummaryIndexWrapperPass>())
1114 ImportSummary = IndexWrapperPass->getIndex();
1115
1116 SSGI = {&M,
1117 [this](Function &F) -> const StackSafetyInfo & {
1118 return getAnalysis<StackSafetyInfoWrapperPass>(F).getResult();
1119 },
1120 ImportSummary};
1121 return false;
1122}
1123
1124bool llvm::needsParamAccessSummary(const Module &M) {
1125 if (StackSafetyRun)
1126 return true;
1127 for (const auto &F : M.functions())
1128 if (F.hasFnAttribute(Kind: Attribute::SanitizeMemTag))
1129 return true;
1130 return false;
1131}
1132
1133void llvm::generateParamAccessSummary(ModuleSummaryIndex &Index) {
1134 if (!Index.hasParamAccess())
1135 return;
1136 const ConstantRange FullSet(FunctionSummary::ParamAccess::RangeWidth, true);
1137
1138 auto CountParamAccesses = [&](auto &Stat) {
1139 if (!AreStatisticsEnabled())
1140 return;
1141 for (auto &GVS : Index)
1142 for (auto &GV : GVS.second.getSummaryList())
1143 if (FunctionSummary *FS = dyn_cast<FunctionSummary>(Val: GV.get()))
1144 Stat += FS->paramAccesses().size();
1145 };
1146
1147 CountParamAccesses(NumCombinedParamAccessesBefore);
1148
1149 std::map<const FunctionSummary *, FunctionInfo<FunctionSummary>> Functions;
1150
1151 // Convert the ModuleSummaryIndex to a FunctionMap
1152 for (auto &GVS : Index) {
1153 for (auto &GV : GVS.second.getSummaryList()) {
1154 FunctionSummary *FS = dyn_cast<FunctionSummary>(Val: GV.get());
1155 if (!FS || FS->paramAccesses().empty())
1156 continue;
1157 if (FS->isLive() && FS->isDSOLocal()) {
1158 FunctionInfo<FunctionSummary> FI;
1159 for (const auto &PS : FS->paramAccesses()) {
1160 auto &US =
1161 FI.Params
1162 .emplace(args: PS.ParamNo, args: FunctionSummary::ParamAccess::RangeWidth)
1163 .first->second;
1164 US.Range = PS.Use;
1165 for (const auto &Call : PS.Calls) {
1166 assert(!Call.Offsets.isFullSet());
1167 FunctionSummary *S =
1168 findCalleeFunctionSummary(VI: Call.Callee, ModuleId: FS->modulePath());
1169 ++NumCombinedCalleeLookupTotal;
1170 if (!S) {
1171 ++NumCombinedCalleeLookupFailed;
1172 US.Range = FullSet;
1173 US.Calls.clear();
1174 break;
1175 }
1176 US.Calls.emplace(args: CallInfo<FunctionSummary>(S, Call.ParamNo),
1177 args: Call.Offsets);
1178 }
1179 }
1180 Functions.emplace(args&: FS, args: std::move(FI));
1181 }
1182 // Reset data for all summaries. Alive and DSO local will be set back from
1183 // of data flow results below. Anything else will not be accessed
1184 // by ThinLTO backend, so we can save on bitcode size.
1185 FS->setParamAccesses({});
1186 }
1187 }
1188 NumCombinedDataFlowNodes += Functions.size();
1189 StackSafetyDataFlowAnalysis<FunctionSummary> SSDFA(
1190 FunctionSummary::ParamAccess::RangeWidth, std::move(Functions));
1191 for (const auto &KV : SSDFA.run()) {
1192 std::vector<FunctionSummary::ParamAccess> NewParams;
1193 NewParams.reserve(n: KV.second.Params.size());
1194 for (const auto &Param : KV.second.Params) {
1195 // It's not needed as FullSet is processed the same as a missing value.
1196 if (Param.second.Range.isFullSet())
1197 continue;
1198 NewParams.emplace_back();
1199 FunctionSummary::ParamAccess &New = NewParams.back();
1200 New.ParamNo = Param.first;
1201 New.Use = Param.second.Range; // Only range is needed.
1202 }
1203 const_cast<FunctionSummary *>(KV.first)->setParamAccesses(
1204 std::move(NewParams));
1205 }
1206
1207 CountParamAccesses(NumCombinedParamAccessesAfter);
1208}
1209
1210static const char LocalPassArg[] = "stack-safety-local";
1211static const char LocalPassName[] = "Stack Safety Local Analysis";
1212INITIALIZE_PASS_BEGIN(StackSafetyInfoWrapperPass, LocalPassArg, LocalPassName,
1213 false, true)
1214INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1215INITIALIZE_PASS_END(StackSafetyInfoWrapperPass, LocalPassArg, LocalPassName,
1216 false, true)
1217
1218static const char GlobalPassName[] = "Stack Safety Analysis";
1219INITIALIZE_PASS_BEGIN(StackSafetyGlobalInfoWrapperPass, DEBUG_TYPE,
1220 GlobalPassName, false, true)
1221INITIALIZE_PASS_DEPENDENCY(StackSafetyInfoWrapperPass)
1222INITIALIZE_PASS_DEPENDENCY(ImmutableModuleSummaryIndexWrapperPass)
1223INITIALIZE_PASS_END(StackSafetyGlobalInfoWrapperPass, DEBUG_TYPE,
1224 GlobalPassName, false, true)
1225