LiveVariables.cpp revision 51e6c0d7596325c33919a589a308c3c1ff07baed
1#include "clang/Analysis/Analyses/LiveVariables.h" 2#include "clang/Analysis/Analyses/PostOrderCFGView.h" 3 4#include "clang/AST/Stmt.h" 5#include "clang/Analysis/CFG.h" 6#include "clang/Analysis/AnalysisContext.h" 7#include "clang/AST/StmtVisitor.h" 8 9#include "llvm/ADT/PostOrderIterator.h" 10#include "llvm/ADT/DenseMap.h" 11 12#include <deque> 13#include <algorithm> 14#include <vector> 15 16using namespace clang; 17 18namespace { 19 20class DataflowWorklist { 21 SmallVector<const CFGBlock *, 20> worklist; 22 llvm::BitVector enqueuedBlocks; 23 PostOrderCFGView *POV; 24public: 25 DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx) 26 : enqueuedBlocks(cfg.getNumBlockIDs()), 27 POV(Ctx.getAnalysis<PostOrderCFGView>()) {} 28 29 void enqueueBlock(const CFGBlock *block); 30 void enqueueSuccessors(const CFGBlock *block); 31 void enqueuePredecessors(const CFGBlock *block); 32 33 const CFGBlock *dequeue(); 34 35 void sortWorklist(); 36}; 37 38} 39 40void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) { 41 if (block && !enqueuedBlocks[block->getBlockID()]) { 42 enqueuedBlocks[block->getBlockID()] = true; 43 worklist.push_back(block); 44 } 45} 46 47void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) { 48 const unsigned OldWorklistSize = worklist.size(); 49 for (CFGBlock::const_succ_iterator I = block->succ_begin(), 50 E = block->succ_end(); I != E; ++I) { 51 enqueueBlock(*I); 52 } 53 54 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size()) 55 return; 56 57 sortWorklist(); 58} 59 60void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) { 61 const unsigned OldWorklistSize = worklist.size(); 62 for (CFGBlock::const_pred_iterator I = block->pred_begin(), 63 E = block->pred_end(); I != E; ++I) { 64 enqueueBlock(*I); 65 } 66 67 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size()) 68 return; 69 70 sortWorklist(); 71} 72 73void DataflowWorklist::sortWorklist() { 74 std::sort(worklist.begin(), worklist.end(), POV->getComparator()); 75} 76 77const CFGBlock *DataflowWorklist::dequeue() { 78 if (worklist.empty()) 79 return 0; 80 const CFGBlock *b = worklist.back(); 81 worklist.pop_back(); 82 enqueuedBlocks[b->getBlockID()] = false; 83 return b; 84} 85 86namespace { 87class LiveVariablesImpl { 88public: 89 AnalysisDeclContext &analysisContext; 90 std::vector<LiveVariables::LivenessValues> cfgBlockValues; 91 llvm::ImmutableSet<const Stmt *>::Factory SSetFact; 92 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact; 93 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness; 94 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness; 95 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness; 96 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment; 97 const bool killAtAssign; 98 99 LiveVariables::LivenessValues 100 merge(LiveVariables::LivenessValues valsA, 101 LiveVariables::LivenessValues valsB); 102 103 LiveVariables::LivenessValues runOnBlock(const CFGBlock *block, 104 LiveVariables::LivenessValues val, 105 LiveVariables::Observer *obs = 0); 106 107 void dumpBlockLiveness(const SourceManager& M); 108 109 LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign) 110 : analysisContext(ac), 111 SSetFact(false), // Do not canonicalize ImmutableSets by default. 112 DSetFact(false), // This is a *major* performance win. 113 killAtAssign(KillAtAssign) {} 114}; 115} 116 117static LiveVariablesImpl &getImpl(void *x) { 118 return *((LiveVariablesImpl *) x); 119} 120 121//===----------------------------------------------------------------------===// 122// Operations and queries on LivenessValues. 123//===----------------------------------------------------------------------===// 124 125bool LiveVariables::LivenessValues::isLive(const Stmt *S) const { 126 return liveStmts.contains(S); 127} 128 129bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const { 130 return liveDecls.contains(D); 131} 132 133namespace { 134 template <typename SET> 135 SET mergeSets(SET A, SET B) { 136 if (A.isEmpty()) 137 return B; 138 139 for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) { 140 A = A.add(*it); 141 } 142 return A; 143 } 144} 145 146LiveVariables::LivenessValues 147LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA, 148 LiveVariables::LivenessValues valsB) { 149 150 llvm::ImmutableSetRef<const Stmt *> 151 SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()), 152 SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()); 153 154 155 llvm::ImmutableSetRef<const VarDecl *> 156 DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()), 157 DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()); 158 159 160 SSetRefA = mergeSets(SSetRefA, SSetRefB); 161 DSetRefA = mergeSets(DSetRefA, DSetRefB); 162 163 // asImmutableSet() canonicalizes the tree, allowing us to do an easy 164 // comparison afterwards. 165 return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(), 166 DSetRefA.asImmutableSet()); 167} 168 169bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const { 170 return liveStmts == V.liveStmts && liveDecls == V.liveDecls; 171} 172 173//===----------------------------------------------------------------------===// 174// Query methods. 175//===----------------------------------------------------------------------===// 176 177static bool isAlwaysAlive(const VarDecl *D) { 178 return D->hasGlobalStorage(); 179} 180 181bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) { 182 return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D); 183} 184 185bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) { 186 return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D); 187} 188 189bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) { 190 return getImpl(impl).stmtsToLiveness[Loc].isLive(S); 191} 192 193//===----------------------------------------------------------------------===// 194// Dataflow computation. 195//===----------------------------------------------------------------------===// 196 197namespace { 198class TransferFunctions : public StmtVisitor<TransferFunctions> { 199 LiveVariablesImpl &LV; 200 LiveVariables::LivenessValues &val; 201 LiveVariables::Observer *observer; 202 const CFGBlock *currentBlock; 203public: 204 TransferFunctions(LiveVariablesImpl &im, 205 LiveVariables::LivenessValues &Val, 206 LiveVariables::Observer *Observer, 207 const CFGBlock *CurrentBlock) 208 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {} 209 210 void VisitBinaryOperator(BinaryOperator *BO); 211 void VisitBlockExpr(BlockExpr *BE); 212 void VisitDeclRefExpr(DeclRefExpr *DR); 213 void VisitDeclStmt(DeclStmt *DS); 214 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS); 215 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE); 216 void VisitUnaryOperator(UnaryOperator *UO); 217 void Visit(Stmt *S); 218}; 219} 220 221static const VariableArrayType *FindVA(QualType Ty) { 222 const Type *ty = Ty.getTypePtr(); 223 while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) { 224 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT)) 225 if (VAT->getSizeExpr()) 226 return VAT; 227 228 ty = VT->getElementType().getTypePtr(); 229 } 230 231 return 0; 232} 233 234static const Stmt *LookThroughStmt(const Stmt *S) { 235 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) 236 return OVE->getSourceExpr()->IgnoreParens(); 237 if (const Expr *E = dyn_cast<Expr>(S)) 238 return E->IgnoreParens(); 239 return S; 240} 241 242static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set, 243 llvm::ImmutableSet<const Stmt *>::Factory &F, 244 const Stmt *S) { 245 Set = F.add(Set, LookThroughStmt(S)); 246} 247 248void TransferFunctions::Visit(Stmt *S) { 249 if (observer) 250 observer->observeStmt(S, currentBlock, val); 251 252 StmtVisitor<TransferFunctions>::Visit(S); 253 254 if (isa<Expr>(S)) { 255 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S); 256 } 257 258 // Mark all children expressions live. 259 260 switch (S->getStmtClass()) { 261 default: 262 break; 263 case Stmt::StmtExprClass: { 264 // For statement expressions, look through the compound statement. 265 S = cast<StmtExpr>(S)->getSubStmt(); 266 break; 267 } 268 case Stmt::CXXMemberCallExprClass: { 269 // Include the implicit "this" pointer as being live. 270 CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S); 271 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) { 272 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj); 273 } 274 break; 275 } 276 case Stmt::DeclStmtClass: { 277 const DeclStmt *DS = cast<DeclStmt>(S); 278 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) { 279 for (const VariableArrayType* VA = FindVA(VD->getType()); 280 VA != 0; VA = FindVA(VA->getElementType())) { 281 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr()); 282 } 283 } 284 break; 285 } 286 // FIXME: These cases eventually shouldn't be needed. 287 case Stmt::ExprWithCleanupsClass: { 288 S = cast<ExprWithCleanups>(S)->getSubExpr(); 289 break; 290 } 291 case Stmt::CXXBindTemporaryExprClass: { 292 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr(); 293 break; 294 } 295 case Stmt::UnaryExprOrTypeTraitExprClass: { 296 // No need to unconditionally visit subexpressions. 297 return; 298 } 299 } 300 301 for (Stmt::child_iterator it = S->child_begin(), ei = S->child_end(); 302 it != ei; ++it) { 303 if (Stmt *child = *it) 304 AddLiveStmt(val.liveStmts, LV.SSetFact, child); 305 } 306} 307 308void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) { 309 if (B->isAssignmentOp()) { 310 if (!LV.killAtAssign) 311 return; 312 313 // Assigning to a variable? 314 Expr *LHS = B->getLHS()->IgnoreParens(); 315 316 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) 317 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 318 // Assignments to references don't kill the ref's address 319 if (VD->getType()->isReferenceType()) 320 return; 321 322 if (!isAlwaysAlive(VD)) { 323 // The variable is now dead. 324 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD); 325 } 326 327 if (observer) 328 observer->observerKill(DR); 329 } 330 } 331} 332 333void TransferFunctions::VisitBlockExpr(BlockExpr *BE) { 334 AnalysisDeclContext::referenced_decls_iterator I, E; 335 llvm::tie(I, E) = 336 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl()); 337 for ( ; I != E ; ++I) { 338 const VarDecl *VD = *I; 339 if (isAlwaysAlive(VD)) 340 continue; 341 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD); 342 } 343} 344 345void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) { 346 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl())) 347 if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end()) 348 val.liveDecls = LV.DSetFact.add(val.liveDecls, D); 349} 350 351void TransferFunctions::VisitDeclStmt(DeclStmt *DS) { 352 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE = DS->decl_end(); 353 DI != DE; ++DI) 354 if (VarDecl *VD = dyn_cast<VarDecl>(*DI)) { 355 if (!isAlwaysAlive(VD)) 356 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD); 357 } 358} 359 360void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) { 361 // Kill the iteration variable. 362 DeclRefExpr *DR = 0; 363 const VarDecl *VD = 0; 364 365 Stmt *element = OS->getElement(); 366 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) { 367 VD = cast<VarDecl>(DS->getSingleDecl()); 368 } 369 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) { 370 VD = cast<VarDecl>(DR->getDecl()); 371 } 372 373 if (VD) { 374 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD); 375 if (observer && DR) 376 observer->observerKill(DR); 377 } 378} 379 380void TransferFunctions:: 381VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE) 382{ 383 // While sizeof(var) doesn't technically extend the liveness of 'var', it 384 // does extent the liveness of metadata if 'var' is a VariableArrayType. 385 // We handle that special case here. 386 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType()) 387 return; 388 389 const Expr *subEx = UE->getArgumentExpr(); 390 if (subEx->getType()->isVariableArrayType()) { 391 assert(subEx->isLValue()); 392 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens()); 393 } 394} 395 396void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) { 397 // Treat ++/-- as a kill. 398 // Note we don't actually have to do anything if we don't have an observer, 399 // since a ++/-- acts as both a kill and a "use". 400 if (!observer) 401 return; 402 403 switch (UO->getOpcode()) { 404 default: 405 return; 406 case UO_PostInc: 407 case UO_PostDec: 408 case UO_PreInc: 409 case UO_PreDec: 410 break; 411 } 412 413 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) 414 if (isa<VarDecl>(DR->getDecl())) { 415 // Treat ++/-- as a kill. 416 observer->observerKill(DR); 417 } 418} 419 420LiveVariables::LivenessValues 421LiveVariablesImpl::runOnBlock(const CFGBlock *block, 422 LiveVariables::LivenessValues val, 423 LiveVariables::Observer *obs) { 424 425 TransferFunctions TF(*this, val, obs, block); 426 427 // Visit the terminator (if any). 428 if (const Stmt *term = block->getTerminator()) 429 TF.Visit(const_cast<Stmt*>(term)); 430 431 // Apply the transfer function for all Stmts in the block. 432 for (CFGBlock::const_reverse_iterator it = block->rbegin(), 433 ei = block->rend(); it != ei; ++it) { 434 const CFGElement &elem = *it; 435 if (!isa<CFGStmt>(elem)) 436 continue; 437 438 const Stmt *S = cast<CFGStmt>(elem).getStmt(); 439 TF.Visit(const_cast<Stmt*>(S)); 440 stmtsToLiveness[S] = val; 441 } 442 return val; 443} 444 445void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) { 446 const CFG *cfg = getImpl(impl).analysisContext.getCFG(); 447 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) 448 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs); 449} 450 451LiveVariables::LiveVariables(void *im) : impl(im) {} 452 453LiveVariables::~LiveVariables() { 454 delete (LiveVariablesImpl*) impl; 455} 456 457LiveVariables * 458LiveVariables::computeLiveness(AnalysisDeclContext &AC, 459 bool killAtAssign) { 460 461 // No CFG? Bail out. 462 CFG *cfg = AC.getCFG(); 463 if (!cfg) 464 return 0; 465 466 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign); 467 468 // Construct the dataflow worklist. Enqueue the exit block as the 469 // start of the analysis. 470 DataflowWorklist worklist(*cfg, AC); 471 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs()); 472 473 // FIXME: we should enqueue using post order. 474 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) { 475 const CFGBlock *block = *it; 476 worklist.enqueueBlock(block); 477 478 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment. 479 // We need to do this because we lack context in the reverse analysis 480 // to determine if a DeclRefExpr appears in such a context, and thus 481 // doesn't constitute a "use". 482 if (killAtAssign) 483 for (CFGBlock::const_iterator bi = block->begin(), be = block->end(); 484 bi != be; ++bi) { 485 if (const CFGStmt *cs = bi->getAs<CFGStmt>()) { 486 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(cs->getStmt())) { 487 if (BO->getOpcode() == BO_Assign) { 488 if (const DeclRefExpr *DR = 489 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) { 490 LV->inAssignment[DR] = 1; 491 } 492 } 493 } 494 } 495 } 496 } 497 498 worklist.sortWorklist(); 499 500 while (const CFGBlock *block = worklist.dequeue()) { 501 // Determine if the block's end value has changed. If not, we 502 // have nothing left to do for this block. 503 LivenessValues &prevVal = LV->blocksEndToLiveness[block]; 504 505 // Merge the values of all successor blocks. 506 LivenessValues val; 507 for (CFGBlock::const_succ_iterator it = block->succ_begin(), 508 ei = block->succ_end(); it != ei; ++it) { 509 if (const CFGBlock *succ = *it) { 510 val = LV->merge(val, LV->blocksBeginToLiveness[succ]); 511 } 512 } 513 514 if (!everAnalyzedBlock[block->getBlockID()]) 515 everAnalyzedBlock[block->getBlockID()] = true; 516 else if (prevVal.equals(val)) 517 continue; 518 519 prevVal = val; 520 521 // Update the dataflow value for the start of this block. 522 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val); 523 524 // Enqueue the value to the predecessors. 525 worklist.enqueuePredecessors(block); 526 } 527 528 return new LiveVariables(LV); 529} 530 531static bool compare_entries(const CFGBlock *A, const CFGBlock *B) { 532 return A->getBlockID() < B->getBlockID(); 533} 534 535static bool compare_vd_entries(const Decl *A, const Decl *B) { 536 SourceLocation ALoc = A->getLocStart(); 537 SourceLocation BLoc = B->getLocStart(); 538 return ALoc.getRawEncoding() < BLoc.getRawEncoding(); 539} 540 541void LiveVariables::dumpBlockLiveness(const SourceManager &M) { 542 getImpl(impl).dumpBlockLiveness(M); 543} 544 545void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) { 546 std::vector<const CFGBlock *> vec; 547 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator 548 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end(); 549 it != ei; ++it) { 550 vec.push_back(it->first); 551 } 552 std::sort(vec.begin(), vec.end(), compare_entries); 553 554 std::vector<const VarDecl*> declVec; 555 556 for (std::vector<const CFGBlock *>::iterator 557 it = vec.begin(), ei = vec.end(); it != ei; ++it) { 558 llvm::errs() << "\n[ B" << (*it)->getBlockID() 559 << " (live variables at block exit) ]\n"; 560 561 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it]; 562 declVec.clear(); 563 564 for (llvm::ImmutableSet<const VarDecl *>::iterator si = 565 vals.liveDecls.begin(), 566 se = vals.liveDecls.end(); si != se; ++si) { 567 declVec.push_back(*si); 568 } 569 570 std::sort(declVec.begin(), declVec.end(), compare_vd_entries); 571 572 for (std::vector<const VarDecl*>::iterator di = declVec.begin(), 573 de = declVec.end(); di != de; ++di) { 574 llvm::errs() << " " << (*di)->getDeclName().getAsString() 575 << " <"; 576 (*di)->getLocation().dump(M); 577 llvm::errs() << ">\n"; 578 } 579 } 580 llvm::errs() << "\n"; 581} 582 583const void *LiveVariables::getTag() { static int x; return &x; } 584const void *RelaxedLiveVariables::getTag() { static int x; return &x; } 585