LiveVariables.cpp revision 357191743236353d2392075eba0d41647219bb61
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 while (S) { 236 if (const ParenExpr *ParenE = dyn_cast<ParenExpr>(S)) 237 S = ParenE->getSubExpr(); 238 else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) 239 S = OVE->getSourceExpr(); 240 else 241 break; 242 } 243 return S; 244} 245 246static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set, 247 llvm::ImmutableSet<const Stmt *>::Factory &F, 248 const Stmt *S) { 249 Set = F.add(Set, LookThroughStmt(S)); 250} 251 252void TransferFunctions::Visit(Stmt *S) { 253 if (observer) 254 observer->observeStmt(S, currentBlock, val); 255 256 StmtVisitor<TransferFunctions>::Visit(S); 257 258 if (isa<Expr>(S)) { 259 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S); 260 } 261 262 // Mark all children expressions live. 263 264 switch (S->getStmtClass()) { 265 default: 266 break; 267 case Stmt::StmtExprClass: { 268 // For statement expressions, look through the compound statement. 269 S = cast<StmtExpr>(S)->getSubStmt(); 270 break; 271 } 272 case Stmt::CXXMemberCallExprClass: { 273 // Include the implicit "this" pointer as being live. 274 CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S); 275 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) { 276 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj); 277 } 278 break; 279 } 280 case Stmt::DeclStmtClass: { 281 const DeclStmt *DS = cast<DeclStmt>(S); 282 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) { 283 for (const VariableArrayType* VA = FindVA(VD->getType()); 284 VA != 0; VA = FindVA(VA->getElementType())) { 285 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr()); 286 } 287 } 288 break; 289 } 290 // FIXME: These cases eventually shouldn't be needed. 291 case Stmt::ExprWithCleanupsClass: { 292 S = cast<ExprWithCleanups>(S)->getSubExpr(); 293 break; 294 } 295 case Stmt::CXXBindTemporaryExprClass: { 296 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr(); 297 break; 298 } 299 case Stmt::UnaryExprOrTypeTraitExprClass: { 300 // No need to unconditionally visit subexpressions. 301 return; 302 } 303 } 304 305 for (Stmt::child_iterator it = S->child_begin(), ei = S->child_end(); 306 it != ei; ++it) { 307 if (Stmt *child = *it) 308 AddLiveStmt(val.liveStmts, LV.SSetFact, child); 309 } 310} 311 312void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) { 313 if (B->isAssignmentOp()) { 314 if (!LV.killAtAssign) 315 return; 316 317 // Assigning to a variable? 318 Expr *LHS = B->getLHS()->IgnoreParens(); 319 320 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) 321 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 322 // Assignments to references don't kill the ref's address 323 if (VD->getType()->isReferenceType()) 324 return; 325 326 if (!isAlwaysAlive(VD)) { 327 // The variable is now dead. 328 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD); 329 } 330 331 if (observer) 332 observer->observerKill(DR); 333 } 334 } 335} 336 337void TransferFunctions::VisitBlockExpr(BlockExpr *BE) { 338 AnalysisDeclContext::referenced_decls_iterator I, E; 339 llvm::tie(I, E) = 340 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl()); 341 for ( ; I != E ; ++I) { 342 const VarDecl *VD = *I; 343 if (isAlwaysAlive(VD)) 344 continue; 345 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD); 346 } 347} 348 349void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) { 350 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl())) 351 if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end()) 352 val.liveDecls = LV.DSetFact.add(val.liveDecls, D); 353} 354 355void TransferFunctions::VisitDeclStmt(DeclStmt *DS) { 356 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE = DS->decl_end(); 357 DI != DE; ++DI) 358 if (VarDecl *VD = dyn_cast<VarDecl>(*DI)) { 359 if (!isAlwaysAlive(VD)) 360 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD); 361 } 362} 363 364void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) { 365 // Kill the iteration variable. 366 DeclRefExpr *DR = 0; 367 const VarDecl *VD = 0; 368 369 Stmt *element = OS->getElement(); 370 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) { 371 VD = cast<VarDecl>(DS->getSingleDecl()); 372 } 373 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) { 374 VD = cast<VarDecl>(DR->getDecl()); 375 } 376 377 if (VD) { 378 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD); 379 if (observer && DR) 380 observer->observerKill(DR); 381 } 382} 383 384void TransferFunctions:: 385VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE) 386{ 387 // While sizeof(var) doesn't technically extend the liveness of 'var', it 388 // does extent the liveness of metadata if 'var' is a VariableArrayType. 389 // We handle that special case here. 390 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType()) 391 return; 392 393 const Expr *subEx = UE->getArgumentExpr(); 394 if (subEx->getType()->isVariableArrayType()) { 395 assert(subEx->isLValue()); 396 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens()); 397 } 398} 399 400void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) { 401 // Treat ++/-- as a kill. 402 // Note we don't actually have to do anything if we don't have an observer, 403 // since a ++/-- acts as both a kill and a "use". 404 if (!observer) 405 return; 406 407 switch (UO->getOpcode()) { 408 default: 409 return; 410 case UO_PostInc: 411 case UO_PostDec: 412 case UO_PreInc: 413 case UO_PreDec: 414 break; 415 } 416 417 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) 418 if (isa<VarDecl>(DR->getDecl())) { 419 // Treat ++/-- as a kill. 420 observer->observerKill(DR); 421 } 422} 423 424LiveVariables::LivenessValues 425LiveVariablesImpl::runOnBlock(const CFGBlock *block, 426 LiveVariables::LivenessValues val, 427 LiveVariables::Observer *obs) { 428 429 TransferFunctions TF(*this, val, obs, block); 430 431 // Visit the terminator (if any). 432 if (const Stmt *term = block->getTerminator()) 433 TF.Visit(const_cast<Stmt*>(term)); 434 435 // Apply the transfer function for all Stmts in the block. 436 for (CFGBlock::const_reverse_iterator it = block->rbegin(), 437 ei = block->rend(); it != ei; ++it) { 438 const CFGElement &elem = *it; 439 if (!isa<CFGStmt>(elem)) 440 continue; 441 442 const Stmt *S = cast<CFGStmt>(elem).getStmt(); 443 TF.Visit(const_cast<Stmt*>(S)); 444 stmtsToLiveness[S] = val; 445 } 446 return val; 447} 448 449void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) { 450 const CFG *cfg = getImpl(impl).analysisContext.getCFG(); 451 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) 452 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs); 453} 454 455LiveVariables::LiveVariables(void *im) : impl(im) {} 456 457LiveVariables::~LiveVariables() { 458 delete (LiveVariablesImpl*) impl; 459} 460 461LiveVariables * 462LiveVariables::computeLiveness(AnalysisDeclContext &AC, 463 bool killAtAssign) { 464 465 // No CFG? Bail out. 466 CFG *cfg = AC.getCFG(); 467 if (!cfg) 468 return 0; 469 470 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign); 471 472 // Construct the dataflow worklist. Enqueue the exit block as the 473 // start of the analysis. 474 DataflowWorklist worklist(*cfg, AC); 475 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs()); 476 477 // FIXME: we should enqueue using post order. 478 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) { 479 const CFGBlock *block = *it; 480 worklist.enqueueBlock(block); 481 482 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment. 483 // We need to do this because we lack context in the reverse analysis 484 // to determine if a DeclRefExpr appears in such a context, and thus 485 // doesn't constitute a "use". 486 if (killAtAssign) 487 for (CFGBlock::const_iterator bi = block->begin(), be = block->end(); 488 bi != be; ++bi) { 489 if (const CFGStmt *cs = bi->getAs<CFGStmt>()) { 490 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(cs->getStmt())) { 491 if (BO->getOpcode() == BO_Assign) { 492 if (const DeclRefExpr *DR = 493 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) { 494 LV->inAssignment[DR] = 1; 495 } 496 } 497 } 498 } 499 } 500 } 501 502 worklist.sortWorklist(); 503 504 while (const CFGBlock *block = worklist.dequeue()) { 505 // Determine if the block's end value has changed. If not, we 506 // have nothing left to do for this block. 507 LivenessValues &prevVal = LV->blocksEndToLiveness[block]; 508 509 // Merge the values of all successor blocks. 510 LivenessValues val; 511 for (CFGBlock::const_succ_iterator it = block->succ_begin(), 512 ei = block->succ_end(); it != ei; ++it) { 513 if (const CFGBlock *succ = *it) { 514 val = LV->merge(val, LV->blocksBeginToLiveness[succ]); 515 } 516 } 517 518 if (!everAnalyzedBlock[block->getBlockID()]) 519 everAnalyzedBlock[block->getBlockID()] = true; 520 else if (prevVal.equals(val)) 521 continue; 522 523 prevVal = val; 524 525 // Update the dataflow value for the start of this block. 526 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val); 527 528 // Enqueue the value to the predecessors. 529 worklist.enqueuePredecessors(block); 530 } 531 532 return new LiveVariables(LV); 533} 534 535static bool compare_entries(const CFGBlock *A, const CFGBlock *B) { 536 return A->getBlockID() < B->getBlockID(); 537} 538 539static bool compare_vd_entries(const Decl *A, const Decl *B) { 540 SourceLocation ALoc = A->getLocStart(); 541 SourceLocation BLoc = B->getLocStart(); 542 return ALoc.getRawEncoding() < BLoc.getRawEncoding(); 543} 544 545void LiveVariables::dumpBlockLiveness(const SourceManager &M) { 546 getImpl(impl).dumpBlockLiveness(M); 547} 548 549void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) { 550 std::vector<const CFGBlock *> vec; 551 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator 552 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end(); 553 it != ei; ++it) { 554 vec.push_back(it->first); 555 } 556 std::sort(vec.begin(), vec.end(), compare_entries); 557 558 std::vector<const VarDecl*> declVec; 559 560 for (std::vector<const CFGBlock *>::iterator 561 it = vec.begin(), ei = vec.end(); it != ei; ++it) { 562 llvm::errs() << "\n[ B" << (*it)->getBlockID() 563 << " (live variables at block exit) ]\n"; 564 565 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it]; 566 declVec.clear(); 567 568 for (llvm::ImmutableSet<const VarDecl *>::iterator si = 569 vals.liveDecls.begin(), 570 se = vals.liveDecls.end(); si != se; ++si) { 571 declVec.push_back(*si); 572 } 573 574 std::sort(declVec.begin(), declVec.end(), compare_vd_entries); 575 576 for (std::vector<const VarDecl*>::iterator di = declVec.begin(), 577 de = declVec.end(); di != de; ++di) { 578 llvm::errs() << " " << (*di)->getDeclName().getAsString() 579 << " <"; 580 (*di)->getLocation().dump(M); 581 llvm::errs() << ">\n"; 582 } 583 } 584 llvm::errs() << "\n"; 585} 586 587const void *LiveVariables::getTag() { static int x; return &x; } 588const void *RelaxedLiveVariables::getTag() { static int x; return &x; } 589