blob: 44c5d51664686bef6a7fc1a664a421417281d8e3 [file] [log] [blame]
Ted Kremenekd27f8162008-01-15 23:55:06 +00001//===-- GRConstants.cpp - Simple, Path-Sens. Constant Prop. ------*- C++ -*-==//
Ted Kremenek64924852008-01-31 02:35:41 +00002//
Ted Kremenek4af84312008-01-31 06:49:09 +00003// The LLVM Compiler Infrastructure
Ted Kremenekd27f8162008-01-15 23:55:06 +00004//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Constant Propagation via Graph Reachability
11//
12// This files defines a simple analysis that performs path-sensitive
13// constant propagation within a function. An example use of this analysis
14// is to perform simple checks for NULL dereferences.
15//
16//===----------------------------------------------------------------------===//
17
Ted Kremeneka90ccfe2008-01-31 19:34:24 +000018#include "RValues.h"
19#include "ValueState.h"
20
Ted Kremenekd27f8162008-01-15 23:55:06 +000021#include "clang/Analysis/PathSensitive/GREngine.h"
22#include "clang/AST/Expr.h"
Ted Kremenek874d63f2008-01-24 02:02:54 +000023#include "clang/AST/ASTContext.h"
Ted Kremenekd27f8162008-01-15 23:55:06 +000024#include "clang/Analysis/Analyses/LiveVariables.h"
Ted Kremenekd27f8162008-01-15 23:55:06 +000025
26#include "llvm/Support/Casting.h"
27#include "llvm/Support/DataTypes.h"
28#include "llvm/ADT/APSInt.h"
29#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek3c6c6722008-01-16 17:56:25 +000031#include "llvm/ADT/SmallVector.h"
Ted Kremenekb38911f2008-01-30 23:03:39 +000032#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekab2b8c52008-01-23 19:59:44 +000033#include "llvm/Support/Allocator.h"
Ted Kremenekd27f8162008-01-15 23:55:06 +000034#include "llvm/Support/Compiler.h"
Ted Kremenekab2b8c52008-01-23 19:59:44 +000035#include "llvm/Support/Streams.h"
36
Ted Kremenek5ee4ff82008-01-25 22:55:56 +000037#include <functional>
38
Ted Kremenekaa66a322008-01-16 21:46:15 +000039#ifndef NDEBUG
40#include "llvm/Support/GraphWriter.h"
41#include <sstream>
42#endif
43
Ted Kremenekd27f8162008-01-15 23:55:06 +000044using namespace clang;
Ted Kremenekd27f8162008-01-15 23:55:06 +000045using llvm::dyn_cast;
46using llvm::cast;
Ted Kremenek5ee4ff82008-01-25 22:55:56 +000047using llvm::APSInt;
Ted Kremenekd27f8162008-01-15 23:55:06 +000048
49//===----------------------------------------------------------------------===//
Ted Kremenekbd03f1d2008-01-28 22:09:13 +000050// The Checker.
Ted Kremenekb38911f2008-01-30 23:03:39 +000051//
52// FIXME: This checker logic should be eventually broken into two components.
53// The first is the "meta"-level checking logic; the code that
54// does the Stmt visitation, fetching values from the map, etc.
55// The second part does the actual state manipulation. This way we
56// get more of a separate of concerns of these two pieces, with the
57// latter potentially being refactored back into the main checking
58// logic.
Ted Kremenekd27f8162008-01-15 23:55:06 +000059//===----------------------------------------------------------------------===//
60
61namespace {
Ted Kremenekd27f8162008-01-15 23:55:06 +000062
Ted Kremenekab2b8c52008-01-23 19:59:44 +000063class VISIBILITY_HIDDEN GRConstants {
Ted Kremenekd27f8162008-01-15 23:55:06 +000064
65public:
Ted Kremeneke070a1d2008-02-04 21:59:01 +000066 typedef ValueStateManager::StateTy StateTy;
Ted Kremenek7d7fe6d2008-01-29 22:56:11 +000067 typedef GRStmtNodeBuilder<GRConstants> StmtNodeBuilder;
68 typedef GRBranchNodeBuilder<GRConstants> BranchNodeBuilder;
Ted Kremenekcb48b9c2008-01-29 00:33:40 +000069 typedef ExplodedGraph<GRConstants> GraphTy;
70 typedef GraphTy::NodeTy NodeTy;
Ted Kremenekab2b8c52008-01-23 19:59:44 +000071
72 class NodeSet {
73 typedef llvm::SmallVector<NodeTy*,3> ImplTy;
74 ImplTy Impl;
75 public:
76
77 NodeSet() {}
Ted Kremenekb38911f2008-01-30 23:03:39 +000078 NodeSet(NodeTy* N) { assert (N && !N->isSink()); Impl.push_back(N); }
Ted Kremenekab2b8c52008-01-23 19:59:44 +000079
Ted Kremenekb38911f2008-01-30 23:03:39 +000080 void Add(NodeTy* N) { if (N && !N->isSink()) Impl.push_back(N); }
Ted Kremenekab2b8c52008-01-23 19:59:44 +000081
82 typedef ImplTy::iterator iterator;
83 typedef ImplTy::const_iterator const_iterator;
84
85 unsigned size() const { return Impl.size(); }
Ted Kremenek9de04c42008-01-24 20:55:43 +000086 bool empty() const { return Impl.empty(); }
Ted Kremenekab2b8c52008-01-23 19:59:44 +000087
88 iterator begin() { return Impl.begin(); }
89 iterator end() { return Impl.end(); }
90
91 const_iterator begin() const { return Impl.begin(); }
92 const_iterator end() const { return Impl.end(); }
93 };
Ted Kremenekcba2e432008-02-05 19:35:18 +000094
Ted Kremenekd27f8162008-01-15 23:55:06 +000095protected:
Ted Kremenekcb48b9c2008-01-29 00:33:40 +000096 /// G - the simulation graph.
97 GraphTy& G;
98
Ted Kremenekab2b8c52008-01-23 19:59:44 +000099 /// Liveness - live-variables information the ValueDecl* and block-level
100 /// Expr* in the CFG. Used to prune out dead state.
Ted Kremenekbffaa832008-01-29 05:13:23 +0000101 LiveVariables Liveness;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000102
Ted Kremenekf4b7a692008-01-29 22:11:49 +0000103 /// Builder - The current GRStmtNodeBuilder which is used when building the nodes
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000104 /// for a given statement.
Ted Kremenek7d7fe6d2008-01-29 22:56:11 +0000105 StmtNodeBuilder* Builder;
106
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000107 /// StateMgr - Object that manages the data for all created states.
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000108 ValueStateManager StateMgr;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000109
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000110 /// ValueMgr - Object that manages the data for all created RValues.
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000111 ValueManager& ValMgr;
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000112
Ted Kremenek68fd2572008-01-29 17:27:31 +0000113 /// SymMgr - Object that manages the symbol information.
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000114 SymbolManager& SymMgr;
Ted Kremenek68fd2572008-01-29 17:27:31 +0000115
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000116 /// StmtEntryNode - The immediate predecessor node.
117 NodeTy* StmtEntryNode;
118
119 /// CurrentStmt - The current block-level statement.
120 Stmt* CurrentStmt;
121
Ted Kremenekb38911f2008-01-30 23:03:39 +0000122 /// UninitBranches - Nodes in the ExplodedGraph that result from
123 /// taking a branch based on an uninitialized value.
124 typedef llvm::SmallPtrSet<NodeTy*,5> UninitBranchesTy;
125 UninitBranchesTy UninitBranches;
126
Ted Kremenekd131c4f2008-02-07 05:48:01 +0000127 /// ImplicitNullDeref - Nodes in the ExplodedGraph that result from
128 /// taking a dereference on a symbolic pointer that may be NULL.
129 typedef llvm::SmallPtrSet<NodeTy*,5> ImplicitNullDerefTy;
130 ImplicitNullDerefTy ImplicitNullDeref;
131
132
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000133 bool StateCleaned;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000134
Ted Kremenekcb48b9c2008-01-29 00:33:40 +0000135 ASTContext& getContext() const { return G.getContext(); }
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000136
Ted Kremenekd27f8162008-01-15 23:55:06 +0000137public:
Ted Kremenekbffaa832008-01-29 05:13:23 +0000138 GRConstants(GraphTy& g) : G(g), Liveness(G.getCFG(), G.getFunctionDecl()),
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000139 Builder(NULL),
Ted Kremenek768ad162008-02-05 05:15:51 +0000140 StateMgr(G.getContext(), G.getAllocator()),
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000141 ValMgr(StateMgr.getValueManager()),
142 SymMgr(StateMgr.getSymbolManager()),
143 StmtEntryNode(NULL), CurrentStmt(NULL) {
Ted Kremenekd27f8162008-01-15 23:55:06 +0000144
Ted Kremenekcb48b9c2008-01-29 00:33:40 +0000145 // Compute liveness information.
Ted Kremenekbffaa832008-01-29 05:13:23 +0000146 Liveness.runOnCFG(G.getCFG());
147 Liveness.runOnAllBlocks(G.getCFG(), NULL, true);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000148 }
Ted Kremenekcb48b9c2008-01-29 00:33:40 +0000149
150 /// getCFG - Returns the CFG associated with this analysis.
151 CFG& getCFG() { return G.getCFG(); }
Ted Kremenekd27f8162008-01-15 23:55:06 +0000152
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000153 /// getInitialState - Return the initial state used for the root vertex
154 /// in the ExplodedGraph.
Ted Kremenekd27f8162008-01-15 23:55:06 +0000155 StateTy getInitialState() {
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000156 StateTy St = StateMgr.getInitialState();
Ted Kremenekff6e3c52008-01-29 00:43:03 +0000157
158 // Iterate the parameters.
159 FunctionDecl& F = G.getFunctionDecl();
160
161 for (FunctionDecl::param_iterator I=F.param_begin(), E=F.param_end();
Ted Kremenek4150abf2008-01-31 00:09:56 +0000162 I!=E; ++I)
Ted Kremenek329f8542008-02-05 21:52:21 +0000163 St = SetValue(St, lval::DeclVal(*I), RValue::GetSymbolValue(SymMgr, *I));
Ted Kremenekff6e3c52008-01-29 00:43:03 +0000164
Ted Kremenekcb48b9c2008-01-29 00:33:40 +0000165 return St;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000166 }
Ted Kremenek3b4f6702008-01-30 23:24:39 +0000167
168 bool isUninitControlFlow(const NodeTy* N) const {
169 return N->isSink() && UninitBranches.count(const_cast<NodeTy*>(N)) != 0;
170 }
Ted Kremenekd131c4f2008-02-07 05:48:01 +0000171
172 bool isImplicitNullDeref(const NodeTy* N) const {
173 return N->isSink() && ImplicitNullDeref.count(const_cast<NodeTy*>(N)) != 0;
174 }
Ted Kremenekd27f8162008-01-15 23:55:06 +0000175
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000176 /// ProcessStmt - Called by GREngine. Used to generate new successor
177 /// nodes by processing the 'effects' of a block-level statement.
Ted Kremenek7d7fe6d2008-01-29 22:56:11 +0000178 void ProcessStmt(Stmt* S, StmtNodeBuilder& builder);
179
180 /// ProcessBranch - Called by GREngine. Used to generate successor
181 /// nodes by processing the 'effects' of a branch condition.
Ted Kremenekf233d482008-02-05 00:26:40 +0000182 void ProcessBranch(Expr* Condition, Stmt* Term, BranchNodeBuilder& builder);
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000183
184 /// RemoveDeadBindings - Return a new state that is the same as 'M' except
185 /// that all subexpression mappings are removed and that any
186 /// block-level expressions that are not live at 'S' also have their
187 /// mappings removed.
188 StateTy RemoveDeadBindings(Stmt* S, StateTy M);
189
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000190 StateTy SetValue(StateTy St, Stmt* S, const RValue& V);
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000191
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000192 StateTy SetValue(StateTy St, const Stmt* S, const RValue& V) {
Ted Kremenek9de04c42008-01-24 20:55:43 +0000193 return SetValue(St, const_cast<Stmt*>(S), V);
194 }
195
Ted Kremenekcba2e432008-02-05 19:35:18 +0000196 /// SetValue - This version of SetValue is used to batch process a set
197 /// of different possible RValues and return a set of different states.
198 const StateTy::BufferTy& SetValue(StateTy St, Stmt* S,
199 const RValue::BufferTy& V,
200 StateTy::BufferTy& RetBuf);
201
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000202 StateTy SetValue(StateTy St, const LValue& LV, const RValue& V);
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000203
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000204 inline RValue GetValue(const StateTy& St, Stmt* S) {
205 return StateMgr.GetValue(St, S);
206 }
Ted Kremenekf233d482008-02-05 00:26:40 +0000207
208 inline RValue GetValue(const StateTy& St, Stmt* S, bool& hasVal) {
209 return StateMgr.GetValue(St, S, &hasVal);
210 }
211
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000212 inline RValue GetValue(const StateTy& St, const Stmt* S) {
Ted Kremenek9de04c42008-01-24 20:55:43 +0000213 return GetValue(St, const_cast<Stmt*>(S));
214 }
215
Ted Kremenekd131c4f2008-02-07 05:48:01 +0000216 inline RValue GetValue(const StateTy& St, const LValue& LV,
217 QualType* T = NULL) {
218
219 return StateMgr.GetValue(St, LV, T);
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000220 }
221
222 inline LValue GetLValue(const StateTy& St, Stmt* S) {
223 return StateMgr.GetLValue(St, S);
224 }
Ted Kremenekf233d482008-02-05 00:26:40 +0000225
226 inline NonLValue GetRValueConstant(uint64_t X, Expr* E) {
227 return NonLValue::GetValue(ValMgr, X, E->getType(), E->getLocStart());
228 }
Ted Kremenekb38911f2008-01-30 23:03:39 +0000229
230 /// Assume - Create new state by assuming that a given expression
231 /// is true or false.
232 inline StateTy Assume(StateTy St, RValue Cond, bool Assumption,
233 bool& isFeasible) {
234 if (isa<LValue>(Cond))
235 return Assume(St, cast<LValue>(Cond), Assumption, isFeasible);
236 else
237 return Assume(St, cast<NonLValue>(Cond), Assumption, isFeasible);
238 }
239
240 StateTy Assume(StateTy St, LValue Cond, bool Assumption, bool& isFeasible);
241 StateTy Assume(StateTy St, NonLValue Cond, bool Assumption, bool& isFeasible);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000242
Ted Kremenek862d5bb2008-02-06 00:54:14 +0000243 StateTy AssumeSymNE(StateTy St, SymbolID sym, const llvm::APSInt& V,
244 bool& isFeasible);
245
246 StateTy AssumeSymEQ(StateTy St, SymbolID sym, const llvm::APSInt& V,
247 bool& isFeasible);
248
Ted Kremenek08b66252008-02-06 04:31:33 +0000249 StateTy AssumeSymInt(StateTy St, bool Assumption, const SymIntConstraint& C,
250 bool& isFeasible);
251
Ted Kremenekd131c4f2008-02-07 05:48:01 +0000252 NodeTy* Nodify(NodeSet& Dst, Stmt* S, NodeTy* Pred, StateTy St);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000253
Ted Kremenekcba2e432008-02-05 19:35:18 +0000254 /// Nodify - This version of Nodify is used to batch process a set of states.
255 /// The states are not guaranteed to be unique.
256 void Nodify(NodeSet& Dst, Stmt* S, NodeTy* Pred, const StateTy::BufferTy& SB);
257
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000258 /// Visit - Transfer function logic for all statements. Dispatches to
259 /// other functions that handle specific kinds of statements.
260 void Visit(Stmt* S, NodeTy* Pred, NodeSet& Dst);
Ted Kremenek874d63f2008-01-24 02:02:54 +0000261
262 /// VisitCast - Transfer function logic for all casts (implicit and explicit).
263 void VisitCast(Expr* CastE, Expr* E, NodeTy* Pred, NodeSet& Dst);
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000264
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000265 /// VisitUnaryOperator - Transfer function logic for unary operators.
266 void VisitUnaryOperator(UnaryOperator* B, NodeTy* Pred, NodeSet& Dst);
267
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000268 /// VisitBinaryOperator - Transfer function logic for binary operators.
Ted Kremenek9de04c42008-01-24 20:55:43 +0000269 void VisitBinaryOperator(BinaryOperator* B, NodeTy* Pred, NodeSet& Dst);
270
Ted Kremenek5b6dc2d2008-02-07 01:08:27 +0000271 void VisitAssignmentLHS(Expr* E, NodeTy* Pred, NodeSet& Dst);
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000272
273 /// VisitDeclRefExpr - Transfer function logic for DeclRefExprs.
274 void VisitDeclRefExpr(DeclRefExpr* DR, NodeTy* Pred, NodeSet& Dst);
275
Ted Kremenek9de04c42008-01-24 20:55:43 +0000276 /// VisitDeclStmt - Transfer function logic for DeclStmts.
Ted Kremenekf233d482008-02-05 00:26:40 +0000277 void VisitDeclStmt(DeclStmt* DS, NodeTy* Pred, NodeSet& Dst);
278
279 /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
280 void VisitGuardedExpr(Stmt* S, Stmt* LHS, Stmt* RHS,
281 NodeTy* Pred, NodeSet& Dst);
282
283 /// VisitLogicalExpr - Transfer function logic for '&&', '||'
284 void VisitLogicalExpr(BinaryOperator* B, NodeTy* Pred, NodeSet& Dst);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000285};
286} // end anonymous namespace
287
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000288
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000289GRConstants::StateTy
290GRConstants::SetValue(StateTy St, Stmt* S, const RValue& V) {
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000291
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000292 if (!StateCleaned) {
293 St = RemoveDeadBindings(CurrentStmt, St);
294 StateCleaned = true;
295 }
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000296
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000297 bool isBlkExpr = false;
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000298
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000299 if (S == CurrentStmt) {
300 isBlkExpr = getCFG().isBlkExpr(S);
301
302 if (!isBlkExpr)
303 return St;
304 }
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000305
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000306 return StateMgr.SetValue(St, S, isBlkExpr, V);
307}
308
Ted Kremenekcba2e432008-02-05 19:35:18 +0000309const GRConstants::StateTy::BufferTy&
310GRConstants::SetValue(StateTy St, Stmt* S, const RValue::BufferTy& RB,
311 StateTy::BufferTy& RetBuf) {
312
313 assert (RetBuf.empty());
314
315 for (RValue::BufferTy::const_iterator I=RB.begin(), E=RB.end(); I!=E; ++I)
316 RetBuf.push_back(SetValue(St, S, *I));
317
318 return RetBuf;
319}
320
Ted Kremeneke070a1d2008-02-04 21:59:01 +0000321GRConstants::StateTy
322GRConstants::SetValue(StateTy St, const LValue& LV, const RValue& V) {
323
324 if (!LV.isValid())
325 return St;
326
327 if (!StateCleaned) {
328 St = RemoveDeadBindings(CurrentStmt, St);
329 StateCleaned = true;
330 }
331
332 return StateMgr.SetValue(St, LV, V);
333}
334
Ted Kremenekf233d482008-02-05 00:26:40 +0000335void GRConstants::ProcessBranch(Expr* Condition, Stmt* Term,
Ted Kremenek71c29bd2008-01-29 23:32:35 +0000336 BranchNodeBuilder& builder) {
Ted Kremenekb38911f2008-01-30 23:03:39 +0000337
338 StateTy PrevState = builder.getState();
Ted Kremenek71c29bd2008-01-29 23:32:35 +0000339
Ted Kremenekb38911f2008-01-30 23:03:39 +0000340 // Remove old bindings for subexpressions.
Ted Kremenekb80cbfe2008-02-05 18:19:15 +0000341 for (StateTy::vb_iterator I=PrevState.begin(), E=PrevState.end(); I!=E; ++I)
Ted Kremenekb38911f2008-01-30 23:03:39 +0000342 if (I.getKey().isSubExpr())
343 PrevState = StateMgr.Remove(PrevState, I.getKey());
Ted Kremenek71c29bd2008-01-29 23:32:35 +0000344
Ted Kremenekf233d482008-02-05 00:26:40 +0000345 // Remove terminator-specific bindings.
346 switch (Term->getStmtClass()) {
347 default: break;
348
349 case Stmt::BinaryOperatorClass: { // '&&', '||'
350 BinaryOperator* B = cast<BinaryOperator>(Term);
351 // FIXME: Liveness analysis should probably remove these automatically.
352 // Verify later when we converge to an 'optimization' stage.
353 PrevState = StateMgr.Remove(PrevState, B->getRHS());
354 break;
355 }
356
357 case Stmt::ConditionalOperatorClass: { // '?' operator
358 ConditionalOperator* C = cast<ConditionalOperator>(Term);
359 // FIXME: Liveness analysis should probably remove these automatically.
360 // Verify later when we converge to an 'optimization' stage.
361 if (Expr* L = C->getLHS()) PrevState = StateMgr.Remove(PrevState, L);
362 PrevState = StateMgr.Remove(PrevState, C->getRHS());
363 break;
364 }
365
366 case Stmt::ChooseExprClass: { // __builtin_choose_expr
367 ChooseExpr* C = cast<ChooseExpr>(Term);
368 // FIXME: Liveness analysis should probably remove these automatically.
369 // Verify later when we converge to an 'optimization' stage.
370 PrevState = StateMgr.Remove(PrevState, C->getRHS());
371 PrevState = StateMgr.Remove(PrevState, C->getRHS());
372 break;
373 }
374 }
375
Ted Kremenekb38911f2008-01-30 23:03:39 +0000376 RValue V = GetValue(PrevState, Condition);
377
378 switch (V.getBaseKind()) {
379 default:
380 break;
381
382 case RValue::InvalidKind:
383 builder.generateNode(PrevState, true);
384 builder.generateNode(PrevState, false);
385 return;
386
387 case RValue::UninitializedKind: {
388 NodeTy* N = builder.generateNode(PrevState, true);
389
390 if (N) {
391 N->markAsSink();
392 UninitBranches.insert(N);
393 }
394
395 builder.markInfeasible(false);
396 return;
397 }
398 }
399
400 // Process the true branch.
401 bool isFeasible = true;
Ted Kremenekf233d482008-02-05 00:26:40 +0000402
Ted Kremenekb38911f2008-01-30 23:03:39 +0000403 StateTy St = Assume(PrevState, V, true, isFeasible);
404
Ted Kremenekf233d482008-02-05 00:26:40 +0000405 if (isFeasible)
406 builder.generateNode(St, true);
Ted Kremenekb38911f2008-01-30 23:03:39 +0000407 else {
408 builder.markInfeasible(true);
409 isFeasible = true;
410 }
411
412 // Process the false branch.
413 St = Assume(PrevState, V, false, isFeasible);
414
Ted Kremenekf233d482008-02-05 00:26:40 +0000415 if (isFeasible)
416 builder.generateNode(St, false);
417 else
418 builder.markInfeasible(false);
Ted Kremenek71c29bd2008-01-29 23:32:35 +0000419}
420
Ted Kremenekf233d482008-02-05 00:26:40 +0000421
422void GRConstants::VisitLogicalExpr(BinaryOperator* B, NodeTy* Pred,
423 NodeSet& Dst) {
424
425 bool hasR2;
426 StateTy PrevState = Pred->getState();
427
428 RValue R1 = GetValue(PrevState, B->getLHS());
429 RValue R2 = GetValue(PrevState, B->getRHS(), hasR2);
430
431 if (isa<InvalidValue>(R1) &&
432 (isa<InvalidValue>(R2) ||
433 isa<UninitializedValue>(R2))) {
434
435 Nodify(Dst, B, Pred, SetValue(PrevState, B, R2));
436 return;
437 }
438 else if (isa<UninitializedValue>(R1)) {
439 Nodify(Dst, B, Pred, SetValue(PrevState, B, R1));
440 return;
441 }
442
443 // R1 is an expression that can evaluate to either 'true' or 'false'.
444 if (B->getOpcode() == BinaryOperator::LAnd) {
445 // hasR2 == 'false' means that LHS evaluated to 'false' and that
446 // we short-circuited, leading to a value of '0' for the '&&' expression.
447 if (hasR2 == false) {
448 Nodify(Dst, B, Pred, SetValue(PrevState, B, GetRValueConstant(0U, B)));
449 return;
450 }
451 }
452 else {
453 assert (B->getOpcode() == BinaryOperator::LOr);
454 // hasR2 == 'false' means that the LHS evaluate to 'true' and that
455 // we short-circuited, leading to a value of '1' for the '||' expression.
456 if (hasR2 == false) {
457 Nodify(Dst, B, Pred, SetValue(PrevState, B, GetRValueConstant(1U, B)));
458 return;
459 }
460 }
461
462 // If we reach here we did not short-circuit. Assume R2 == true and
463 // R2 == false.
464
465 bool isFeasible;
466 StateTy St = Assume(PrevState, R2, true, isFeasible);
467
468 if (isFeasible)
469 Nodify(Dst, B, Pred, SetValue(PrevState, B, GetRValueConstant(1U, B)));
470
471 St = Assume(PrevState, R2, false, isFeasible);
472
473 if (isFeasible)
474 Nodify(Dst, B, Pred, SetValue(PrevState, B, GetRValueConstant(0U, B)));
475}
476
477
478
Ted Kremenek7d7fe6d2008-01-29 22:56:11 +0000479void GRConstants::ProcessStmt(Stmt* S, StmtNodeBuilder& builder) {
Ted Kremenekd27f8162008-01-15 23:55:06 +0000480 Builder = &builder;
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000481
482 StmtEntryNode = builder.getLastNode();
483 CurrentStmt = S;
484 NodeSet Dst;
485 StateCleaned = false;
486
487 Visit(S, StmtEntryNode, Dst);
488
489 // If no nodes were generated, generate a new node that has all the
490 // dead mappings removed.
491 if (Dst.size() == 1 && *Dst.begin() == StmtEntryNode) {
492 StateTy St = RemoveDeadBindings(S, StmtEntryNode->getState());
493 builder.generateNode(S, St, StmtEntryNode);
494 }
Ted Kremenekf84469b2008-01-18 00:41:32 +0000495
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000496 CurrentStmt = NULL;
497 StmtEntryNode = NULL;
498 Builder = NULL;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000499}
500
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000501GRConstants::StateTy GRConstants::RemoveDeadBindings(Stmt* Loc, StateTy M) {
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000502
503 // This code essentially performs a "mark-and-sweep" of the VariableBindings.
504 // The roots are any Block-level exprs and Decls that our liveness algorithm
505 // tells us are live. We then see what Decls they may reference, and keep
506 // those around. This code more than likely can be made faster, and the
507 // frequency of which this method is called should be experimented with
508 // for optimum performance.
Ted Kremenekf84469b2008-01-18 00:41:32 +0000509
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000510 llvm::SmallVector<ValueDecl*, 10> WList;
Ted Kremenekf84469b2008-01-18 00:41:32 +0000511
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000512 for (StateTy::vb_iterator I = M.begin(), E = M.end();
513 I!=E && !I.getKey().isSymbol(); ++I) {
514
515 // Remove old bindings for subexpressions.
516 if (I.getKey().isSubExpr()) {
Ted Kremenek65cac132008-01-29 05:25:31 +0000517 M = StateMgr.Remove(M, I.getKey());
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000518 continue;
Ted Kremenek65cac132008-01-29 05:25:31 +0000519 }
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000520
521 if (I.getKey().isBlkExpr()) {
522 if (Liveness.isLive(Loc, cast<Stmt>(I.getKey()))) {
523 if (isa<lval::DeclVal>(I.getData())) {
524 lval::DeclVal LV = cast<lval::DeclVal>(I.getData());
525 WList.push_back(LV.getDecl());
526 }
527 }
528 else
529 M = StateMgr.Remove(M, I.getKey());
530
531 continue;
Ted Kremenek65cac132008-01-29 05:25:31 +0000532 }
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000533
534 assert (I.getKey().isDecl());
535
536 if (VarDecl* V = dyn_cast<VarDecl>(cast<ValueDecl>(I.getKey())))
537 if (Liveness.isLive(Loc, V))
538 WList.push_back(V);
Ted Kremenek65cac132008-01-29 05:25:31 +0000539 }
Ted Kremenek565256e2008-01-24 22:44:24 +0000540
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000541 llvm::SmallPtrSet<ValueDecl*, 10> Marked;
542
543 while (!WList.empty()) {
544 ValueDecl* V = WList.back();
545 WList.pop_back();
546
547 if (Marked.count(V))
548 continue;
549
550 Marked.insert(V);
551
552 if (V->getType()->isPointerType()) {
553 const LValue& LV = cast<LValue>(GetValue(M, lval::DeclVal(V)));
554
555 if (!isa<lval::DeclVal>(LV))
556 continue;
557
558 const lval::DeclVal& LVD = cast<lval::DeclVal>(LV);
559 WList.push_back(LVD.getDecl());
560 }
561 }
562
563 for (StateTy::vb_iterator I = M.begin(), E = M.end(); I!=E ; ++I)
564 if (I.getKey().isDecl())
565 if (VarDecl* V = dyn_cast<VarDecl>(cast<ValueDecl>(I.getKey())))
566 if (!Marked.count(V))
567 M = StateMgr.Remove(M, V);
568
Ted Kremeneke00fe3f2008-01-17 00:52:48 +0000569 return M;
Ted Kremeneke00fe3f2008-01-17 00:52:48 +0000570}
571
Ted Kremenekd131c4f2008-02-07 05:48:01 +0000572GRConstants::NodeTy*
573GRConstants::Nodify(NodeSet& Dst, Stmt* S, NodeTy* Pred, StateTy St) {
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000574
575 // If the state hasn't changed, don't generate a new node.
576 if (St == Pred->getState())
Ted Kremenekd131c4f2008-02-07 05:48:01 +0000577 return NULL;
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000578
Ted Kremenekd131c4f2008-02-07 05:48:01 +0000579 NodeTy* N = Builder->generateNode(S, St, Pred);
580 Dst.Add(N);
581 return N;
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000582}
Ted Kremenekd27f8162008-01-15 23:55:06 +0000583
Ted Kremenekcba2e432008-02-05 19:35:18 +0000584void GRConstants::Nodify(NodeSet& Dst, Stmt* S, NodeTy* Pred,
585 const StateTy::BufferTy& SB) {
586
587 for (StateTy::BufferTy::const_iterator I=SB.begin(), E=SB.end(); I!=E; ++I)
588 Nodify(Dst, S, Pred, *I);
589}
590
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000591void GRConstants::VisitDeclRefExpr(DeclRefExpr* D, NodeTy* Pred, NodeSet& Dst) {
592 if (D != CurrentStmt) {
593 Dst.Add(Pred); // No-op. Simply propagate the current state unchanged.
594 return;
595 }
596
597 // If we are here, we are loading the value of the decl and binding
598 // it to the block-level expression.
599
600 StateTy St = Pred->getState();
601
602 Nodify(Dst, D, Pred,
603 SetValue(St, D, GetValue(St, lval::DeclVal(D->getDecl()))));
604}
605
Ted Kremenekcba2e432008-02-05 19:35:18 +0000606void GRConstants::VisitCast(Expr* CastE, Expr* E, NodeTy* Pred, NodeSet& Dst) {
Ted Kremenek874d63f2008-01-24 02:02:54 +0000607
608 QualType T = CastE->getType();
609
610 // Check for redundant casts.
611 if (E->getType() == T) {
612 Dst.Add(Pred);
613 return;
614 }
615
616 NodeSet S1;
617 Visit(E, Pred, S1);
618
619 for (NodeSet::iterator I1=S1.begin(), E1=S1.end(); I1 != E1; ++I1) {
620 NodeTy* N = *I1;
621 StateTy St = N->getState();
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000622 const RValue& V = GetValue(St, E);
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000623 Nodify(Dst, CastE, N, SetValue(St, CastE, V.EvalCast(ValMgr, CastE)));
Ted Kremenek874d63f2008-01-24 02:02:54 +0000624 }
Ted Kremenek9de04c42008-01-24 20:55:43 +0000625}
626
627void GRConstants::VisitDeclStmt(DeclStmt* DS, GRConstants::NodeTy* Pred,
628 GRConstants::NodeSet& Dst) {
629
630 StateTy St = Pred->getState();
631
632 for (const ScopedDecl* D = DS->getDecl(); D; D = D->getNextDeclarator())
Ted Kremenek403c1812008-01-28 22:51:57 +0000633 if (const VarDecl* VD = dyn_cast<VarDecl>(D)) {
634 const Expr* E = VD->getInit();
Ted Kremenek329f8542008-02-05 21:52:21 +0000635 St = SetValue(St, lval::DeclVal(VD),
Ted Kremenek403c1812008-01-28 22:51:57 +0000636 E ? GetValue(St, E) : UninitializedValue());
637 }
Ted Kremenek9de04c42008-01-24 20:55:43 +0000638
639 Nodify(Dst, DS, Pred, St);
640
641 if (Dst.empty())
642 Dst.Add(Pred);
643}
Ted Kremenek874d63f2008-01-24 02:02:54 +0000644
Ted Kremenekf233d482008-02-05 00:26:40 +0000645
646void GRConstants::VisitGuardedExpr(Stmt* S, Stmt* LHS, Stmt* RHS,
647 NodeTy* Pred, NodeSet& Dst) {
648
649 StateTy St = Pred->getState();
650
651 RValue R = GetValue(St, LHS);
652 if (isa<InvalidValue>(R)) R = GetValue(St, RHS);
653
654 Nodify(Dst, S, Pred, SetValue(St, S, R));
655}
656
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000657void GRConstants::VisitUnaryOperator(UnaryOperator* U,
658 GRConstants::NodeTy* Pred,
659 GRConstants::NodeSet& Dst) {
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000660
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000661 NodeSet S1;
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000662 UnaryOperator::Opcode Op = U->getOpcode();
663
664 // FIXME: This is a hack so that for '*' and '&' we don't recurse
665 // on visiting the subexpression if it is a DeclRefExpr. We should
666 // probably just handle AddrOf and Deref in their own methods to make
667 // this cleaner.
668 if ((Op == UnaryOperator::Deref || Op == UnaryOperator::AddrOf) &&
669 isa<DeclRefExpr>(U->getSubExpr()))
670 S1.Add(Pred);
671 else
672 Visit(U->getSubExpr(), Pred, S1);
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000673
674 for (NodeSet::iterator I1=S1.begin(), E1=S1.end(); I1 != E1; ++I1) {
675 NodeTy* N1 = *I1;
676 StateTy St = N1->getState();
677
678 switch (U->getOpcode()) {
679 case UnaryOperator::PostInc: {
680 const LValue& L1 = GetLValue(St, U->getSubExpr());
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000681 NonLValue R1 = cast<NonLValue>(GetValue(St, L1));
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000682
683 NonLValue Result = R1.EvalBinaryOp(ValMgr, BinaryOperator::Add,
684 GetRValueConstant(1U, U));
685
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000686 Nodify(Dst, U, N1, SetValue(SetValue(St, U, R1), L1, Result));
687 break;
688 }
689
690 case UnaryOperator::PostDec: {
691 const LValue& L1 = GetLValue(St, U->getSubExpr());
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000692 NonLValue R1 = cast<NonLValue>(GetValue(St, L1));
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000693
694 NonLValue Result = R1.EvalBinaryOp(ValMgr, BinaryOperator::Sub,
695 GetRValueConstant(1U, U));
696
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000697 Nodify(Dst, U, N1, SetValue(SetValue(St, U, R1), L1, Result));
698 break;
699 }
700
701 case UnaryOperator::PreInc: {
702 const LValue& L1 = GetLValue(St, U->getSubExpr());
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000703 NonLValue R1 = cast<NonLValue>(GetValue(St, L1));
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000704
705 NonLValue Result = R1.EvalBinaryOp(ValMgr, BinaryOperator::Add,
706 GetRValueConstant(1U, U));
707
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000708 Nodify(Dst, U, N1, SetValue(SetValue(St, U, Result), L1, Result));
709 break;
710 }
711
712 case UnaryOperator::PreDec: {
713 const LValue& L1 = GetLValue(St, U->getSubExpr());
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000714 NonLValue R1 = cast<NonLValue>(GetValue(St, L1));
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000715
716 NonLValue Result = R1.EvalBinaryOp(ValMgr, BinaryOperator::Sub,
717 GetRValueConstant(1U, U));
718
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000719 Nodify(Dst, U, N1, SetValue(SetValue(St, U, Result), L1, Result));
720 break;
721 }
722
Ted Kremenekdacbb4f2008-01-24 08:20:02 +0000723 case UnaryOperator::Minus: {
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000724 const NonLValue& R1 = cast<NonLValue>(GetValue(St, U->getSubExpr()));
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000725 Nodify(Dst, U, N1, SetValue(St, U, R1.EvalMinus(ValMgr, U)));
Ted Kremenekdacbb4f2008-01-24 08:20:02 +0000726 break;
727 }
728
Ted Kremenekc5d3b4c2008-02-04 16:58:30 +0000729 case UnaryOperator::Not: {
730 const NonLValue& R1 = cast<NonLValue>(GetValue(St, U->getSubExpr()));
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000731 Nodify(Dst, U, N1, SetValue(St, U, R1.EvalComplement(ValMgr)));
Ted Kremenekc5d3b4c2008-02-04 16:58:30 +0000732 break;
733 }
734
Ted Kremenekc60f0f72008-02-06 17:56:00 +0000735 case UnaryOperator::LNot: {
736 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
737 //
738 // Note: technically we do "E == 0", but this is the same in the
739 // transfer functions as "0 == E".
740
741 RValue V1 = GetValue(St, U->getSubExpr());
742
743 if (isa<LValue>(V1)) {
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000744 const LValue& L1 = cast<LValue>(V1);
745 lval::ConcreteInt V2(ValMgr.getZeroWithPtrWidth());
746 Nodify(Dst, U, N1,
747 SetValue(St, U, L1.EvalBinaryOp(ValMgr, BinaryOperator::EQ,
748 V2)));
Ted Kremenekc60f0f72008-02-06 17:56:00 +0000749 }
750 else {
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000751 const NonLValue& R1 = cast<NonLValue>(V1);
Ted Kremenekc60f0f72008-02-06 17:56:00 +0000752 nonlval::ConcreteInt V2(ValMgr.getZeroWithPtrWidth());
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000753 Nodify(Dst, U, N1,
754 SetValue(St, U, R1.EvalBinaryOp(ValMgr, BinaryOperator::EQ,
755 V2)));
Ted Kremenekc60f0f72008-02-06 17:56:00 +0000756 }
757
758 break;
759 }
760
Ted Kremenek64924852008-01-31 02:35:41 +0000761 case UnaryOperator::AddrOf: {
762 const LValue& L1 = GetLValue(St, U->getSubExpr());
763 Nodify(Dst, U, N1, SetValue(St, U, L1));
764 break;
765 }
766
767 case UnaryOperator::Deref: {
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000768 // FIXME: Stop when dereferencing an uninitialized value.
769 // FIXME: Bifurcate when dereferencing a symbolic with no constraints?
770
771 const RValue& V = GetValue(St, U->getSubExpr());
772 const LValue& L1 = cast<LValue>(V);
773
Ted Kremenekd131c4f2008-02-07 05:48:01 +0000774 // After a dereference, one of two possible situations arise:
775 // (1) A crash, because the pointer was NULL.
776 // (2) The pointer is not NULL, and the dereference works.
777 //
778 // We add these assumptions.
779
780 bool isFeasible;
781
782 // "Assume" that the pointer is NULL.
783 StateTy StNull = Assume(St, L1, false, isFeasible);
784
785 if (isFeasible) {
786 NodeTy* NullNode = Nodify(Dst, U, N1, StNull);
787 if (NullNode) {
788 NullNode->markAsSink();
789 ImplicitNullDeref.insert(NullNode);
790 }
791 }
792
793 // "Assume" that the pointer is Not-NULL.
794 StateTy StNotNull = Assume(St, L1, true, isFeasible);
795
796 if (isFeasible) {
797 QualType T = U->getType();
798 Nodify(Dst, U, N1, SetValue(StNotNull, U,
799 GetValue(StNotNull, L1, &T)));
800 }
801
Ted Kremenek64924852008-01-31 02:35:41 +0000802 break;
803 }
804
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000805 default: ;
806 assert (false && "Not implemented.");
807 }
808 }
809}
810
Ted Kremenek5b6dc2d2008-02-07 01:08:27 +0000811void GRConstants::VisitAssignmentLHS(Expr* E, GRConstants::NodeTy* Pred,
812 GRConstants::NodeSet& Dst) {
813
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000814 if (isa<DeclRefExpr>(E)) {
815 Dst.Add(Pred);
Ted Kremenek5b6dc2d2008-02-07 01:08:27 +0000816 return;
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000817 }
Ted Kremenek5b6dc2d2008-02-07 01:08:27 +0000818
819 if (UnaryOperator* U = dyn_cast<UnaryOperator>(E)) {
820 if (U->getOpcode() == UnaryOperator::Deref) {
821 Visit(U->getSubExpr(), Pred, Dst);
822 return;
823 }
824 }
825
826 Visit(E, Pred, Dst);
827}
828
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000829void GRConstants::VisitBinaryOperator(BinaryOperator* B,
830 GRConstants::NodeTy* Pred,
831 GRConstants::NodeSet& Dst) {
832 NodeSet S1;
Ted Kremenek5b6dc2d2008-02-07 01:08:27 +0000833
834 if (B->isAssignmentOp())
835 VisitAssignmentLHS(B->getLHS(), Pred, S1);
836 else
837 Visit(B->getLHS(), Pred, S1);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000838
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000839 for (NodeSet::iterator I1=S1.begin(), E1=S1.end(); I1 != E1; ++I1) {
840 NodeTy* N1 = *I1;
Ted Kremeneke00fe3f2008-01-17 00:52:48 +0000841
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000842 // When getting the value for the LHS, check if we are in an assignment.
843 // In such cases, we want to (initially) treat the LHS as an LValue,
844 // so we use GetLValue instead of GetValue so that DeclRefExpr's are
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000845 // evaluated to LValueDecl's instead of to an NonLValue.
846 const RValue& V1 =
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000847 B->isAssignmentOp() ? GetLValue(N1->getState(), B->getLHS())
848 : GetValue(N1->getState(), B->getLHS());
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000849
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000850 NodeSet S2;
851 Visit(B->getRHS(), N1, S2);
852
853 for (NodeSet::iterator I2=S2.begin(), E2=S2.end(); I2 != E2; ++I2) {
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000854
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000855 NodeTy* N2 = *I2;
856 StateTy St = N2->getState();
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000857 const RValue& V2 = GetValue(St, B->getRHS());
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000858
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000859 BinaryOperator::Opcode Op = B->getOpcode();
860
861 if (Op <= BinaryOperator::Or) {
862
Ted Kremenek5b6dc2d2008-02-07 01:08:27 +0000863 if (isa<InvalidValue>(V1) || isa<UninitializedValue>(V1)) {
864 Nodify(Dst, B, N2, SetValue(St, B, V1));
865 continue;
866 }
867
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000868 if (isa<LValue>(V1)) {
869 // FIXME: Add support for RHS being a non-lvalue.
870 const LValue& L1 = cast<LValue>(V1);
871 const LValue& L2 = cast<LValue>(V2);
Ted Kremenek687af802008-01-29 19:43:15 +0000872
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000873 Nodify(Dst, B, N2, SetValue(St, B, L1.EvalBinaryOp(ValMgr, Op, L2)));
874 }
875 else {
Ted Kremenekbd03f1d2008-01-28 22:09:13 +0000876 const NonLValue& R1 = cast<NonLValue>(V1);
877 const NonLValue& R2 = cast<NonLValue>(V2);
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000878
879 Nodify(Dst, B, N2, SetValue(St, B, R1.EvalBinaryOp(ValMgr, Op, R2)));
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000880 }
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000881
882 continue;
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000883
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000884 }
885
886 switch (Op) {
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000887 case BinaryOperator::Assign: {
888 const LValue& L1 = cast<LValue>(V1);
Ted Kremenek3434b082008-02-06 04:41:14 +0000889 Nodify(Dst, B, N2, SetValue(SetValue(St, B, V2), L1, V2));
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000890 break;
891 }
892
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000893 default: { // Compound assignment operators.
Ted Kremenek687af802008-01-29 19:43:15 +0000894
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000895 assert (B->isCompoundAssignmentOp());
896
897 const LValue& L1 = cast<LValue>(V1);
898 RValue Result = cast<NonLValue>(InvalidValue());
899
900 Op = (BinaryOperator::Opcode)
901 (((unsigned) Op) - ((unsigned) BinaryOperator::MulAssign));
902
903 if (isa<LValue>(V2)) {
904 // FIXME: Add support for Non-LValues on RHS.
Ted Kremenek687af802008-01-29 19:43:15 +0000905 const LValue& L2 = cast<LValue>(V2);
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000906 Result = L1.EvalBinaryOp(ValMgr, Op, L2);
Ted Kremenek687af802008-01-29 19:43:15 +0000907 }
908 else {
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000909 const NonLValue& R1 = cast<NonLValue>(GetValue(N1->getState(), L1));
Ted Kremenek687af802008-01-29 19:43:15 +0000910 const NonLValue& R2 = cast<NonLValue>(V2);
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000911 Result = R1.EvalBinaryOp(ValMgr, Op, R2);
Ted Kremenek687af802008-01-29 19:43:15 +0000912 }
913
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000914 Nodify(Dst, B, N2, SetValue(SetValue(St, B, Result), L1, Result));
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000915 break;
Ted Kremenekcf78b6a2008-02-06 22:50:25 +0000916 }
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000917 }
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000918 }
Ted Kremenekd27f8162008-01-15 23:55:06 +0000919 }
Ted Kremenekd27f8162008-01-15 23:55:06 +0000920}
Ted Kremenekee985462008-01-16 18:18:48 +0000921
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000922
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000923void GRConstants::Visit(Stmt* S, GRConstants::NodeTy* Pred,
924 GRConstants::NodeSet& Dst) {
925
926 // FIXME: add metadata to the CFG so that we can disable
927 // this check when we KNOW that there is no block-level subexpression.
928 // The motivation is that this check requires a hashtable lookup.
929
930 if (S != CurrentStmt && getCFG().isBlkExpr(S)) {
931 Dst.Add(Pred);
932 return;
933 }
934
935 switch (S->getStmtClass()) {
936 case Stmt::BinaryOperatorClass:
Ted Kremenekf233d482008-02-05 00:26:40 +0000937
938 if (cast<BinaryOperator>(S)->isLogicalOp()) {
939 VisitLogicalExpr(cast<BinaryOperator>(S), Pred, Dst);
940 break;
941 }
942
943 // Fall-through.
944
Ted Kremenekb4ae33f2008-01-23 23:38:00 +0000945 case Stmt::CompoundAssignOperatorClass:
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000946 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
947 break;
948
Ted Kremenek7b8009a2008-01-24 02:28:56 +0000949 case Stmt::UnaryOperatorClass:
950 VisitUnaryOperator(cast<UnaryOperator>(S), Pred, Dst);
951 break;
952
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000953 case Stmt::ParenExprClass:
954 Visit(cast<ParenExpr>(S)->getSubExpr(), Pred, Dst);
955 break;
Ted Kremenek3271f8d2008-02-07 04:16:04 +0000956
957 case Stmt::DeclRefExprClass:
958 VisitDeclRefExpr(cast<DeclRefExpr>(S), Pred, Dst);
959 break;
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000960
Ted Kremenek874d63f2008-01-24 02:02:54 +0000961 case Stmt::ImplicitCastExprClass: {
962 ImplicitCastExpr* C = cast<ImplicitCastExpr>(S);
963 VisitCast(C, C->getSubExpr(), Pred, Dst);
964 break;
965 }
966
967 case Stmt::CastExprClass: {
968 CastExpr* C = cast<CastExpr>(S);
969 VisitCast(C, C->getSubExpr(), Pred, Dst);
970 break;
971 }
972
Ted Kremenekf233d482008-02-05 00:26:40 +0000973 case Stmt::ConditionalOperatorClass: { // '?' operator
974 ConditionalOperator* C = cast<ConditionalOperator>(S);
975 VisitGuardedExpr(S, C->getLHS(), C->getRHS(), Pred, Dst);
976 break;
977 }
978
979 case Stmt::ChooseExprClass: { // __builtin_choose_expr
980 ChooseExpr* C = cast<ChooseExpr>(S);
981 VisitGuardedExpr(S, C->getLHS(), C->getRHS(), Pred, Dst);
982 break;
983 }
984
Ted Kremenek5b6dc2d2008-02-07 01:08:27 +0000985 case Stmt::ReturnStmtClass:
986 if (Expr* R = cast<ReturnStmt>(S)->getRetValue())
987 Visit(R, Pred, Dst);
988 else
989 Dst.Add(Pred);
990
991 break;
992
Ted Kremenek9de04c42008-01-24 20:55:43 +0000993 case Stmt::DeclStmtClass:
994 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
995 break;
996
Ted Kremenekab2b8c52008-01-23 19:59:44 +0000997 default:
998 Dst.Add(Pred); // No-op. Simply propagate the current state unchanged.
999 break;
Ted Kremenek79649df2008-01-17 18:25:22 +00001000 }
Ted Kremenek1ccd31c2008-01-16 19:42:59 +00001001}
1002
Ted Kremenekee985462008-01-16 18:18:48 +00001003//===----------------------------------------------------------------------===//
Ted Kremenekb38911f2008-01-30 23:03:39 +00001004// "Assume" logic.
1005//===----------------------------------------------------------------------===//
1006
Ted Kremenek862d5bb2008-02-06 00:54:14 +00001007GRConstants::StateTy GRConstants::Assume(StateTy St, LValue Cond,
1008 bool Assumption,
Ted Kremeneka90ccfe2008-01-31 19:34:24 +00001009 bool& isFeasible) {
Ted Kremeneka6e4d212008-02-01 06:36:40 +00001010
1011 switch (Cond.getSubKind()) {
1012 default:
Ted Kremenek862d5bb2008-02-06 00:54:14 +00001013 assert (false && "'Assume' not implemented for this LValue.");
Ted Kremeneka6e4d212008-02-01 06:36:40 +00001014 return St;
1015
Ted Kremenek862d5bb2008-02-06 00:54:14 +00001016 case lval::SymbolValKind:
1017 if (Assumption)
1018 return AssumeSymNE(St, cast<lval::SymbolVal>(Cond).getSymbol(),
1019 ValMgr.getZeroWithPtrWidth(), isFeasible);
1020 else
1021 return AssumeSymEQ(St, cast<lval::SymbolVal>(Cond).getSymbol(),
1022 ValMgr.getZeroWithPtrWidth(), isFeasible);
1023
Ted Kremenek08b66252008-02-06 04:31:33 +00001024
Ted Kremenek329f8542008-02-05 21:52:21 +00001025 case lval::DeclValKind:
Ted Kremeneka6e4d212008-02-01 06:36:40 +00001026 isFeasible = Assumption;
1027 return St;
Ted Kremenek862d5bb2008-02-06 00:54:14 +00001028
Ted Kremenek329f8542008-02-05 21:52:21 +00001029 case lval::ConcreteIntKind: {
1030 bool b = cast<lval::ConcreteInt>(Cond).getValue() != 0;
Ted Kremeneka6e4d212008-02-01 06:36:40 +00001031 isFeasible = b ? Assumption : !Assumption;
1032 return St;
1033 }
1034 }
Ted Kremenekb38911f2008-01-30 23:03:39 +00001035}
1036
Ted Kremenek862d5bb2008-02-06 00:54:14 +00001037GRConstants::StateTy GRConstants::Assume(StateTy St, NonLValue Cond,
1038 bool Assumption,
Ted Kremeneka90ccfe2008-01-31 19:34:24 +00001039 bool& isFeasible) {
Ted Kremenekb38911f2008-01-30 23:03:39 +00001040
1041 switch (Cond.getSubKind()) {
1042 default:
1043 assert (false && "'Assume' not implemented for this NonLValue.");
1044 return St;
1045
Ted Kremenekfeb01f62008-02-06 17:32:17 +00001046
1047 case nonlval::SymbolValKind: {
1048 lval::SymbolVal& SV = cast<lval::SymbolVal>(Cond);
1049 SymbolID sym = SV.getSymbol();
1050
1051 if (Assumption)
1052 return AssumeSymNE(St, sym, ValMgr.getValue(0, SymMgr.getType(sym)),
1053 isFeasible);
1054 else
1055 return AssumeSymEQ(St, sym, ValMgr.getValue(0, SymMgr.getType(sym)),
1056 isFeasible);
1057 }
1058
Ted Kremenek08b66252008-02-06 04:31:33 +00001059 case nonlval::SymIntConstraintValKind:
1060 return
1061 AssumeSymInt(St, Assumption,
1062 cast<nonlval::SymIntConstraintVal>(Cond).getConstraint(),
1063 isFeasible);
1064
Ted Kremenek329f8542008-02-05 21:52:21 +00001065 case nonlval::ConcreteIntKind: {
1066 bool b = cast<nonlval::ConcreteInt>(Cond).getValue() != 0;
Ted Kremenekb38911f2008-01-30 23:03:39 +00001067 isFeasible = b ? Assumption : !Assumption;
1068 return St;
1069 }
1070 }
1071}
1072
Ted Kremenek862d5bb2008-02-06 00:54:14 +00001073GRConstants::StateTy
1074GRConstants::AssumeSymNE(StateTy St, SymbolID sym,
1075 const llvm::APSInt& V, bool& isFeasible) {
1076
1077 // First, determine if sym == X, where X != V.
1078 if (const llvm::APSInt* X = St.getSymVal(sym)) {
1079 isFeasible = *X != V;
1080 return St;
1081 }
1082
1083 // Second, determine if sym != V.
1084 if (St.isNotEqual(sym, V)) {
1085 isFeasible = true;
1086 return St;
1087 }
1088
1089 // If we reach here, sym is not a constant and we don't know if it is != V.
1090 // Make that assumption.
1091
1092 isFeasible = true;
1093 return StateMgr.AddNE(St, sym, V);
1094}
1095
1096GRConstants::StateTy
1097GRConstants::AssumeSymEQ(StateTy St, SymbolID sym,
1098 const llvm::APSInt& V, bool& isFeasible) {
1099
1100 // First, determine if sym == X, where X != V.
1101 if (const llvm::APSInt* X = St.getSymVal(sym)) {
1102 isFeasible = *X == V;
1103 return St;
1104 }
1105
1106 // Second, determine if sym != V.
1107 if (St.isNotEqual(sym, V)) {
1108 isFeasible = false;
1109 return St;
1110 }
1111
1112 // If we reach here, sym is not a constant and we don't know if it is == V.
1113 // Make that assumption.
1114
1115 isFeasible = true;
1116 return StateMgr.AddEQ(St, sym, V);
1117}
Ted Kremenekb38911f2008-01-30 23:03:39 +00001118
Ted Kremenek08b66252008-02-06 04:31:33 +00001119GRConstants::StateTy
1120GRConstants::AssumeSymInt(StateTy St, bool Assumption,
1121 const SymIntConstraint& C, bool& isFeasible) {
1122
1123 switch (C.getOpcode()) {
1124 default:
1125 // No logic yet for other operators.
1126 return St;
1127
1128 case BinaryOperator::EQ:
1129 if (Assumption)
1130 return AssumeSymEQ(St, C.getSymbol(), C.getInt(), isFeasible);
1131 else
1132 return AssumeSymNE(St, C.getSymbol(), C.getInt(), isFeasible);
1133
1134 case BinaryOperator::NE:
1135 if (Assumption)
1136 return AssumeSymNE(St, C.getSymbol(), C.getInt(), isFeasible);
1137 else
1138 return AssumeSymEQ(St, C.getSymbol(), C.getInt(), isFeasible);
1139 }
1140}
1141
Ted Kremenekb38911f2008-01-30 23:03:39 +00001142//===----------------------------------------------------------------------===//
Ted Kremenekee985462008-01-16 18:18:48 +00001143// Driver.
1144//===----------------------------------------------------------------------===//
1145
Ted Kremenekaa66a322008-01-16 21:46:15 +00001146#ifndef NDEBUG
Ted Kremenek3b4f6702008-01-30 23:24:39 +00001147static GRConstants* GraphPrintCheckerState;
1148
Ted Kremenekaa66a322008-01-16 21:46:15 +00001149namespace llvm {
1150template<>
1151struct VISIBILITY_HIDDEN DOTGraphTraits<GRConstants::NodeTy*> :
1152 public DefaultDOTGraphTraits {
Ted Kremenek9ff731d2008-01-24 22:27:20 +00001153
Ted Kremenek9153f732008-02-05 07:17:49 +00001154 static void PrintKindLabel(std::ostream& Out, VarBindKey::Kind kind) {
Ted Kremenek803c9ed2008-01-23 22:30:44 +00001155 switch (kind) {
Ted Kremenek9153f732008-02-05 07:17:49 +00001156 case VarBindKey::IsSubExpr: Out << "Sub-Expressions:\\l"; break;
1157 case VarBindKey::IsDecl: Out << "Variables:\\l"; break;
1158 case VarBindKey::IsBlkExpr: Out << "Block-level Expressions:\\l"; break;
1159 default: assert (false && "Unknown VarBindKey type.");
Ted Kremenek803c9ed2008-01-23 22:30:44 +00001160 }
1161 }
1162
Ted Kremenek9ff731d2008-01-24 22:27:20 +00001163 static void PrintKind(std::ostream& Out, GRConstants::StateTy M,
Ted Kremenek9153f732008-02-05 07:17:49 +00001164 VarBindKey::Kind kind, bool isFirstGroup = false) {
Ted Kremenek9ff731d2008-01-24 22:27:20 +00001165 bool isFirst = true;
1166
Ted Kremenekb80cbfe2008-02-05 18:19:15 +00001167 for (GRConstants::StateTy::vb_iterator I=M.begin(), E=M.end();I!=E;++I) {
Ted Kremenek9ff731d2008-01-24 22:27:20 +00001168 if (I.getKey().getKind() != kind)
1169 continue;
1170
1171 if (isFirst) {
1172 if (!isFirstGroup) Out << "\\l\\l";
1173 PrintKindLabel(Out, kind);
1174 isFirst = false;
1175 }
1176 else
1177 Out << "\\l";
1178
1179 Out << ' ';
1180
1181 if (ValueDecl* V = dyn_cast<ValueDecl>(I.getKey()))
1182 Out << V->getName();
1183 else {
1184 Stmt* E = cast<Stmt>(I.getKey());
1185 Out << " (" << (void*) E << ") ";
1186 E->printPretty(Out);
1187 }
1188
1189 Out << " : ";
1190 I.getData().print(Out);
1191 }
1192 }
1193
Ted Kremeneked4de312008-02-06 03:56:15 +00001194 static void PrintEQ(std::ostream& Out, GRConstants::StateTy St) {
1195 ValueState::ConstantEqTy CE = St.getImpl()->ConstantEq;
1196
1197 if (CE.isEmpty())
1198 return;
1199
1200 Out << "\\l\\|'==' constraints:";
1201
1202 for (ValueState::ConstantEqTy::iterator I=CE.begin(), E=CE.end(); I!=E;++I)
1203 Out << "\\l $" << I.getKey() << " : " << I.getData()->toString();
1204 }
1205
1206 static void PrintNE(std::ostream& Out, GRConstants::StateTy St) {
1207 ValueState::ConstantNotEqTy NE = St.getImpl()->ConstantNotEq;
1208
1209 if (NE.isEmpty())
1210 return;
1211
1212 Out << "\\l\\|'!=' constraints:";
1213
1214 for (ValueState::ConstantNotEqTy::iterator I=NE.begin(), EI=NE.end();
1215 I != EI; ++I){
1216
1217 Out << "\\l $" << I.getKey() << " : ";
1218 bool isFirst = true;
1219
1220 ValueState::IntSetTy::iterator J=I.getData().begin(),
1221 EJ=I.getData().end();
1222 for ( ; J != EJ; ++J) {
1223 if (isFirst) isFirst = false;
1224 else Out << ", ";
1225
1226 Out << (*J)->toString();
1227 }
1228 }
1229 }
1230
Ted Kremenekaa66a322008-01-16 21:46:15 +00001231 static std::string getNodeLabel(const GRConstants::NodeTy* N, void*) {
1232 std::ostringstream Out;
Ted Kremenek803c9ed2008-01-23 22:30:44 +00001233
1234 // Program Location.
Ted Kremenekaa66a322008-01-16 21:46:15 +00001235 ProgramPoint Loc = N->getLocation();
1236
1237 switch (Loc.getKind()) {
1238 case ProgramPoint::BlockEntranceKind:
1239 Out << "Block Entrance: B"
1240 << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
1241 break;
1242
1243 case ProgramPoint::BlockExitKind:
1244 assert (false);
1245 break;
1246
1247 case ProgramPoint::PostStmtKind: {
1248 const PostStmt& L = cast<PostStmt>(Loc);
Ted Kremenek9ff731d2008-01-24 22:27:20 +00001249 Out << L.getStmt()->getStmtClassName() << ':'
1250 << (void*) L.getStmt() << ' ';
1251
Ted Kremenekaa66a322008-01-16 21:46:15 +00001252 L.getStmt()->printPretty(Out);
Ted Kremenekd131c4f2008-02-07 05:48:01 +00001253
1254 if (GraphPrintCheckerState->isImplicitNullDeref(N)) {
1255 Out << "\\|Implicit-Null Dereference.\\l";
1256 }
1257
Ted Kremenekaa66a322008-01-16 21:46:15 +00001258 break;
1259 }
1260
1261 default: {
1262 const BlockEdge& E = cast<BlockEdge>(Loc);
1263 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
1264 << E.getDst()->getBlockID() << ')';
Ted Kremenekb38911f2008-01-30 23:03:39 +00001265
1266 if (Stmt* T = E.getSrc()->getTerminator()) {
1267 Out << "\\|Terminator: ";
1268 E.getSrc()->printTerminator(Out);
1269
1270 if (isa<SwitchStmt>(T)) {
1271 // FIXME
1272 }
1273 else {
1274 Out << "\\lCondition: ";
1275 if (*E.getSrc()->succ_begin() == E.getDst())
1276 Out << "true";
1277 else
1278 Out << "false";
1279 }
1280
1281 Out << "\\l";
1282 }
Ted Kremenek3b4f6702008-01-30 23:24:39 +00001283
1284 if (GraphPrintCheckerState->isUninitControlFlow(N)) {
1285 Out << "\\|Control-flow based on\\lUninitialized value.\\l";
1286 }
Ted Kremenekaa66a322008-01-16 21:46:15 +00001287 }
1288 }
1289
Ted Kremenek9153f732008-02-05 07:17:49 +00001290 Out << "\\|StateID: " << (void*) N->getState().getImpl() << "\\|";
Ted Kremenekaa66a322008-01-16 21:46:15 +00001291
Ted Kremenek9153f732008-02-05 07:17:49 +00001292 PrintKind(Out, N->getState(), VarBindKey::IsDecl, true);
1293 PrintKind(Out, N->getState(), VarBindKey::IsBlkExpr);
1294 PrintKind(Out, N->getState(), VarBindKey::IsSubExpr);
Ted Kremeneked4de312008-02-06 03:56:15 +00001295
1296 PrintEQ(Out, N->getState());
1297 PrintNE(Out, N->getState());
Ted Kremenek803c9ed2008-01-23 22:30:44 +00001298
Ted Kremenek803c9ed2008-01-23 22:30:44 +00001299 Out << "\\l";
Ted Kremenekaa66a322008-01-16 21:46:15 +00001300 return Out.str();
1301 }
1302};
1303} // end llvm namespace
1304#endif
1305
Ted Kremenekee985462008-01-16 18:18:48 +00001306namespace clang {
Ted Kremenekcb48b9c2008-01-29 00:33:40 +00001307void RunGRConstants(CFG& cfg, FunctionDecl& FD, ASTContext& Ctx) {
1308 GREngine<GRConstants> Engine(cfg, FD, Ctx);
Ted Kremenekee985462008-01-16 18:18:48 +00001309 Engine.ExecuteWorkList();
Ted Kremenekaa66a322008-01-16 21:46:15 +00001310#ifndef NDEBUG
Ted Kremenek3b4f6702008-01-30 23:24:39 +00001311 GraphPrintCheckerState = &Engine.getCheckerState();
Ted Kremenekaa66a322008-01-16 21:46:15 +00001312 llvm::ViewGraph(*Engine.getGraph().roots_begin(),"GRConstants");
Ted Kremenek3b4f6702008-01-30 23:24:39 +00001313 GraphPrintCheckerState = NULL;
Ted Kremenekaa66a322008-01-16 21:46:15 +00001314#endif
Ted Kremenekee985462008-01-16 18:18:48 +00001315}
Ted Kremenekab2b8c52008-01-23 19:59:44 +00001316} // end clang namespace