blob: 314902e922ff2f24f2fdc8db78fecdad9e49fd22 [file] [log] [blame]
Ted Kremenekd27f8162008-01-15 23:55:06 +00001//===-- GRConstants.cpp - Simple, Path-Sens. Constant Prop. ------*- C++ -*-==//
2//
3// The LLVM Compiler Infrastructure
4//
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
18#include "clang/Analysis/PathSensitive/GREngine.h"
19#include "clang/AST/Expr.h"
20#include "clang/Analysis/Analyses/LiveVariables.h"
21#include "clang/Analysis/Visitors/CFGStmtVisitor.h"
22
23#include "llvm/Support/Casting.h"
24#include "llvm/Support/DataTypes.h"
25#include "llvm/ADT/APSInt.h"
26#include "llvm/ADT/FoldingSet.h"
27#include "llvm/ADT/ImmutableMap.h"
28#include "llvm/Support/Compiler.h"
29
30using namespace clang;
31using llvm::APInt;
32using llvm::APFloat;
33using llvm::dyn_cast;
34using llvm::cast;
35
36//===----------------------------------------------------------------------===//
Ted Kremenekcb448ca2008-01-16 00:53:15 +000037/// DSPtr - A variant smart pointer that wraps either a Decl* or a
Ted Kremenekd27f8162008-01-15 23:55:06 +000038/// Stmt*. Use cast<> or dyn_cast<> to get actual pointer type
39//===----------------------------------------------------------------------===//
40namespace {
Ted Kremenekcb448ca2008-01-16 00:53:15 +000041class VISIBILITY_HIDDEN DSPtr {
Ted Kremenekd27f8162008-01-15 23:55:06 +000042 const uintptr_t Raw;
43public:
44 enum VariantKind { IsDecl=0x1, IsBlkLvl=0x2, IsSubExp=0x3, Flags=0x3 };
45 inline void* getPtr() const { return reinterpret_cast<void*>(Raw & ~Flags); }
46 inline VariantKind getKind() const { return (VariantKind) (Raw & Flags); }
47
Ted Kremenekcb448ca2008-01-16 00:53:15 +000048 DSPtr(Decl* D) : Raw(reinterpret_cast<uintptr_t>(D) | IsDecl) {}
49 DSPtr(Stmt* S, bool isBlkLvl)
Ted Kremenekd27f8162008-01-15 23:55:06 +000050 : Raw(reinterpret_cast<uintptr_t>(S) | (isBlkLvl ? IsBlkLvl : IsSubExp)) {}
51
52 bool isSubExpr() const { return getKind() == IsSubExp; }
53
54 inline void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremeneked371ce2008-01-16 05:49:09 +000055 ID.AddInteger(Raw);
Ted Kremenekd27f8162008-01-15 23:55:06 +000056 }
Ted Kremenekcb448ca2008-01-16 00:53:15 +000057 inline bool operator==(const DSPtr& X) const { return Raw == X.Raw; }
58 inline bool operator!=(const DSPtr& X) const { return Raw != X.Raw; }
59 inline bool operator<(const DSPtr& X) const { return Raw < X.Raw; }
Ted Kremenekd27f8162008-01-15 23:55:06 +000060};
61} // end anonymous namespace
62
Ted Kremenekcb448ca2008-01-16 00:53:15 +000063// Machinery to get cast<> and dyn_cast<> working with DSPtr.
Ted Kremenekd27f8162008-01-15 23:55:06 +000064namespace llvm {
Ted Kremenekcb448ca2008-01-16 00:53:15 +000065 template<> inline bool isa<Decl,DSPtr>(const DSPtr& V) {
66 return V.getKind() == DSPtr::IsDecl;
Ted Kremenekd27f8162008-01-15 23:55:06 +000067 }
Ted Kremenekcb448ca2008-01-16 00:53:15 +000068 template<> inline bool isa<Stmt,DSPtr>(const DSPtr& V) {
69 return ((unsigned) V.getKind()) > DSPtr::IsDecl;
Ted Kremenekd27f8162008-01-15 23:55:06 +000070 }
Ted Kremenekcb448ca2008-01-16 00:53:15 +000071 template<> struct VISIBILITY_HIDDEN cast_retty_impl<Decl,DSPtr> {
Ted Kremenekd27f8162008-01-15 23:55:06 +000072 typedef const Decl* ret_type;
73 };
Ted Kremenekcb448ca2008-01-16 00:53:15 +000074 template<> struct VISIBILITY_HIDDEN cast_retty_impl<Stmt,DSPtr> {
Ted Kremenekd27f8162008-01-15 23:55:06 +000075 typedef const Stmt* ret_type;
76 };
Ted Kremenekcb448ca2008-01-16 00:53:15 +000077 template<> struct VISIBILITY_HIDDEN simplify_type<DSPtr> {
Ted Kremenekd27f8162008-01-15 23:55:06 +000078 typedef void* SimpleType;
Ted Kremenekcb448ca2008-01-16 00:53:15 +000079 static inline SimpleType getSimplifiedValue(const DSPtr &V) {
Ted Kremenekd27f8162008-01-15 23:55:06 +000080 return V.getPtr();
81 }
82 };
83} // end llvm namespace
84
85//===----------------------------------------------------------------------===//
86// DeclStmtMapTy - A ImmutableMap type from Decl*/Stmt* to integers.
87//
88// FIXME: We may eventually use APSInt, or a mixture of APSInt and
89// integer primitives to do this right; this will handle both
90// different bit-widths and allow us to detect integer overflows, etc.
91//
92//===----------------------------------------------------------------------===//
93
Ted Kremenekcb448ca2008-01-16 00:53:15 +000094typedef llvm::ImmutableMap<DSPtr,uint64_t> DeclStmtMapTy;
Ted Kremenekd27f8162008-01-15 23:55:06 +000095
96namespace clang {
97template<>
98struct VISIBILITY_HIDDEN GRTrait<DeclStmtMapTy> {
99 static inline void* toPtr(DeclStmtMapTy M) {
100 return reinterpret_cast<void*>(M.getRoot());
101 }
102 static inline DeclStmtMapTy toState(void* P) {
103 return DeclStmtMapTy(static_cast<DeclStmtMapTy::TreeTy*>(P));
104 }
105};
106}
107
108//===----------------------------------------------------------------------===//
109// The Checker!
110//===----------------------------------------------------------------------===//
111
112namespace {
113class VISIBILITY_HIDDEN ExprVariantTy {
114 const uint64_t val;
115 const bool isConstant;
116public:
117 ExprVariantTy() : val(0), isConstant(false) {}
118 ExprVariantTy(uint64_t v) : val(v), isConstant(true) {}
119
120 operator bool() const { return isConstant; }
121 uint64_t getVal() const { assert (isConstant); return val; }
122
123 ExprVariantTy operator+(const ExprVariantTy& X) const {
124 if (!isConstant || !X.isConstant) return ExprVariantTy();
125 else return ExprVariantTy(val+X.val);
126 }
127
128 ExprVariantTy operator-(const ExprVariantTy& X) const {
129 if (!isConstant || !X.isConstant) return ExprVariantTy();
130 else return ExprVariantTy(val+X.val);
131 }
132};
133} // end anonymous namespace
134
135//===----------------------------------------------------------------------===//
136// The Checker!
137//===----------------------------------------------------------------------===//
138
139namespace {
140class VISIBILITY_HIDDEN GRConstants : public CFGStmtVisitor<GRConstants> {
141
142public:
143 typedef DeclStmtMapTy StateTy;
144 typedef GRNodeBuilder<GRConstants> NodeBuilder;
145 typedef ExplodedNode<StateTy> NodeTy;
146
147protected:
148 // Liveness - live-variables information the Decl* and Expr* (block-level)
149 // in the CFG. Used to prune out dead state.
150 LiveVariables* Liveness;
151
152 // Builder - The current GRNodeBuilder which is used when building the nodes
153 // for a given statement.
154 NodeBuilder* Builder;
155
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000156 DeclStmtMapTy::Factory StateMgr;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000157
158 // cfg - the current CFG.
159 CFG* cfg;
160
161 typedef llvm::SmallPtrSet<NodeTy*,16> NodeSetTy;
162 NodeSetTy NodeSetA;
163 NodeSetTy NodeSetB;
164 NodeSetTy* Nodes;
165 NodeSetTy* OldNodes;
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000166 StateTy CurrentState;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000167
168 bool DoNotSwitch;
169
170public:
171 GRConstants() : Liveness(NULL), Builder(NULL), cfg(NULL),
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000172 Nodes(&NodeSetA), OldNodes(&NodeSetB),
173 CurrentState(StateMgr.GetEmptyMap()), DoNotSwitch(false) {}
Ted Kremenekd27f8162008-01-15 23:55:06 +0000174
175 ~GRConstants() { delete Liveness; }
176
177 CFG& getCFG() { assert (cfg); return *cfg; }
178
179 void Initialize(CFG& c) {
180 cfg = &c;
181 Liveness = new LiveVariables(c);
182 Liveness->runOnCFG(c);
183 }
184
185 StateTy getInitialState() {
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000186 return StateMgr.GetEmptyMap();
Ted Kremenekd27f8162008-01-15 23:55:06 +0000187 }
188
189 void ProcessStmt(Stmt* S, NodeBuilder& builder);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000190 void SwitchNodeSets();
Ted Kremenekd27f8162008-01-15 23:55:06 +0000191 void DoStmt(Stmt* S);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000192 StateTy RemoveGrandchildrenMappings(Stmt* S, StateTy M);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000193
194 void AddBinding(Expr* E, ExprVariantTy V, bool isBlkLvl = false);
195 ExprVariantTy GetBinding(Expr* E);
196
197 void BlockStmt_VisitStmt(Stmt* S) { DoStmt(S); }
198 void VisitStmt(Stmt* S) { DoNotSwitch = true; }
199
200 void VisitAssign(BinaryOperator* O);
201 void VisitIntegerLiteral(IntegerLiteral* L);
202 void VisitBinAdd(BinaryOperator* O);
203 void VisitBinSub(BinaryOperator* O);
204};
205} // end anonymous namespace
206
207void GRConstants::ProcessStmt(Stmt* S, NodeBuilder& builder) {
208 Builder = &builder;
209 Nodes->clear();
210 OldNodes->clear();
211 NodeTy* N = Builder->getLastNode();
212 assert (N);
213 OldNodes->insert(N);
214 DoNotSwitch = true;
215 BlockStmt_Visit(S);
216 Builder = NULL;
217}
218
219ExprVariantTy GRConstants::GetBinding(Expr* E) {
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000220 DSPtr P(E, getCFG().isBlkExpr(E));
221 StateTy::iterator I = CurrentState.find(P);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000222
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000223 if (I == CurrentState.end())
Ted Kremenekd27f8162008-01-15 23:55:06 +0000224 return ExprVariantTy();
225
226 return (*I).second;
227}
228
229void GRConstants::AddBinding(Expr* E, ExprVariantTy V, bool isBlkLvl) {
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000230 CurrentState = StateMgr.Add(CurrentState, DSPtr(E,isBlkLvl), V.getVal());
Ted Kremenekd27f8162008-01-15 23:55:06 +0000231}
232
233void GRConstants::SwitchNodeSets() {
234 NodeSetTy* Tmp = OldNodes;
235 OldNodes = Nodes;
236 Nodes = Tmp;
237 Nodes->clear();
238}
239
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000240GRConstants::StateTy
241GRConstants::RemoveGrandchildrenMappings(Stmt* S, GRConstants::StateTy State) {
242
243 typedef Stmt::child_iterator iterator;
244
245 for (iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I)
246 if (Stmt* C = *I)
247 for (iterator CI=C->child_begin(), CE=C->child_end(); CI!=CE; ++CI) {
248 // Observe that this will only remove mappings to non-block level
249 // expressions. This is valid even if *CI is a block-level expression,
250 // since it simply won't be in the map in the first place.
251 State = StateMgr.Remove(State, DSPtr(*CI,false));
252 }
253
254 return State;
255}
Ted Kremenekd27f8162008-01-15 23:55:06 +0000256
257void GRConstants::DoStmt(Stmt* S) {
258 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I)
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000259 if (*I) DoStmt(*I);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000260
261 if (!DoNotSwitch) SwitchNodeSets();
262 DoNotSwitch = false;
263
264 for (NodeSetTy::iterator I=OldNodes->begin(), E=OldNodes->end(); I!=E; ++I) {
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000265 NodeTy* Pred = *I;
266 CurrentState = Pred->getState();
267
268 StateTy CleanedState = RemoveGrandchildrenMappings(S, CurrentState);
269 bool AlwaysGenerateNode = false;
270
271 if (CleanedState != CurrentState) {
272 CurrentState = CleanedState;
273 AlwaysGenerateNode = true;
274 }
275
Ted Kremenekd27f8162008-01-15 23:55:06 +0000276 Visit(S);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000277
278 if (AlwaysGenerateNode || CurrentState != CleanedState) {
279 NodeTy* N = Builder->generateNode(S, CurrentState, Pred);
280 if (N) Nodes->insert(N);
281 }
282 else Nodes->insert(Pred);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000283 }
284}
285
286void GRConstants::VisitIntegerLiteral(IntegerLiteral* L) {
287 AddBinding(L, L->getValue().getZExtValue());
288}
289
290void GRConstants::VisitBinAdd(BinaryOperator* B) {
291 AddBinding(B, GetBinding(B->getLHS()) + GetBinding(B->getRHS()));
292}
293
294void GRConstants::VisitBinSub(BinaryOperator* B) {
295 AddBinding(B, GetBinding(B->getLHS()) - GetBinding(B->getRHS()));
296}
297