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/Analysis/ScalarEvolutionExpressions.h"
13 #include "llvm/IR/CallSite.h"
14 #include "llvm/IR/InstIterator.h"
15 #include "llvm/IR/IntrinsicInst.h"
16 #include "llvm/InitializePasses.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/raw_ostream.h"
19
20 using namespace llvm;
21
22 #define DEBUG_TYPE "stack-safety"
23
24 static cl::opt<int> StackSafetyMaxIterations("stack-safety-max-iterations",
25 cl::init(20), cl::Hidden);
26
27 namespace {
28
29 /// Rewrite an SCEV expression for a memory access address to an expression that
30 /// represents offset from the given alloca.
31 class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
32 const Value *AllocaPtr;
33
34 public:
AllocaOffsetRewriter(ScalarEvolution & SE,const Value * AllocaPtr)35 AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
36 : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
37
visit(const SCEV * Expr)38 const SCEV *visit(const SCEV *Expr) {
39 // Only re-write the expression if the alloca is used in an addition
40 // expression (it can be used in other types of expressions if it's cast to
41 // an int and passed as an argument.)
42 if (!isa<SCEVAddRecExpr>(Expr) && !isa<SCEVAddExpr>(Expr) &&
43 !isa<SCEVUnknown>(Expr))
44 return Expr;
45 return SCEVRewriteVisitor<AllocaOffsetRewriter>::visit(Expr);
46 }
47
visitUnknown(const SCEVUnknown * Expr)48 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
49 // FIXME: look through one or several levels of definitions?
50 // This can be inttoptr(AllocaPtr) and SCEV would not unwrap
51 // it for us.
52 if (Expr->getValue() == AllocaPtr)
53 return SE.getZero(Expr->getType());
54 return Expr;
55 }
56 };
57
58 /// Describes use of address in as a function call argument.
59 struct PassAsArgInfo {
60 /// Function being called.
61 const GlobalValue *Callee = nullptr;
62 /// Index of argument which pass address.
63 size_t ParamNo = 0;
64 // Offset range of address from base address (alloca or calling function
65 // argument).
66 // Range should never set to empty-set, that is an invalid access range
67 // that can cause empty-set to be propagated with ConstantRange::add
68 ConstantRange Offset;
PassAsArgInfo__anon2ef982e30111::PassAsArgInfo69 PassAsArgInfo(const GlobalValue *Callee, size_t ParamNo, ConstantRange Offset)
70 : Callee(Callee), ParamNo(ParamNo), Offset(Offset) {}
71
getName__anon2ef982e30111::PassAsArgInfo72 StringRef getName() const { return Callee->getName(); }
73 };
74
operator <<(raw_ostream & OS,const PassAsArgInfo & P)75 raw_ostream &operator<<(raw_ostream &OS, const PassAsArgInfo &P) {
76 return OS << "@" << P.getName() << "(arg" << P.ParamNo << ", " << P.Offset
77 << ")";
78 }
79
80 /// Describe uses of address (alloca or parameter) inside of the function.
81 struct UseInfo {
82 // Access range if the address (alloca or parameters).
83 // It is allowed to be empty-set when there are no known accesses.
84 ConstantRange Range;
85
86 // List of calls which pass address as an argument.
87 SmallVector<PassAsArgInfo, 4> Calls;
88
UseInfo__anon2ef982e30111::UseInfo89 explicit UseInfo(unsigned PointerSize) : Range{PointerSize, false} {}
90
updateRange__anon2ef982e30111::UseInfo91 void updateRange(ConstantRange R) { Range = Range.unionWith(R); }
92 };
93
operator <<(raw_ostream & OS,const UseInfo & U)94 raw_ostream &operator<<(raw_ostream &OS, const UseInfo &U) {
95 OS << U.Range;
96 for (auto &Call : U.Calls)
97 OS << ", " << Call;
98 return OS;
99 }
100
101 struct AllocaInfo {
102 const AllocaInst *AI = nullptr;
103 uint64_t Size = 0;
104 UseInfo Use;
105
AllocaInfo__anon2ef982e30111::AllocaInfo106 AllocaInfo(unsigned PointerSize, const AllocaInst *AI, uint64_t Size)
107 : AI(AI), Size(Size), Use(PointerSize) {}
108
getName__anon2ef982e30111::AllocaInfo109 StringRef getName() const { return AI->getName(); }
110 };
111
operator <<(raw_ostream & OS,const AllocaInfo & A)112 raw_ostream &operator<<(raw_ostream &OS, const AllocaInfo &A) {
113 return OS << A.getName() << "[" << A.Size << "]: " << A.Use;
114 }
115
116 struct ParamInfo {
117 const Argument *Arg = nullptr;
118 UseInfo Use;
119
ParamInfo__anon2ef982e30111::ParamInfo120 explicit ParamInfo(unsigned PointerSize, const Argument *Arg)
121 : Arg(Arg), Use(PointerSize) {}
122
getName__anon2ef982e30111::ParamInfo123 StringRef getName() const { return Arg ? Arg->getName() : "<N/A>"; }
124 };
125
operator <<(raw_ostream & OS,const ParamInfo & P)126 raw_ostream &operator<<(raw_ostream &OS, const ParamInfo &P) {
127 return OS << P.getName() << "[]: " << P.Use;
128 }
129
130 /// Calculate the allocation size of a given alloca. Returns 0 if the
131 /// size can not be statically determined.
getStaticAllocaAllocationSize(const AllocaInst * AI)132 uint64_t getStaticAllocaAllocationSize(const AllocaInst *AI) {
133 const DataLayout &DL = AI->getModule()->getDataLayout();
134 uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType());
135 if (AI->isArrayAllocation()) {
136 auto C = dyn_cast<ConstantInt>(AI->getArraySize());
137 if (!C)
138 return 0;
139 Size *= C->getZExtValue();
140 }
141 return Size;
142 }
143
144 } // end anonymous namespace
145
146 /// Describes uses of allocas and parameters inside of a single function.
147 struct StackSafetyInfo::FunctionInfo {
148 // May be a Function or a GlobalAlias
149 const GlobalValue *GV = nullptr;
150 // Informations about allocas uses.
151 SmallVector<AllocaInfo, 4> Allocas;
152 // Informations about parameters uses.
153 SmallVector<ParamInfo, 4> Params;
154 // TODO: describe return value as depending on one or more of its arguments.
155
156 // StackSafetyDataFlowAnalysis counter stored here for faster access.
157 int UpdateCount = 0;
158
FunctionInfoStackSafetyInfo::FunctionInfo159 FunctionInfo(const StackSafetyInfo &SSI) : FunctionInfo(*SSI.Info) {}
160
FunctionInfoStackSafetyInfo::FunctionInfo161 explicit FunctionInfo(const Function *F) : GV(F){};
162 // Creates FunctionInfo that forwards all the parameters to the aliasee.
163 explicit FunctionInfo(const GlobalAlias *A);
164
165 FunctionInfo(FunctionInfo &&) = default;
166
IsDSOLocalStackSafetyInfo::FunctionInfo167 bool IsDSOLocal() const { return GV->isDSOLocal(); };
168
IsInterposableStackSafetyInfo::FunctionInfo169 bool IsInterposable() const { return GV->isInterposable(); };
170
getNameStackSafetyInfo::FunctionInfo171 StringRef getName() const { return GV->getName(); }
172
printStackSafetyInfo::FunctionInfo173 void print(raw_ostream &O) const {
174 // TODO: Consider different printout format after
175 // StackSafetyDataFlowAnalysis. Calls and parameters are irrelevant then.
176 O << " @" << getName() << (IsDSOLocal() ? "" : " dso_preemptable")
177 << (IsInterposable() ? " interposable" : "") << "\n";
178 O << " args uses:\n";
179 for (auto &P : Params)
180 O << " " << P << "\n";
181 O << " allocas uses:\n";
182 for (auto &AS : Allocas)
183 O << " " << AS << "\n";
184 }
185
186 private:
187 FunctionInfo(const FunctionInfo &) = default;
188 };
189
FunctionInfo(const GlobalAlias * A)190 StackSafetyInfo::FunctionInfo::FunctionInfo(const GlobalAlias *A) : GV(A) {
191 unsigned PointerSize = A->getParent()->getDataLayout().getPointerSizeInBits();
192 const GlobalObject *Aliasee = A->getBaseObject();
193 const FunctionType *Type = cast<FunctionType>(Aliasee->getValueType());
194 // 'Forward' all parameters to this alias to the aliasee
195 for (unsigned ArgNo = 0; ArgNo < Type->getNumParams(); ArgNo++) {
196 Params.emplace_back(PointerSize, nullptr);
197 UseInfo &US = Params.back().Use;
198 US.Calls.emplace_back(Aliasee, ArgNo, ConstantRange(APInt(PointerSize, 0)));
199 }
200 }
201
202 namespace {
203
204 class StackSafetyLocalAnalysis {
205 const Function &F;
206 const DataLayout &DL;
207 ScalarEvolution &SE;
208 unsigned PointerSize = 0;
209
210 const ConstantRange UnknownRange;
211
212 ConstantRange offsetFromAlloca(Value *Addr, const Value *AllocaPtr);
213 ConstantRange getAccessRange(Value *Addr, const Value *AllocaPtr,
214 uint64_t AccessSize);
215 ConstantRange getMemIntrinsicAccessRange(const MemIntrinsic *MI, const Use &U,
216 const Value *AllocaPtr);
217
218 bool analyzeAllUses(const Value *Ptr, UseInfo &AS);
219
getRange(uint64_t Lower,uint64_t Upper) const220 ConstantRange getRange(uint64_t Lower, uint64_t Upper) const {
221 return ConstantRange(APInt(PointerSize, Lower), APInt(PointerSize, Upper));
222 }
223
224 public:
StackSafetyLocalAnalysis(const Function & F,ScalarEvolution & SE)225 StackSafetyLocalAnalysis(const Function &F, ScalarEvolution &SE)
226 : F(F), DL(F.getParent()->getDataLayout()), SE(SE),
227 PointerSize(DL.getPointerSizeInBits()),
228 UnknownRange(PointerSize, true) {}
229
230 // Run the transformation on the associated function.
231 StackSafetyInfo run();
232 };
233
234 ConstantRange
offsetFromAlloca(Value * Addr,const Value * AllocaPtr)235 StackSafetyLocalAnalysis::offsetFromAlloca(Value *Addr,
236 const Value *AllocaPtr) {
237 if (!SE.isSCEVable(Addr->getType()))
238 return UnknownRange;
239
240 AllocaOffsetRewriter Rewriter(SE, AllocaPtr);
241 const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
242 ConstantRange Offset = SE.getUnsignedRange(Expr).zextOrTrunc(PointerSize);
243 assert(!Offset.isEmptySet());
244 return Offset;
245 }
246
getAccessRange(Value * Addr,const Value * AllocaPtr,uint64_t AccessSize)247 ConstantRange StackSafetyLocalAnalysis::getAccessRange(Value *Addr,
248 const Value *AllocaPtr,
249 uint64_t AccessSize) {
250 if (!SE.isSCEVable(Addr->getType()))
251 return UnknownRange;
252
253 AllocaOffsetRewriter Rewriter(SE, AllocaPtr);
254 const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
255
256 ConstantRange AccessStartRange =
257 SE.getUnsignedRange(Expr).zextOrTrunc(PointerSize);
258 ConstantRange SizeRange = getRange(0, AccessSize);
259 ConstantRange AccessRange = AccessStartRange.add(SizeRange);
260 assert(!AccessRange.isEmptySet());
261 return AccessRange;
262 }
263
getMemIntrinsicAccessRange(const MemIntrinsic * MI,const Use & U,const Value * AllocaPtr)264 ConstantRange StackSafetyLocalAnalysis::getMemIntrinsicAccessRange(
265 const MemIntrinsic *MI, const Use &U, const Value *AllocaPtr) {
266 if (auto MTI = dyn_cast<MemTransferInst>(MI)) {
267 if (MTI->getRawSource() != U && MTI->getRawDest() != U)
268 return getRange(0, 1);
269 } else {
270 if (MI->getRawDest() != U)
271 return getRange(0, 1);
272 }
273 const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
274 // Non-constant size => unsafe. FIXME: try SCEV getRange.
275 if (!Len)
276 return UnknownRange;
277 ConstantRange AccessRange = getAccessRange(U, AllocaPtr, Len->getZExtValue());
278 return AccessRange;
279 }
280
281 /// The function analyzes all local uses of Ptr (alloca or argument) and
282 /// calculates local access range and all function calls where it was used.
analyzeAllUses(const Value * Ptr,UseInfo & US)283 bool StackSafetyLocalAnalysis::analyzeAllUses(const Value *Ptr, UseInfo &US) {
284 SmallPtrSet<const Value *, 16> Visited;
285 SmallVector<const Value *, 8> WorkList;
286 WorkList.push_back(Ptr);
287
288 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
289 while (!WorkList.empty()) {
290 const Value *V = WorkList.pop_back_val();
291 for (const Use &UI : V->uses()) {
292 auto I = cast<const Instruction>(UI.getUser());
293 assert(V == UI.get());
294
295 switch (I->getOpcode()) {
296 case Instruction::Load: {
297 US.updateRange(
298 getAccessRange(UI, Ptr, DL.getTypeStoreSize(I->getType())));
299 break;
300 }
301
302 case Instruction::VAArg:
303 // "va-arg" from a pointer is safe.
304 break;
305 case Instruction::Store: {
306 if (V == I->getOperand(0)) {
307 // Stored the pointer - conservatively assume it may be unsafe.
308 US.updateRange(UnknownRange);
309 return false;
310 }
311 US.updateRange(getAccessRange(
312 UI, Ptr, DL.getTypeStoreSize(I->getOperand(0)->getType())));
313 break;
314 }
315
316 case Instruction::Ret:
317 // Information leak.
318 // FIXME: Process parameters correctly. This is a leak only if we return
319 // alloca.
320 US.updateRange(UnknownRange);
321 return false;
322
323 case Instruction::Call:
324 case Instruction::Invoke: {
325 ImmutableCallSite CS(I);
326
327 if (I->isLifetimeStartOrEnd())
328 break;
329
330 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
331 US.updateRange(getMemIntrinsicAccessRange(MI, UI, Ptr));
332 break;
333 }
334
335 // FIXME: consult devirt?
336 // Do not follow aliases, otherwise we could inadvertently follow
337 // dso_preemptable aliases or aliases with interposable linkage.
338 const GlobalValue *Callee =
339 dyn_cast<GlobalValue>(CS.getCalledValue()->stripPointerCasts());
340 if (!Callee) {
341 US.updateRange(UnknownRange);
342 return false;
343 }
344
345 assert(isa<Function>(Callee) || isa<GlobalAlias>(Callee));
346
347 ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
348 for (ImmutableCallSite::arg_iterator A = B; A != E; ++A) {
349 if (A->get() == V) {
350 ConstantRange Offset = offsetFromAlloca(UI, Ptr);
351 US.Calls.emplace_back(Callee, A - B, Offset);
352 }
353 }
354
355 break;
356 }
357
358 default:
359 if (Visited.insert(I).second)
360 WorkList.push_back(cast<const Instruction>(I));
361 }
362 }
363 }
364
365 return true;
366 }
367
run()368 StackSafetyInfo StackSafetyLocalAnalysis::run() {
369 StackSafetyInfo::FunctionInfo Info(&F);
370 assert(!F.isDeclaration() &&
371 "Can't run StackSafety on a function declaration");
372
373 LLVM_DEBUG(dbgs() << "[StackSafety] " << F.getName() << "\n");
374
375 for (auto &I : instructions(F)) {
376 if (auto AI = dyn_cast<AllocaInst>(&I)) {
377 Info.Allocas.emplace_back(PointerSize, AI,
378 getStaticAllocaAllocationSize(AI));
379 AllocaInfo &AS = Info.Allocas.back();
380 analyzeAllUses(AI, AS.Use);
381 }
382 }
383
384 for (const Argument &A : make_range(F.arg_begin(), F.arg_end())) {
385 Info.Params.emplace_back(PointerSize, &A);
386 ParamInfo &PS = Info.Params.back();
387 analyzeAllUses(&A, PS.Use);
388 }
389
390 LLVM_DEBUG(dbgs() << "[StackSafety] done\n");
391 LLVM_DEBUG(Info.print(dbgs()));
392 return StackSafetyInfo(std::move(Info));
393 }
394
395 class StackSafetyDataFlowAnalysis {
396 using FunctionMap =
397 std::map<const GlobalValue *, StackSafetyInfo::FunctionInfo>;
398
399 FunctionMap Functions;
400 // Callee-to-Caller multimap.
401 DenseMap<const GlobalValue *, SmallVector<const GlobalValue *, 4>> Callers;
402 SetVector<const GlobalValue *> WorkList;
403
404 unsigned PointerSize = 0;
405 const ConstantRange UnknownRange;
406
407 ConstantRange getArgumentAccessRange(const GlobalValue *Callee,
408 unsigned ParamNo) const;
409 bool updateOneUse(UseInfo &US, bool UpdateToFullSet);
410 void updateOneNode(const GlobalValue *Callee,
411 StackSafetyInfo::FunctionInfo &FS);
updateOneNode(const GlobalValue * Callee)412 void updateOneNode(const GlobalValue *Callee) {
413 updateOneNode(Callee, Functions.find(Callee)->second);
414 }
updateAllNodes()415 void updateAllNodes() {
416 for (auto &F : Functions)
417 updateOneNode(F.first, F.second);
418 }
419 void runDataFlow();
420 #ifndef NDEBUG
421 void verifyFixedPoint();
422 #endif
423
424 public:
425 StackSafetyDataFlowAnalysis(
426 Module &M, std::function<const StackSafetyInfo &(Function &)> FI);
427 StackSafetyGlobalInfo run();
428 };
429
StackSafetyDataFlowAnalysis(Module & M,std::function<const StackSafetyInfo & (Function &)> FI)430 StackSafetyDataFlowAnalysis::StackSafetyDataFlowAnalysis(
431 Module &M, std::function<const StackSafetyInfo &(Function &)> FI)
432 : PointerSize(M.getDataLayout().getPointerSizeInBits()),
433 UnknownRange(PointerSize, true) {
434 // Without ThinLTO, run the local analysis for every function in the TU and
435 // then run the DFA.
436 for (auto &F : M.functions())
437 if (!F.isDeclaration())
438 Functions.emplace(&F, FI(F));
439 for (auto &A : M.aliases())
440 if (isa<Function>(A.getBaseObject()))
441 Functions.emplace(&A, StackSafetyInfo::FunctionInfo(&A));
442 }
443
444 ConstantRange
getArgumentAccessRange(const GlobalValue * Callee,unsigned ParamNo) const445 StackSafetyDataFlowAnalysis::getArgumentAccessRange(const GlobalValue *Callee,
446 unsigned ParamNo) const {
447 auto IT = Functions.find(Callee);
448 // Unknown callee (outside of LTO domain or an indirect call).
449 if (IT == Functions.end())
450 return UnknownRange;
451 const StackSafetyInfo::FunctionInfo &FS = IT->second;
452 // The definition of this symbol may not be the definition in this linkage
453 // unit.
454 if (!FS.IsDSOLocal() || FS.IsInterposable())
455 return UnknownRange;
456 if (ParamNo >= FS.Params.size()) // possibly vararg
457 return UnknownRange;
458 return FS.Params[ParamNo].Use.Range;
459 }
460
updateOneUse(UseInfo & US,bool UpdateToFullSet)461 bool StackSafetyDataFlowAnalysis::updateOneUse(UseInfo &US,
462 bool UpdateToFullSet) {
463 bool Changed = false;
464 for (auto &CS : US.Calls) {
465 assert(!CS.Offset.isEmptySet() &&
466 "Param range can't be empty-set, invalid offset range");
467
468 ConstantRange CalleeRange = getArgumentAccessRange(CS.Callee, CS.ParamNo);
469 CalleeRange = CalleeRange.add(CS.Offset);
470 if (!US.Range.contains(CalleeRange)) {
471 Changed = true;
472 if (UpdateToFullSet)
473 US.Range = UnknownRange;
474 else
475 US.Range = US.Range.unionWith(CalleeRange);
476 }
477 }
478 return Changed;
479 }
480
updateOneNode(const GlobalValue * Callee,StackSafetyInfo::FunctionInfo & FS)481 void StackSafetyDataFlowAnalysis::updateOneNode(
482 const GlobalValue *Callee, StackSafetyInfo::FunctionInfo &FS) {
483 bool UpdateToFullSet = FS.UpdateCount > StackSafetyMaxIterations;
484 bool Changed = false;
485 for (auto &AS : FS.Allocas)
486 Changed |= updateOneUse(AS.Use, UpdateToFullSet);
487 for (auto &PS : FS.Params)
488 Changed |= updateOneUse(PS.Use, UpdateToFullSet);
489
490 if (Changed) {
491 LLVM_DEBUG(dbgs() << "=== update [" << FS.UpdateCount
492 << (UpdateToFullSet ? ", full-set" : "") << "] "
493 << FS.getName() << "\n");
494 // Callers of this function may need updating.
495 for (auto &CallerID : Callers[Callee])
496 WorkList.insert(CallerID);
497
498 ++FS.UpdateCount;
499 }
500 }
501
runDataFlow()502 void StackSafetyDataFlowAnalysis::runDataFlow() {
503 Callers.clear();
504 WorkList.clear();
505
506 SmallVector<const GlobalValue *, 16> Callees;
507 for (auto &F : Functions) {
508 Callees.clear();
509 StackSafetyInfo::FunctionInfo &FS = F.second;
510 for (auto &AS : FS.Allocas)
511 for (auto &CS : AS.Use.Calls)
512 Callees.push_back(CS.Callee);
513 for (auto &PS : FS.Params)
514 for (auto &CS : PS.Use.Calls)
515 Callees.push_back(CS.Callee);
516
517 llvm::sort(Callees);
518 Callees.erase(std::unique(Callees.begin(), Callees.end()), Callees.end());
519
520 for (auto &Callee : Callees)
521 Callers[Callee].push_back(F.first);
522 }
523
524 updateAllNodes();
525
526 while (!WorkList.empty()) {
527 const GlobalValue *Callee = WorkList.back();
528 WorkList.pop_back();
529 updateOneNode(Callee);
530 }
531 }
532
533 #ifndef NDEBUG
verifyFixedPoint()534 void StackSafetyDataFlowAnalysis::verifyFixedPoint() {
535 WorkList.clear();
536 updateAllNodes();
537 assert(WorkList.empty());
538 }
539 #endif
540
run()541 StackSafetyGlobalInfo StackSafetyDataFlowAnalysis::run() {
542 runDataFlow();
543 LLVM_DEBUG(verifyFixedPoint());
544
545 StackSafetyGlobalInfo SSI;
546 for (auto &F : Functions)
547 SSI.emplace(F.first, std::move(F.second));
548 return SSI;
549 }
550
print(const StackSafetyGlobalInfo & SSI,raw_ostream & O,const Module & M)551 void print(const StackSafetyGlobalInfo &SSI, raw_ostream &O, const Module &M) {
552 size_t Count = 0;
553 for (auto &F : M.functions())
554 if (!F.isDeclaration()) {
555 SSI.find(&F)->second.print(O);
556 O << "\n";
557 ++Count;
558 }
559 for (auto &A : M.aliases()) {
560 SSI.find(&A)->second.print(O);
561 O << "\n";
562 ++Count;
563 }
564 assert(Count == SSI.size() && "Unexpected functions in the result");
565 }
566
567 } // end anonymous namespace
568
569 StackSafetyInfo::StackSafetyInfo() = default;
570 StackSafetyInfo::StackSafetyInfo(StackSafetyInfo &&) = default;
571 StackSafetyInfo &StackSafetyInfo::operator=(StackSafetyInfo &&) = default;
572
StackSafetyInfo(FunctionInfo && Info)573 StackSafetyInfo::StackSafetyInfo(FunctionInfo &&Info)
574 : Info(new FunctionInfo(std::move(Info))) {}
575
576 StackSafetyInfo::~StackSafetyInfo() = default;
577
print(raw_ostream & O) const578 void StackSafetyInfo::print(raw_ostream &O) const { Info->print(O); }
579
580 AnalysisKey StackSafetyAnalysis::Key;
581
run(Function & F,FunctionAnalysisManager & AM)582 StackSafetyInfo StackSafetyAnalysis::run(Function &F,
583 FunctionAnalysisManager &AM) {
584 StackSafetyLocalAnalysis SSLA(F, AM.getResult<ScalarEvolutionAnalysis>(F));
585 return SSLA.run();
586 }
587
run(Function & F,FunctionAnalysisManager & AM)588 PreservedAnalyses StackSafetyPrinterPass::run(Function &F,
589 FunctionAnalysisManager &AM) {
590 OS << "'Stack Safety Local Analysis' for function '" << F.getName() << "'\n";
591 AM.getResult<StackSafetyAnalysis>(F).print(OS);
592 return PreservedAnalyses::all();
593 }
594
595 char StackSafetyInfoWrapperPass::ID = 0;
596
StackSafetyInfoWrapperPass()597 StackSafetyInfoWrapperPass::StackSafetyInfoWrapperPass() : FunctionPass(ID) {
598 initializeStackSafetyInfoWrapperPassPass(*PassRegistry::getPassRegistry());
599 }
600
getAnalysisUsage(AnalysisUsage & AU) const601 void StackSafetyInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
602 AU.addRequired<ScalarEvolutionWrapperPass>();
603 AU.setPreservesAll();
604 }
605
print(raw_ostream & O,const Module * M) const606 void StackSafetyInfoWrapperPass::print(raw_ostream &O, const Module *M) const {
607 SSI.print(O);
608 }
609
runOnFunction(Function & F)610 bool StackSafetyInfoWrapperPass::runOnFunction(Function &F) {
611 StackSafetyLocalAnalysis SSLA(
612 F, getAnalysis<ScalarEvolutionWrapperPass>().getSE());
613 SSI = StackSafetyInfo(SSLA.run());
614 return false;
615 }
616
617 AnalysisKey StackSafetyGlobalAnalysis::Key;
618
619 StackSafetyGlobalInfo
run(Module & M,ModuleAnalysisManager & AM)620 StackSafetyGlobalAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
621 FunctionAnalysisManager &FAM =
622 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
623
624 StackSafetyDataFlowAnalysis SSDFA(
625 M, [&FAM](Function &F) -> const StackSafetyInfo & {
626 return FAM.getResult<StackSafetyAnalysis>(F);
627 });
628 return SSDFA.run();
629 }
630
run(Module & M,ModuleAnalysisManager & AM)631 PreservedAnalyses StackSafetyGlobalPrinterPass::run(Module &M,
632 ModuleAnalysisManager &AM) {
633 OS << "'Stack Safety Analysis' for module '" << M.getName() << "'\n";
634 print(AM.getResult<StackSafetyGlobalAnalysis>(M), OS, M);
635 return PreservedAnalyses::all();
636 }
637
638 char StackSafetyGlobalInfoWrapperPass::ID = 0;
639
StackSafetyGlobalInfoWrapperPass()640 StackSafetyGlobalInfoWrapperPass::StackSafetyGlobalInfoWrapperPass()
641 : ModulePass(ID) {
642 initializeStackSafetyGlobalInfoWrapperPassPass(
643 *PassRegistry::getPassRegistry());
644 }
645
print(raw_ostream & O,const Module * M) const646 void StackSafetyGlobalInfoWrapperPass::print(raw_ostream &O,
647 const Module *M) const {
648 ::print(SSI, O, *M);
649 }
650
getAnalysisUsage(AnalysisUsage & AU) const651 void StackSafetyGlobalInfoWrapperPass::getAnalysisUsage(
652 AnalysisUsage &AU) const {
653 AU.addRequired<StackSafetyInfoWrapperPass>();
654 }
655
runOnModule(Module & M)656 bool StackSafetyGlobalInfoWrapperPass::runOnModule(Module &M) {
657 StackSafetyDataFlowAnalysis SSDFA(
658 M, [this](Function &F) -> const StackSafetyInfo & {
659 return getAnalysis<StackSafetyInfoWrapperPass>(F).getResult();
660 });
661 SSI = SSDFA.run();
662 return false;
663 }
664
665 static const char LocalPassArg[] = "stack-safety-local";
666 static const char LocalPassName[] = "Stack Safety Local Analysis";
667 INITIALIZE_PASS_BEGIN(StackSafetyInfoWrapperPass, LocalPassArg, LocalPassName,
668 false, true)
669 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
670 INITIALIZE_PASS_END(StackSafetyInfoWrapperPass, LocalPassArg, LocalPassName,
671 false, true)
672
673 static const char GlobalPassName[] = "Stack Safety Analysis";
674 INITIALIZE_PASS_BEGIN(StackSafetyGlobalInfoWrapperPass, DEBUG_TYPE,
675 GlobalPassName, false, false)
676 INITIALIZE_PASS_DEPENDENCY(StackSafetyInfoWrapperPass)
677 INITIALIZE_PASS_END(StackSafetyGlobalInfoWrapperPass, DEBUG_TYPE,
678 GlobalPassName, false, false)
679