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