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