LLVM 24.0.0git
StackSafetyAnalysis.cpp
Go to the documentation of this file.
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
12#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/Statistic.h"
21#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/Instruction.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(20), cl::Hidden);
63
64static cl::opt<bool> StackSafetyPrint("stack-safety-print", cl::init(false),
66
67static cl::opt<bool> StackSafetyRun("stack-safety-run", cl::init(false),
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(R) !=
82 return ConstantRange::getFull(L.getBitWidth());
83 ConstantRange Result = L.add(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(R);
92 // Two non-wrapped sets can produce wrapped.
93 if (Result.isSignWrappedSet())
94 Result = ConstantRange::getFull(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(Range, R); }
134 void addRange(const Instruction *I, const ConstantRange &R, bool IsSafe) {
135 if (!IsSafe)
136 UnsafeAccesses.insert(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();
156 unsigned PointerSize = DL.getPointerTypeSizeInBits(AI.getType());
157 // Fallback to empty range for alloca size.
158 ConstantRange R = ConstantRange::getEmpty(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>(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(PointerSize);
173 APSize = APSize.smul_ov(Mul, Overflow);
174 if (Overflow)
175 return R;
176 }
177 R = ConstantRange(APInt::getZero(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(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>(&I)) {
210 auto &AS = Allocas.find(AI)->second;
211 O << " " << AI->getName() << "["
212 << getStaticAllocaSizeRange(*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
226 FunctionInfo<GlobalValue> Info;
227};
228
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(SE.getContext());
284 return SE.getTruncateOrZeroExtend(SE.getSCEV(Val), PtrTy);
285 }
286
287 if (ValTy->getPointerAddressSpace() != 0)
288 return nullptr;
289 return SE.getSCEV(Val);
290}
291
292ConstantRange StackSafetyLocalAnalysis::offsetFrom(Value *Addr, Value *Base) {
293 if (!SE.isSCEVable(Addr->getType()) || !SE.isSCEVable(Base->getType()))
294 return UnknownRange;
295
296 const SCEV *AddrExp = getSCEVAsPointer(Addr);
297 const SCEV *BaseExp = getSCEVAsPointer(Base);
298 if (!AddrExp || !BaseExp)
299 return UnknownRange;
300
301 const SCEV *Diff = SE.getMinusSCEV(AddrExp, BaseExp);
302 if (isa<SCEVCouldNotCompute>(Diff))
303 return UnknownRange;
304
305 ConstantRange Offset = SE.getSignedRange(Diff);
306 if (isUnsafe(Offset))
307 return UnknownRange;
308 return Offset.sextOrTrunc(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(PointerSize);
317 assert(!isUnsafe(SizeRange));
318
319 ConstantRange Offsets = offsetFrom(Addr, Base);
320 if (isUnsafe(Offsets))
321 return UnknownRange;
322
323 Offsets = addOverflowNever(Offsets, SizeRange);
324 if (isUnsafe(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 ConstantRange(APInt::getZero(PointerSize), APSize));
338}
339
340ConstantRange StackSafetyLocalAnalysis::getMemIntrinsicAccessRange(
341 const MemIntrinsic *MI, const Use &U, Value *Base) {
342 if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
343 if (MTI->getRawSource() != U && MTI->getRawDest() != U)
344 return ConstantRange::getEmpty(PointerSize);
345 } else {
346 if (MI->getRawDest() != U)
347 return ConstantRange::getEmpty(PointerSize);
348 }
349
350 auto *CalculationTy = IntegerType::getIntNTy(SE.getContext(), PointerSize);
351 if (!SE.isSCEVable(MI->getLength()->getType()))
352 return UnknownRange;
353
354 const SCEV *Expr =
355 SE.getTruncateOrZeroExtend(SE.getSCEV(MI->getLength()), CalculationTy);
356 ConstantRange Sizes = SE.getSignedRange(Expr);
357 if (!Sizes.getUpper().isStrictlyPositive() || isUnsafe(Sizes))
358 return UnknownRange;
359 Sizes = Sizes.sextOrTrunc(PointerSize);
360 ConstantRange SizeRange(APInt::getZero(PointerSize), Sizes.getUpper() - 1);
361 return getAccessRange(U, Base, SizeRange);
362}
363
364bool StackSafetyLocalAnalysis::isSafeAccess(const Use &U, AllocaInst *AI,
365 Value *V) {
366 return isSafeAccess(U, AI, 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(SE.getContext(), PointerSize);
374 const SCEV *SV = SE.getConstant(CalculationTy, TS.getFixedValue());
375 return isSafeAccess(U, AI, 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>(AccessSize))
384 return false;
385
386 const auto *I = cast<Instruction>(U.getUser());
387
388 const SCEV *AddrExp = getSCEVAsPointer(U.get());
389 const SCEV *BaseExp = getSCEVAsPointer(AI);
390 if (!AddrExp || !BaseExp)
391 return false;
392
393 const SCEV *Diff = SE.getMinusSCEV(AddrExp, BaseExp);
394 if (isa<SCEVCouldNotCompute>(Diff))
395 return false;
396
397 auto Size = getStaticAllocaSizeRange(*AI);
398
399 auto *CalculationTy = IntegerType::getIntNTy(SE.getContext(), PointerSize);
400 auto ToDiffTy = [&](const SCEV *V) {
401 return SE.getTruncateOrZeroExtend(V, CalculationTy);
402 };
403 const SCEV *Min = ToDiffTy(SE.getConstant(Size.getLower()));
404 const SCEV *Max = SE.getMinusSCEV(ToDiffTy(SE.getConstant(Size.getUpper())),
405 ToDiffTy(AccessSize));
406 return SE.evaluatePredicateAt(ICmpInst::Predicate::ICMP_SGE, Diff, Min, I)
407 .value_or(false) &&
408 SE.evaluatePredicateAt(ICmpInst::Predicate::ICMP_SLE, Diff, Max, I)
409 .value_or(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(Ptr);
420 AllocaInst *AI = dyn_cast<AllocaInst>(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>(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, UnknownRange, /*IsSafe=*/false);
436 return;
437 }
438 if (AI && !SL.isAliveAfter(AI, I)) {
439 US.addRange(I, UnknownRange, /*IsSafe=*/false);
440 return;
441 }
442 auto TypeSize = DL.getTypeStoreSize(StoredVal->getType());
443 auto AccessRange = getAccessRange(UI, Ptr, TypeSize);
444 bool Safe = isSafeAccess(UI, AI, TypeSize);
445 US.addRange(I, AccessRange, Safe);
446 return;
447 };
448
449 switch (I->getOpcode()) {
450 case Instruction::Load: {
451 if (AI && !SL.isAliveAfter(AI, I)) {
452 US.addRange(I, UnknownRange, /*IsSafe=*/false);
453 break;
454 }
455 auto TypeSize = DL.getTypeStoreSize(I->getType());
456 auto AccessRange = getAccessRange(UI, Ptr, TypeSize);
457 bool Safe = isSafeAccess(UI, AI, TypeSize);
458 US.addRange(I, AccessRange, 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>(I)->getValueOperand());
467 break;
468 case Instruction::AtomicCmpXchg:
469 RecordStore(cast<AtomicCmpXchgInst>(I)->getNewValOperand());
470 break;
471 case Instruction::AtomicRMW:
472 RecordStore(cast<AtomicRMWInst>(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, 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, UnknownRange, /*IsSafe=*/false);
489 break;
490 }
491 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
492 auto AccessRange = getMemIntrinsicAccessRange(MI, UI, Ptr);
493 bool Safe = false;
494 if (const auto *MTI = dyn_cast<MemTransferInst>(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(UI, AI, MI->getLength());
501 US.addRange(I, AccessRange, Safe);
502 break;
503 }
504
505 const auto &CB = cast<CallBase>(*I);
506 if (CB.getReturnedArgOperand() == V) {
507 if (Visited.insert(I).second)
509 }
510
511 if (!CB.isArgOperand(&UI)) {
512 US.addRange(I, UnknownRange, /*IsSafe=*/false);
513 break;
514 }
515
516 unsigned ArgNo = CB.getArgOperandNo(&UI);
517 if (CB.isByValArgument(ArgNo)) {
518 auto TypeSize = DL.getTypeStoreSize(CB.getParamByValType(ArgNo));
519 auto AccessRange = getAccessRange(UI, Ptr, TypeSize);
520 bool Safe = isSafeAccess(UI, AI, TypeSize);
521 US.addRange(I, AccessRange, 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>(CB.getCalledOperand()->stripPointerCasts());
530 if (!Callee || isa<GlobalIFunc>(Callee) ||
531 isa<GlobalVariable>(Callee)) {
532 US.addRange(I, UnknownRange, /*IsSafe=*/false);
533 break;
534 }
535
536 assert(isa<Function>(Callee) || isa<GlobalAlias>(Callee));
537 ConstantRange Offsets = offsetFrom(UI, Ptr);
538 auto Insert =
539 US.Calls.emplace(CallInfo<GlobalValue>(Callee, ArgNo), Offsets);
540 if (!Insert.second)
541 Insert.first->second = Insert.first->second.unionWith(Offsets);
542 break;
543 }
544
545 default:
546 if (Visited.insert(I).second)
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
561 for (auto &I : instructions(F))
562 if (auto *AI = dyn_cast<AllocaInst>(&I))
563 Allocas.push_back(AI);
564 StackLifetime SL(F, Allocas, StackLifetime::LivenessType::Must);
565 SL.run();
566
567 for (auto *AI : Allocas) {
568 auto &UI = Info.Allocas.emplace(AI, PointerSize).first->second;
569 analyzeAllUses(AI, 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(A.getArgNo(), PointerSize).first->second;
577 analyzeAllUses(&A, 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(KV.first.Callee, KV.first.ParamNo, 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(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() {
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>(GVS.get()))
732 if (!AS->hasAliasee())
733 continue;
734 if (!isa<FunctionSummary>(GVS->getBaseObject()))
735 continue;
736 if (GlobalValue::isLocalLinkage(GVS->linkage())) {
737 if (GVS->modulePath() == ModuleId) {
738 S = GVS.get();
739 break;
740 }
741 } else if (GlobalValue::isExternalLinkage(GVS->linkage())) {
742 if (S) {
743 ++NumIndexCalleeMultipleExternal;
744 return nullptr;
745 }
746 S = GVS.get();
747 } else if (GlobalValue::isWeakLinkage(GVS->linkage())) {
748 if (S) {
749 ++NumIndexCalleeMultipleWeak;
750 return nullptr;
751 }
752 S = GVS.get();
753 } else if (GlobalValue::isAvailableExternallyLinkage(GVS->linkage()) ||
754 GlobalValue::isLinkOnceLinkage(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>(S))
766 return FS;
767 AliasSummary *AS = dyn_cast<AliasSummary>(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>(GV))
782 return F;
783 const GlobalAlias *A = dyn_cast<GlobalAlias>(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(TmpCalls, Use.Calls);
810 for (const auto &C : TmpCalls) {
811 const Function *F = findCalleeInModule(C.first.Callee);
812 if (F) {
813 Use.Calls.emplace(CallInfo<GlobalValue>(F, C.first.ParamNo), C.second);
814 continue;
815 }
816
817 if (!Index)
818 return Use.updateRange(FullSet);
819 FunctionSummary *FS =
820 findCalleeFunctionSummary(Index->getValueInfo(C.first.Callee->getGUID()),
821 C.first.Callee->getParent()->getModuleIdentifier());
822 ++NumModuleCalleeLookupTotal;
823 if (!FS) {
824 ++NumModuleCalleeLookupFailed;
825 return Use.updateRange(FullSet);
826 }
827 const ConstantRange *Found = findParamAccess(*FS, C.first.ParamNo);
828 if (!Found || Found->isFullSet())
829 return Use.updateRange(FullSet);
830 ConstantRange Access = Found->sextOrTrunc(Use.Range.getBitWidth());
831 if (!Access.isEmptySet())
832 Use.updateRange(addOverflowNever(Access, 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(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(A, Index);
863 for (auto &C : A.Calls) {
864 A.updateRange(SSDFA.getArgumentAccessRange(C.first.Callee,
865 C.first.ParamNo, C.second));
866 }
867 // FIXME: This is needed only to preserve calls in print() results.
868 A.Calls = SrcF.Allocas.find(KV.first)->second.Calls;
869 }
870 for (auto &KV : FI.Params) {
871 auto &P = KV.second;
872 P.Calls = SrcF.Params.find(KV.first)->second.Calls;
873 }
874 SSI[F.first] = std::move(FI);
875 }
876
877 return SSI;
878}
879
880} // end anonymous namespace
881
883
885 std::function<ScalarEvolution &()> GetSE)
886 : F(F), GetSE(GetSE) {}
887
889
891
893
895 if (!Info) {
896 StackSafetyLocalAnalysis SSLA(*F, GetSE());
897 Info.reset(new InfoTy{SSLA.run()});
898 }
899 return *Info;
900}
901
903 getInfo().Info.print(O, 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(&F, std::move(FI));
914 }
915 }
916 Info.reset(new InfoTy{
917 createGlobalStackSafetyInfo(std::move(Functions), Index), {}, {}});
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);
924 if (AIRange.contains(KV.second.Range)) {
925 Info->SafeAllocas.insert(AI);
926 ++NumAllocaStackSafe;
927 }
928 Info->UnsafeAccesses.insert(KV.second.UnsafeAccesses.begin(),
929 KV.second.UnsafeAccesses.end());
930 }
931 }
932
934 print(errs());
935 }
936 return *Info;
937}
938
939std::vector<FunctionSummary::ParamAccess>
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(KV.first, PS.Range);
953 FunctionSummary::ParamAccess &Param = ParamAccesses.back();
954
955 Param.Calls.reserve(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(C.first.ParamNo,
966 Index.getOrInsertValueInfo(C.first.Callee),
967 C.second);
968 }
969 }
970 for (FunctionSummary::ParamAccess &Param : ParamAccesses) {
971 sort(Param.Calls, [](const FunctionSummary::ParamAccess::Call &L,
973 return std::tie(L.ParamNo, L.Callee) < std::tie(R.ParamNo, R.Callee);
974 });
975 }
976 return ParamAccesses;
977}
978
980
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
990 default;
991
994
996
998 const auto &Info = getInfo();
999 return Info.SafeAllocas.count(&AI);
1000}
1001
1003 const auto &Info = getInfo();
1004 return Info.UnsafeAccesses.find(&I) == Info.UnsafeAccesses.end();
1005}
1006
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(&F)->second.print(O, F.getName(), &F);
1015 O << " safe accesses:"
1016 << "\n";
1017 for (const auto &I : instructions(F)) {
1018 const CallInst *Call = dyn_cast<CallInst>(&I);
1021 (Call && Call->hasByValArgument())) &&
1023 O << " " << I << "\n";
1024 }
1025 }
1026 O << "\n";
1027 }
1028 }
1029}
1030
1032
1033AnalysisKey StackSafetyAnalysis::Key;
1034
1041
1044 OS << "'Stack Safety Local Analysis' for function '" << F.getName() << "'\n";
1046 return PreservedAnalyses::all();
1047}
1048
1050
1052
1057
1059 SSI.print(O);
1060}
1061
1063 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1064 SSI = {&F, [SE]() -> ScalarEvolution & { return *SE; }};
1065 return false;
1066}
1067
1068AnalysisKey StackSafetyGlobalAnalysis::Key;
1069
1074 const ModuleSummaryIndex *Index = nullptr;
1075 if (auto *IndexPass =
1077 Index = IndexPass->getIndex();
1078 return {&M,
1079 [&FAM](Function &F) -> const StackSafetyInfo & {
1080 return FAM.getResult<StackSafetyAnalysis>(F);
1081 },
1082 Index};
1083}
1084
1087 OS << "'Stack Safety Analysis' for module '" << M.getName() << "'\n";
1089 return PreservedAnalyses::all();
1090}
1091
1093
1096
1098
1100 const Module *M) const {
1101 SSGI.print(O);
1102}
1103
1109
1111 const ModuleSummaryIndex *ImportSummary = nullptr;
1112 if (auto *IndexWrapperPass =
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
1125 if (StackSafetyRun)
1126 return true;
1127 for (const auto &F : M.functions())
1128 if (F.hasFnAttribute(Attribute::SanitizeMemTag))
1129 return true;
1130 return false;
1131}
1132
1134 if (!Index.hasParamAccess())
1135 return;
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>(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()) {
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(PS.ParamNo, 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(Call.Callee, FS->modulePath());
1169 ++NumCombinedCalleeLookupTotal;
1170 if (!S) {
1171 ++NumCombinedCalleeLookupFailed;
1172 US.Range = FullSet;
1173 US.Calls.clear();
1174 break;
1175 }
1176 US.Calls.emplace(CallInfo<FunctionSummary>(S, Call.ParamNo),
1177 Call.Offsets);
1178 }
1179 }
1180 Functions.emplace(FS, 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(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";
1213 false, true)
1217
1218static const char GlobalPassName[] = "Stack Safety Analysis";
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
DXIL Resource Access
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static void addRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
This is the interface to build a ModuleSummaryIndex for a module.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
#define P(N)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static const char LocalPassArg[]
static const char LocalPassName[]
static true const char GlobalPassName[]
static cl::opt< int > StackSafetyMaxIterations("stack-safety-max-iterations", cl::init(20), cl::Hidden)
static cl::opt< bool > StackSafetyRun("stack-safety-run", cl::init(false), cl::Hidden)
static cl::opt< bool > StackSafetyPrint("stack-safety-print", cl::init(false), cl::Hidden)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
an instruction to allocate memory on the stack
LLVM_ABI TypeSize getAllocationBaseSize(const DataLayout &DL) const
Get the size of the allocated type.
PointerType * getType() const
Overload to return most specific pointer type.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
This class represents a function call, abstracting a target machine's calling convention.
This class represents a range of values.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
FunctionPass(char &pid)
Definition Pass.h:316
Function summary information to aid decisions and implementation of importing.
GlobalValueSummary * getBaseObject()
If this is an alias summary, returns the summary of the aliased object (a global variable or function...
bool isDSOLocal() const
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
static bool isLinkOnceLinkage(LinkageTypes Linkage)
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
static bool isExternalLinkage(LinkageTypes Linkage)
static bool isWeakLinkage(LinkageTypes Linkage)
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:178
NPM analysis to provide an externally-built ModuleSummaryIndex (e.g.
Legacy wrapper pass to provide the ModuleSummaryIndex object.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
This is the common base class for memset/memcpy/memmove.
ModulePass(char &pid)
Definition Pass.h:257
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class represents an analyzed expression in the program.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVMContext & getContext() const
void insert_range(Range &&R)
Definition SetVector.h:182
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
value_type pop_back_val()
Definition SetVector.h:285
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
iterator erase(const_iterator CI)
void push_back(const T &Elt)
Compute live ranges of allocas.
LLVM_ABI void run()
LLVM_ABI bool isReachable(const Instruction *I) const
Returns true if instruction is reachable from entry.
LLVM_ABI bool isAliveAfter(const AllocaInst *AI, const Instruction *I) const
Returns true if the alloca is alive after the instruction.
StackSafetyInfo wrapper for the new pass manager.
LLVM_ABI StackSafetyInfo run(Function &F, FunctionAnalysisManager &AM)
This pass performs the global (interprocedural) stack safety analysis (new pass manager).
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &AM)
This pass performs the global (interprocedural) stack safety analysis (legacy pass manager).
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &O, const Module *M) const override
print - Print out the internal state of the pass.
LLVM_ABI void print(raw_ostream &O) const
LLVM_ABI bool stackAccessIsSafe(const Instruction &I) const
LLVM_ABI bool isSafe(const AllocaInst &AI) const
LLVM_ABI StackSafetyGlobalInfo & operator=(StackSafetyGlobalInfo &&)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
StackSafetyInfo wrapper for the legacy pass manager.
void print(raw_ostream &O, const Module *M) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Interface to access stack safety analysis results for single function.
LLVM_ABI void print(raw_ostream &O) const
LLVM_ABI ~StackSafetyInfo()
LLVM_ABI const InfoTy & getInfo() const
LLVM_ABI StackSafetyInfo()
LLVM_ABI StackSafetyInfo & operator=(StackSafetyInfo &&)
LLVM_ABI std::vector< FunctionSummary::ParamAccess > getParamAccesses(ModuleSummaryIndex &Index) const
Parameters use for a FunctionSummary.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
Changed
Offsets
Offsets in bytes from the start of the input buffer.
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void generateParamAccessSummary(ModuleSummaryIndex &Index)
LLVM_ABI bool needsParamAccessSummary(const Module &M)
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
std::set< const Instruction * > UnsafeAccesses
SmallPtrSet< const AllocaInst *, 8 > SafeAllocas
FunctionInfo< GlobalValue > Info
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Describes the use of a value in a call instruction, specifying the call's target, the value's paramet...
Describes the uses of a parameter by the function.
static constexpr uint32_t RangeWidth