20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/PostOrderIterator.h" 22 #include "llvm/ADT/PriorityQueue.h" 23 #include "llvm/Support/raw_ostream.h" 27 using namespace clang;
31 class DataflowWorklist {
32 llvm::BitVector enqueuedBlocks;
34 llvm::PriorityQueue<const CFGBlock *, SmallVector<const CFGBlock *, 20>,
39 : enqueuedBlocks(cfg.getNumBlockIDs()),
41 worklist(POV->getComparator()) {}
43 void enqueueBlock(
const CFGBlock *block);
44 void enqueuePredecessors(
const CFGBlock *block);
52 if (block && !enqueuedBlocks[block->
getBlockID()]) {
58 void DataflowWorklist::enqueuePredecessors(
const clang::CFGBlock *block) {
60 E = block->
pred_end(); I != E; ++I) {
65 const CFGBlock *DataflowWorklist::dequeue() {
75 class LiveVariablesImpl {
81 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
82 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
83 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
84 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
85 const bool killAtAssign;
98 : analysisContext(ac),
102 killAtAssign(KillAtAssign) {}
107 return *((LiveVariablesImpl *) x);
115 return liveStmts.contains(S);
119 if (
const auto *DD = dyn_cast<DecompositionDecl>(D)) {
122 alive |= liveBindings.contains(BD);
125 return liveDecls.contains(D);
129 template <
typename SET>
130 SET mergeSets(SET A, SET B) {
134 for (
typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
141 void LiveVariables::Observer::anchor() { }
147 llvm::ImmutableSetRef<const Stmt *>
148 SSetRefA(valsA.
liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
149 SSetRefB(valsB.
liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
152 llvm::ImmutableSetRef<const VarDecl *>
153 DSetRefA(valsA.
liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
154 DSetRefB(valsB.
liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
156 llvm::ImmutableSetRef<const BindingDecl *>
157 BSetRefA(valsA.
liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()),
158 BSetRefB(valsB.
liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory());
160 SSetRefA = mergeSets(SSetRefA, SSetRefB);
161 DSetRefA = mergeSets(DSetRefA, DSetRefB);
162 BSetRefA = mergeSets(BSetRefA, BSetRefB);
167 DSetRefA.asImmutableSet(),
168 BSetRefA.asImmutableSet());
192 return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
200 class TransferFunctions :
public StmtVisitor<TransferFunctions> {
201 LiveVariablesImpl &LV;
206 TransferFunctions(LiveVariablesImpl &im,
210 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
225 while (
const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
227 if (VAT->getSizeExpr())
230 ty = VT->getElementType().getTypePtr();
238 if (
const Expr *Ex = dyn_cast<Expr>(S))
239 S = Ex->IgnoreParens();
241 S = EWC->getSubExpr();
245 S = OVE->getSourceExpr();
259 void TransferFunctions::Visit(
Stmt *S) {
261 observer->observeStmt(S, currentBlock, val);
266 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
274 case Stmt::StmtExprClass: {
276 S = cast<StmtExpr>(S)->getSubStmt();
279 case Stmt::CXXMemberCallExprClass: {
283 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
287 case Stmt::ObjCMessageExprClass: {
291 val.liveDecls = LV.DSetFact.add(val.liveDecls,
292 LV.analysisContext.getSelfDecl());
295 case Stmt::DeclStmtClass: {
296 const DeclStmt *DS = cast<DeclStmt>(S);
299 VA !=
nullptr; VA =
FindVA(VA->getElementType())) {
300 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
305 case Stmt::PseudoObjectExprClass: {
308 Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
311 child = OV->getSourceExpr();
313 val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
318 case Stmt::ExprWithCleanupsClass: {
319 S = cast<ExprWithCleanups>(S)->getSubExpr();
322 case Stmt::CXXBindTemporaryExprClass: {
323 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
326 case Stmt::UnaryExprOrTypeTraitExprClass: {
345 if (!LV.killAtAssign)
351 if (
DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
352 const Decl* D = DR->getDecl();
355 if (
const BindingDecl* BD = dyn_cast<BindingDecl>(D)) {
356 Killed = !BD->getType()->isReferenceType();
358 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
359 }
else if (
const auto *VD = dyn_cast<VarDecl>(D)) {
362 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
366 if (Killed && observer)
367 observer->observerKill(DR);
372 void TransferFunctions::VisitBlockExpr(
BlockExpr *BE) {
374 LV.analysisContext.getReferencedBlockVars(BE->
getBlockDecl())) {
377 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
381 void TransferFunctions::VisitDeclRefExpr(
DeclRefExpr *DR) {
383 bool InAssignment = LV.inAssignment[DR];
384 if (
const auto *BD = dyn_cast<BindingDecl>(D)) {
386 val.liveBindings = LV.BSetFact.
add(val.liveBindings, BD);
387 }
else if (
const auto *VD = dyn_cast<VarDecl>(D)) {
389 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
393 void TransferFunctions::VisitDeclStmt(
DeclStmt *DS) {
394 for (
const auto *DI : DS->
decls()) {
395 if (
const auto *DD = dyn_cast<DecompositionDecl>(DI)) {
396 for (
const auto *BD : DD->bindings())
397 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
398 }
else if (
const auto *VD = dyn_cast<VarDecl>(DI)) {
400 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
411 if (
DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
414 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
415 VD = cast<VarDecl>(DR->
getDecl());
419 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
421 observer->observerKill(DR);
425 void TransferFunctions::
437 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->
IgnoreParens());
441 void TransferFunctions::VisitUnaryOperator(
UnaryOperator *UO) {
460 if (isa<VarDecl>(D) || isa<BindingDecl>(D)) {
462 observer->observerKill(DR);
472 TransferFunctions TF(*
this, val, obs, block);
476 TF.Visit(const_cast<Stmt*>(term));
480 ei = block->
rend(); it != ei; ++it) {
493 TF.Visit(const_cast<Stmt*>(S));
494 stmtsToLiveness[S] = val;
500 const CFG *cfg =
getImpl(impl).analysisContext.getCFG();
502 getImpl(impl).runOnBlock(*it,
getImpl(impl).blocksEndToLiveness[*it], &obs);
505 LiveVariables::LiveVariables(
void *im) : impl(im) {}
508 delete (LiveVariablesImpl*) impl;
525 LiveVariablesImpl *LV =
new LiveVariablesImpl(AC, killAtAssign);
529 DataflowWorklist worklist(*cfg, AC);
535 worklist.enqueueBlock(block);
546 if (
const auto *BO = dyn_cast<BinaryOperator>(stmt)) {
547 if (BO->getOpcode() == BO_Assign) {
549 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
550 LV->inAssignment[DR] = 1;
558 while (
const CFGBlock *block = worklist.dequeue()) {
566 ei = block->
succ_end(); it != ei; ++it) {
568 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
573 everAnalyzedBlock[block->
getBlockID()] =
true;
574 else if (prevVal.
equals(val))
580 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
583 worklist.enqueuePredecessors(block);
590 getImpl(impl).dumpBlockLiveness(M);
593 void LiveVariablesImpl::dumpBlockLiveness(
const SourceManager &M) {
594 std::vector<const CFGBlock *> vec;
595 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
596 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
598 vec.push_back(it->first);
600 llvm::sort(vec.begin(), vec.end(), [](
const CFGBlock *A,
const CFGBlock *B) {
604 std::vector<const VarDecl*> declVec;
606 for (std::vector<const CFGBlock *>::iterator
607 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
608 llvm::errs() <<
"\n[ B" << (*it)->getBlockID()
609 <<
" (live variables at block exit) ]\n";
614 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
616 se = vals.
liveDecls.end(); si != se; ++si) {
617 declVec.push_back(*si);
620 llvm::sort(declVec.begin(), declVec.end(),
625 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
626 de = declVec.end(); di != de; ++di) {
627 llvm::errs() <<
" " << (*di)->getDeclName().getAsString()
629 (*di)->getLocation().dump(M);
630 llvm::errs() <<
">\n";
633 llvm::errs() <<
"\n";
The receiver is the instance of the superclass object.
const BlockDecl * getBlockDecl() const
static const VariableArrayType * FindVA(QualType Ty)
A (possibly-)qualified type.
static bool isAlwaysAlive(const VarDecl *D)
static const Stmt * LookThroughStmt(const Stmt *S)
AdjacentBlocks::const_iterator const_pred_iterator
static LiveVariables * computeLiveness(AnalysisDeclContext &analysisContext, bool killAtAssign)
Compute the liveness information for a given CFG.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
succ_iterator succ_begin()
Stmt - This represents one statement.
unsigned getBlockID() const
Decl - This represents one declaration (or definition), e.g.
Expr * getImplicitObjectArgument() const
Retrieves the implicit object argument for the member call.
The base class of the type hierarchy.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type...
static const void * getTag()
Represents a variable declaration or definition.
llvm::ImmutableSet< const BindingDecl * > liveBindings
bool equals(const LivenessValues &V) const
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
static bool isAssignmentOp(Opcode Opc)
bool isVariableArrayType() const
AnalysisDeclContext contains the context data for the function or method under analysis.
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
bool isReferenceType() const
void runOnAllBlocks(Observer &obs)
AdjacentBlocks::const_iterator const_succ_iterator
static bool runOnBlock(const CFGBlock *block, const CFG &cfg, AnalysisDeclContext &ac, CFGBlockValues &vals, const ClassifyRefs &classification, llvm::BitVector &wasAnalyzed, UninitVariablesHandler &handler)
bool isLive(const CFGBlock *B, const VarDecl *D)
Return true if a variable is live at the end of a specified block.
A builtin binary operation expression such as "x + y" or "x <= y".
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
A binding in a decomposition declaration.
~LiveVariables() override
CFGBlockListTy::const_iterator const_iterator
static const void * getTag()
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Represents a single basic block in a source-level CFG.
Expr - This represents one expression.
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt...
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
ElementList::const_iterator const_iterator
An expression that sends a message to the given Objective-C object or class.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
static LiveVariablesImpl & getImpl(void *x)
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
reverse_iterator rbegin()
SourceLocation getLocStart() const LLVM_READONLY
CFGTerminator getTerminator()
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
void dumpBlockLiveness(const SourceManager &M)
Print to stderr the liveness information associated with each basic block.
Expr * getSubExpr() const
static void AddLiveStmt(llvm::ImmutableSet< const Stmt *> &Set, llvm::ImmutableSet< const Stmt *>::Factory &F, const Stmt *S)
SourceLocation getLocStart() const LLVM_READONLY
Represents a call to a member function that may be written either with member call syntax (e...
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
llvm::ImmutableSet< const VarDecl * > liveDecls
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
UnaryExprOrTypeTrait getKind() const
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
bool isArgumentType() const
Optional< T > getAs() const
Convert to the specified CFGElement type, returning None if this CFGElement is not of the desired typ...
pred_iterator pred_begin()
Dataflow Directional Tag Classes.
bool isLive(const Stmt *S) const
StmtClass getStmtClass() const
const Decl * getSingleDecl() const
llvm::ImmutableSet< const Stmt * > liveStmts
Represents Objective-C's collection statement.
Represents a top-level expression in a basic block.
RetTy Visit(PTR(Stmt) S, ParamTys... P)
A reference to a declared variable, function, enum, etc.
static llvm::ImmutableListFactory< const FieldRegion * > Factory
Represents a C array with a specified size that is not an integer-constant-expression.
static bool writeShouldKill(const VarDecl *VD)
This class handles loading and caching of source files into memory.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.