22 #define DEBUG_TYPE "stack-safety" 32 const Value *AllocaPtr;
38 const SCEV *visit(
const SCEV *Expr) {
42 if (!isa<SCEVAddRecExpr>(Expr) && !isa<SCEVAddExpr>(Expr) &&
43 !isa<SCEVUnknown>(Expr))
53 return SE.getZero(Expr->
getType());
59 struct PassAsArgInfo {
70 : Callee(Callee), ParamNo(ParamNo), Offset(Offset) {}
76 return OS <<
"@" << P.getName() <<
"(arg" << P.ParamNo <<
", " << P.Offset
89 explicit UseInfo(
unsigned PointerSize) : Range{PointerSize,
false} {}
96 for (
auto &Call : U.Calls)
106 AllocaInfo(
unsigned PointerSize,
const AllocaInst *AI, uint64_t Size)
107 : AI(AI), Size(Size), Use(PointerSize) {}
113 return OS << A.getName() <<
"[" << A.Size <<
"]: " << A.Use;
120 explicit ParamInfo(
unsigned PointerSize,
const Argument *Arg)
121 : Arg(Arg), Use(PointerSize) {}
127 return OS << P.getName() <<
"[]: " << P.Use;
132 uint64_t getStaticAllocaAllocationSize(
const AllocaInst *AI) {
139 Size *=
C->getZExtValue();
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";
195 for (
unsigned ArgNo = 0; ArgNo < Type->
getNumParams(); ArgNo++) {
204 class StackSafetyLocalAnalysis {
208 unsigned PointerSize = 0;
214 uint64_t AccessSize);
216 const Value *AllocaPtr);
218 bool analyzeAllUses(
const Value *Ptr, UseInfo &AS);
228 UnknownRange(PointerSize,
true) {}
235 StackSafetyLocalAnalysis::offsetFromAlloca(
Value *Addr,
236 const Value *AllocaPtr) {
237 if (!SE.isSCEVable(Addr->
getType()))
240 AllocaOffsetRewriter
Rewriter(SE, AllocaPtr);
241 const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
248 const Value *AllocaPtr,
249 uint64_t AccessSize) {
250 if (!SE.isSCEVable(Addr->
getType()))
253 AllocaOffsetRewriter
Rewriter(SE, AllocaPtr);
254 const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
257 SE.getUnsignedRange(Expr).
zextOrTrunc(PointerSize);
264 ConstantRange StackSafetyLocalAnalysis::getMemIntrinsicAccessRange(
266 if (
auto MTI = dyn_cast<MemTransferInst>(MI)) {
267 if (MTI->getRawSource() != U && MTI->getRawDest() != U)
268 return getRange(0, 1);
271 return getRange(0, 1);
277 ConstantRange AccessRange = getAccessRange(U, AllocaPtr, Len->getZExtValue());
283 bool StackSafetyLocalAnalysis::analyzeAllUses(
const Value *Ptr, UseInfo &US) {
289 while (!WorkList.
empty()) {
291 for (
const Use &UI : V->
uses()) {
292 auto I = cast<const Instruction>(UI.getUser());
295 switch (
I->getOpcode()) {
302 case Instruction::VAArg:
306 if (V ==
I->getOperand(0)) {
308 US.updateRange(UnknownRange);
311 US.updateRange(getAccessRange(
320 US.updateRange(UnknownRange);
324 case Instruction::Invoke: {
327 if (
I->isLifetimeStartOrEnd())
331 US.updateRange(getMemIntrinsicAccessRange(MI, UI, Ptr));
341 US.updateRange(UnknownRange);
345 assert(isa<Function>(Callee) || isa<GlobalAlias>(Callee));
351 US.Calls.emplace_back(Callee, A - B, Offset);
360 WorkList.
push_back(cast<const Instruction>(
I));
371 "Can't run StackSafety on a function declaration");
376 if (
auto AI = dyn_cast<AllocaInst>(&
I)) {
378 getStaticAllocaAllocationSize(AI));
380 analyzeAllUses(AI, AS.Use);
387 analyzeAllUses(&A, PS.Use);
395 class StackSafetyDataFlowAnalysis {
397 std::map<const GlobalValue *, StackSafetyInfo::FunctionInfo>;
399 FunctionMap Functions;
404 unsigned PointerSize = 0;
408 unsigned ParamNo)
const;
409 bool updateOneUse(UseInfo &US,
bool UpdateToFullSet);
413 updateOneNode(Callee, Functions.find(Callee)->second);
415 void updateAllNodes() {
416 for (
auto &
F : Functions)
417 updateOneNode(
F.first,
F.second);
421 void verifyFixedPoint();
425 StackSafetyDataFlowAnalysis(
430 StackSafetyDataFlowAnalysis::StackSafetyDataFlowAnalysis(
433 UnknownRange(PointerSize,
true) {
437 if (!
F.isDeclaration())
438 Functions.emplace(&
F, FI(
F));
440 if (isa<Function>(A.getBaseObject()))
445 StackSafetyDataFlowAnalysis::getArgumentAccessRange(
const GlobalValue *Callee,
446 unsigned ParamNo)
const {
447 auto IT = Functions.find(Callee);
449 if (
IT == Functions.end())
458 return FS.
Params[ParamNo].Use.Range;
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");
468 ConstantRange CalleeRange = getArgumentAccessRange(CS.Callee, CS.ParamNo);
469 CalleeRange = CalleeRange.add(CS.Offset);
470 if (!US.Range.contains(CalleeRange)) {
473 US.Range = UnknownRange;
475 US.Range = US.Range.unionWith(CalleeRange);
481 void StackSafetyDataFlowAnalysis::updateOneNode(
484 bool Changed =
false;
486 Changed |= updateOneUse(AS.Use, UpdateToFullSet);
487 for (
auto &PS : FS.
Params)
488 Changed |= updateOneUse(PS.Use, UpdateToFullSet);
492 << (UpdateToFullSet ?
", full-set" :
"") <<
"] " 495 for (
auto &CallerID : Callers[Callee])
496 WorkList.insert(CallerID);
502 void StackSafetyDataFlowAnalysis::runDataFlow() {
507 for (
auto &
F : Functions) {
511 for (
auto &CS : AS.Use.Calls)
513 for (
auto &PS : FS.
Params)
514 for (
auto &CS : PS.Use.Calls)
520 for (
auto &Callee : Callees)
521 Callers[
Callee].push_back(
F.first);
526 while (!WorkList.empty()) {
529 updateOneNode(Callee);
534 void StackSafetyDataFlowAnalysis::verifyFixedPoint() {
546 for (
auto &
F : Functions)
547 SSI.emplace(
F.first, std::move(
F.second));
554 if (!
F.isDeclaration()) {
555 SSI.find(&
F)->second.print(O);
560 SSI.find(&A)->second.print(O);
564 assert(Count == SSI.size() &&
"Unexpected functions in the result");
569 StackSafetyInfo::StackSafetyInfo() =
default;
590 OS <<
"'Stack Safety Local Analysis' for function '" << F.
getName() <<
"'\n";
611 StackSafetyLocalAnalysis SSLA(
612 F, getAnalysis<ScalarEvolutionWrapperPass>().getSE());
624 StackSafetyDataFlowAnalysis SSDFA(
633 OS <<
"'Stack Safety Analysis' for module '" << M.
getName() <<
"'\n";
657 StackSafetyDataFlowAnalysis SSDFA(
659 return getAnalysis<StackSafetyInfoWrapperPass>(
F).
getResult();
678 GlobalPassName, false, false)
A parsed version of the target data layout string in and methods for querying it. ...
reference emplace_back(ArgTypes &&... Args)
Result run(Module &M, ModuleAnalysisManager &AM)
iterator_range< use_iterator > uses()
FunctionInfo(const StackSafetyInfo &SSI)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
StringRef getName() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
A Module instance is used to store all the information related to an LLVM module. ...
void print(raw_ostream &O, const Module *M) const override
print - Print out the internal state of the pass.
void push_back(const T &Elt)
The main scalar evolution driver.
StackSafetyGlobalInfoWrapperPass()
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
StringRef getName() const
Get a short "name" for the module.
block Block Frequency true
FunctionInfo(const Function *F)
Value * getLength() const
const SCEV * visit(const SCEV *S)
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
A Use represents the edge between a Value definition and its users.
ValTy * getCalledValue() const
Return the pointer to function that is being called.
static StringRef getName(Value *V)
void print(raw_ostream &O, const Module *M) const override
print - Print out the internal state of the pass.
ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static const char LocalPassArg[]
Class to represent function types.
Type * getType() const
All values are typed, get the type of this value.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Describes uses of allocas and parameters inside of a single function.
INITIALIZE_PASS_BEGIN(StackSafetyInfoWrapperPass, LocalPassArg, LocalPassName, false, true) INITIALIZE_PASS_END(StackSafetyInfoWrapperPass
const GlobalObject * getBaseObject() const
void print(raw_ostream &O) const
This pass performs the global (interprocedural) stack safety analysis (legacy pass manager)...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
The operation itself must be expressed in terms of simpler actions on this target.
Analysis containing CSE Info
const StackSafetyGlobalInfo & getResult() const
StackSafetyInfo wrapper for the new pass manager.
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on...
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
initializer< Ty > init(const Ty &Val)
SmallVector< ParamInfo, 4 > Params
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
iterator_range< iterator > functions()
StackSafetyInfo run(Function &F, FunctionAnalysisManager &AM)
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Interface to access stack safety analysis results for single function.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This pass performs the global (interprocedural) stack safety analysis (new pass manager).
const Value * getArraySize() const
Get the number of elements allocated.
StackSafetyInfo wrapper for the legacy pass manager.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static cl::opt< int > StackSafetyMaxIterations("stack-safety-max-iterations", cl::init(20), cl::Hidden)
void sort(IteratorTy Start, IteratorTy End)
bool isEmptySet() const
Return true if this set contains no members.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
This is the common base class for memset/memcpy/memmove.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
static const char LocalPassName[]
void print(raw_ostream &O) const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
std::map< const GlobalValue *, StackSafetyInfo > StackSafetyGlobalInfo
This class represents a range of values.
LLVM_NODISCARD T pop_back_val()
static true const char GlobalPassName[]
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
amdgpu Simplify well known AMD library false FunctionCallee Callee
void setPreservesAll()
Set by analyses that do not transform their input at all.
print must be executed print the must be executed contexed for all instructions
Analysis pass that exposes the ScalarEvolution for a function.
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate IT block based on arch"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT, "arm-no-restrict-it", "Allow IT blocks based on ARMv7")))
Virtual Register Rewriter
This class represents an analyzed expression in the program.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
Establish a view to a call site for examination.
StackSafetyInfoWrapperPass()
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
void initializeStackSafetyGlobalInfoWrapperPassPass(PassRegistry &)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void initializeStackSafetyInfoWrapperPassPass(PassRegistry &)
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
A vector that has set insertion semantics.
SmallVector< AllocaInfo, 4 > Allocas
This class implements an extremely fast bulk output stream that can only output to a stream...
print Print MemDeps of function
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
Value * getRawDest() const
A special type used by analysis passes to provide an address that identifies that particular analysis...
This visitor recursively visits a SCEV expression and re-writes it.
bool IsInterposable() const
an instruction to allocate memory on the stack
iterator_range< alias_iterator > aliases()
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...