19#include "llvm/ADT/DenseMap.h"
20#include "llvm/Support/raw_ostream.h"
28class LiveVariablesImpl {
31 llvm::ImmutableSet<const Expr *>::Factory ESetFact;
32 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
33 llvm::ImmutableSet<const BindingDecl *>::Factory BSetFact;
34 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
35 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
36 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
37 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
38 const bool killAtAssign;
52 : analysisContext(ac),
55 BSetFact(
false), killAtAssign(KillAtAssign) {}
59static LiveVariablesImpl &
getImpl(
void *x) {
60 return *((LiveVariablesImpl *) x);
72 if (
const auto *DD = dyn_cast<DecompositionDecl>(D)) {
75 alive |= liveBindings.contains(BD);
80 alive |= liveDecls.contains(DD);
83 return liveDecls.contains(D);
87 template <
typename SET>
88 SET mergeSets(SET A, SET B) {
92 for (
typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
99void LiveVariables::Observer::anchor() { }
105 llvm::ImmutableSetRef<const Expr *> SSetRefA(
106 valsA.
liveExprs.getRootWithoutRetain(), ESetFact.getTreeFactory()),
107 SSetRefB(valsB.
liveExprs.getRootWithoutRetain(),
108 ESetFact.getTreeFactory());
110 llvm::ImmutableSetRef<const VarDecl *>
111 DSetRefA(valsA.
liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
112 DSetRefB(valsB.
liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
114 llvm::ImmutableSetRef<const BindingDecl *>
115 BSetRefA(valsA.
liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()),
116 BSetRefB(valsB.
liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory());
118 SSetRefA = mergeSets(SSetRefA, SSetRefB);
119 DSetRefA = mergeSets(DSetRefA, DSetRefB);
120 BSetRefA = mergeSets(BSetRefA, BSetRefB);
125 DSetRefA.asImmutableSet(),
126 BSetRefA.asImmutableSet());
130 return liveExprs ==
V.liveExprs && liveDecls ==
V.liveDecls;
150 return getImpl(impl).stmtsToLiveness[Loc].isLive(Val);
158class TransferFunctions :
public StmtVisitor<TransferFunctions> {
159 LiveVariablesImpl &LV;
164 TransferFunctions(LiveVariablesImpl &im,
168 : LV(im), val(Val), observer(Observer), currentBlock(
CurrentBlock) {}
183 while (
const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
185 if (VAT->getSizeExpr())
188 ty = VT->getElementType().getTypePtr();
196 if (
const Expr *Ex = dyn_cast<Expr>(E))
198 if (
const FullExpr *FE = dyn_cast<FullExpr>(E)) {
199 E = FE->getSubExpr();
203 E = OVE->getSourceExpr();
212 llvm::ImmutableSet<const Expr *>::Factory &F,
217void TransferFunctions::Visit(
Stmt *S) {
219 observer->observeStmt(S, currentBlock, val);
223 if (
const auto *E = dyn_cast<Expr>(S)) {
224 val.liveExprs = LV.ESetFact.remove(val.liveExprs, E);
229 switch (S->getStmtClass()) {
232 case Stmt::StmtExprClass: {
234 S = cast<StmtExpr>(S)->getSubStmt();
237 case Stmt::CXXMemberCallExprClass: {
241 AddLiveExpr(val.liveExprs, LV.ESetFact, ImplicitObj);
245 case Stmt::ObjCMessageExprClass: {
249 val.liveDecls = LV.DSetFact.add(val.liveDecls,
250 LV.analysisContext.getSelfDecl());
253 case Stmt::DeclStmtClass: {
254 const DeclStmt *DS = cast<DeclStmt>(S);
257 VA !=
nullptr; VA =
FindVA(VA->getElementType())) {
258 AddLiveExpr(val.liveExprs, LV.ESetFact, VA->getSizeExpr());
263 case Stmt::PseudoObjectExprClass: {
266 Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
269 child = OV->getSourceExpr();
271 val.liveExprs = LV.ESetFact.add(val.liveExprs, child);
276 case Stmt::ExprWithCleanupsClass: {
277 S = cast<ExprWithCleanups>(S)->getSubExpr();
280 case Stmt::CXXBindTemporaryExprClass: {
281 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
284 case Stmt::UnaryExprOrTypeTraitExprClass: {
288 case Stmt::IfStmtClass: {
292 AddLiveExpr(val.liveExprs, LV.ESetFact, cast<IfStmt>(S)->getCond());
295 case Stmt::WhileStmtClass: {
299 AddLiveExpr(val.liveExprs, LV.ESetFact, cast<WhileStmt>(S)->getCond());
302 case Stmt::DoStmtClass: {
306 AddLiveExpr(val.liveExprs, LV.ESetFact, cast<DoStmt>(S)->getCond());
309 case Stmt::ForStmtClass: {
313 AddLiveExpr(val.liveExprs, LV.ESetFact, cast<ForStmt>(S)->getCond());
322 for (
Stmt *Child : S->children()) {
323 if (
const auto *E = dyn_cast_or_null<Expr>(Child))
334 if (LV.killAtAssign && B->
getOpcode() == BO_Assign) {
336 LV.inAssignment[DR] = 1;
340 if (!LV.killAtAssign)
346 if (
DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
347 const Decl* D = DR->getDecl();
350 if (
const BindingDecl* BD = dyn_cast<BindingDecl>(D)) {
351 Killed = !BD->getType()->isReferenceType();
353 if (
const auto *HV = BD->getHoldingVar())
354 val.liveDecls = LV.DSetFact.remove(val.liveDecls, HV);
356 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
358 }
else if (
const auto *VD = dyn_cast<VarDecl>(D)) {
361 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
365 if (Killed && observer)
366 observer->observerKill(DR);
371void TransferFunctions::VisitBlockExpr(
BlockExpr *BE) {
373 LV.analysisContext.getReferencedBlockVars(BE->
getBlockDecl())) {
376 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
380void TransferFunctions::VisitDeclRefExpr(
DeclRefExpr *DR) {
382 bool InAssignment = LV.inAssignment[DR];
383 if (
const auto *BD = dyn_cast<BindingDecl>(D)) {
385 if (
const auto *HV = BD->getHoldingVar())
386 val.liveDecls = LV.DSetFact.
add(val.liveDecls, HV);
388 val.liveBindings = LV.BSetFact.add(val.liveBindings, BD);
390 }
else if (
const auto *VD = dyn_cast<VarDecl>(D)) {
392 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
396void TransferFunctions::VisitDeclStmt(
DeclStmt *DS) {
397 for (
const auto *DI : DS->
decls()) {
398 if (
const auto *DD = dyn_cast<DecompositionDecl>(DI)) {
399 for (
const auto *BD : DD->bindings()) {
400 if (
const auto *HV = BD->getHoldingVar())
401 val.liveDecls = LV.DSetFact.remove(val.liveDecls, HV);
403 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
408 val.liveDecls = LV.DSetFact.remove(val.liveDecls, DD);
409 }
else if (
const auto *VD = dyn_cast<VarDecl>(DI)) {
411 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
421 Stmt *element = OS->getElement();
422 if (
DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
425 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
426 VD = cast<VarDecl>(DR->
getDecl());
430 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
432 observer->observerKill(DR);
436void TransferFunctions::
448 val.liveExprs = LV.ESetFact.add(val.liveExprs, subEx->
IgnoreParens());
452void TransferFunctions::VisitUnaryOperator(
UnaryOperator *UO) {
471 if (isa<VarDecl>(D) || isa<BindingDecl>(D)) {
473 observer->observerKill(DR);
479LiveVariablesImpl::runOnBlock(
const CFGBlock *block,
483 TransferFunctions TF(*
this, val, obs, block);
487 TF.Visit(
const_cast<Stmt*
>(term));
491 ei = block->
rend(); it != ei; ++it) {
494 if (std::optional<CFGAutomaticObjDtor> Dtor =
504 TF.Visit(
const_cast<Stmt*
>(S));
505 stmtsToLiveness[S] = val;
511 const CFG *cfg =
getImpl(impl).analysisContext.getCFG();
513 getImpl(impl).runOnBlock(*it,
getImpl(impl).blocksEndToLiveness[*it], &obs);
516LiveVariables::LiveVariables(
void *im) : impl(im) {}
519 delete (LiveVariablesImpl*) impl;
522std::unique_ptr<LiveVariables>
526 CFG *cfg = AC.getCFG();
535 LiveVariablesImpl *LV =
new LiveVariablesImpl(AC, killAtAssign);
555 ei = block->
succ_end(); it != ei; ++it) {
557 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
562 everAnalyzedBlock[block->
getBlockID()] =
true;
563 else if (prevVal.
equals(val))
569 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
575 return std::unique_ptr<LiveVariables>(
new LiveVariables(LV));
579 getImpl(impl).dumpBlockLiveness(M);
582void LiveVariablesImpl::dumpBlockLiveness(
const SourceManager &M) {
583 std::vector<const CFGBlock *> vec;
584 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
585 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
587 vec.push_back(it->first);
593 std::vector<const VarDecl*> declVec;
595 for (std::vector<const CFGBlock *>::iterator
596 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
597 llvm::errs() <<
"\n[ B" << (*it)->getBlockID()
598 <<
" (live variables at block exit) ]\n";
603 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
605 se = vals.
liveDecls.end(); si != se; ++si) {
606 declVec.push_back(*si);
609 llvm::sort(declVec, [](
const Decl *A,
const Decl *B) {
613 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
614 de = declVec.end(); di != de; ++di) {
615 llvm::errs() <<
" " << (*di)->getDeclName().getAsString()
617 (*di)->getLocation().print(llvm::errs(), M);
618 llvm::errs() <<
">\n";
621 llvm::errs() <<
"\n";
625 getImpl(impl).dumpExprLiveness(M);
628void LiveVariablesImpl::dumpExprLiveness(
const SourceManager &M) {
630 for (
const CFGBlock *B : *analysisContext.getCFG()) {
632 llvm::errs() <<
"\n[ B" << B->getBlockID()
633 <<
" (live expressions at block exit) ]\n";
634 for (
const Expr *E : blocksEndToLiveness[B].liveExprs) {
635 llvm::errs() <<
"\n";
638 llvm::errs() <<
"\n";
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static const VariableArrayType * FindVA(const Type *t)
static bool writeShouldKill(const VarDecl *VD)
static void AddLiveExpr(llvm::ImmutableSet< const Expr * > &Set, llvm::ImmutableSet< const Expr * >::Factory &F, const Expr *E)
static LiveVariablesImpl & getImpl(void *x)
static const Expr * LookThroughExpr(const Expr *E)
static bool isAlwaysAlive(const VarDecl *D)
const CFGBlock * CurrentBlock
static bool runOnBlock(const CFGBlock *block, const CFG &cfg, AnalysisDeclContext &ac, CFGBlockValues &vals, const ClassifyRefs &classification, llvm::BitVector &wasAnalyzed, UninitVariablesHandler &handler)
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
A builtin binary operation expression such as "x + y" or "x <= y".
static bool isAssignmentOp(Opcode Opc)
A binding in a decomposition declaration.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
const BlockDecl * getBlockDecl() const
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Represents a single basic block in a source-level CFG.
reverse_iterator rbegin()
succ_iterator succ_begin()
Stmt * getTerminatorStmt()
unsigned getBlockID() const
AdjacentBlocks::const_iterator const_succ_iterator
Represents a top-level expression in a basic block.
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type.
std::optional< T > getAs() const
Convert to the specified CFGElement type, returning std::nullopt if this CFGElement is not of the des...
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
llvm::iterator_range< iterator > nodes()
Represents a call to a member function that may be written either with member call syntax (e....
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
void enqueueBlock(const CFGBlock *Block)
const CFGBlock * dequeue()
A reference to a declared variable, function, enum, etc.
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
const Decl * getSingleDecl() const
Decl - This represents one declaration (or definition), e.g.
SourceLocation getBeginLoc() const LLVM_READONLY
This represents one expression.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
FullExpr - Represents a "full-expression" node.
llvm::ImmutableSet< const BindingDecl * > liveBindings
llvm::ImmutableSet< const Expr * > liveExprs
llvm::ImmutableSet< const VarDecl * > liveDecls
bool isLive(const Expr *E) const
bool equals(const LivenessValues &V) const
void dumpExprLiveness(const SourceManager &M)
Print to stderr the expression liveness information associated with each basic block.
void dumpBlockLiveness(const SourceManager &M)
Print to stderr the variable liveness information associated with each basic block.
void runOnAllBlocks(Observer &obs)
~LiveVariables() override
static const void * getTag()
bool isLive(const CFGBlock *B, const VarDecl *D)
Return true if a variable is live at the end of a specified block.
static std::unique_ptr< LiveVariables > computeLiveness(AnalysisDeclContext &analysisContext, bool killAtAssign)
Compute the liveness information for a given CFG.
Represents Objective-C's collection statement.
An expression that sends a message to the given Objective-C object or class.
@ SuperInstance
The receiver is the instance of the superclass object.
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
A (possibly-)qualified type.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
static const void * getTag()
This class handles loading and caching of source files into memory.
RetTy Visit(PTR(Stmt) S, ParamTys... P)
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
The base class of the type hierarchy.
bool isReferenceType() const
bool isVariableArrayType() const
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
bool isArgumentType() const
UnaryExprOrTypeTrait getKind() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Expr * getSubExpr() const
Represents a variable declaration or definition.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Represents a C array with a specified size that is not an integer-constant-expression.
A worklist implementation for backward dataflow analysis.
void enqueuePredecessors(const CFGBlock *Block)