blob: 5acaf79b34acdf94478c9d77de0aa38c5182515d [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"
Ted Kremenek3c6c6722008-01-16 17:56:25 +000028#include "llvm/ADT/SmallVector.h"
Ted Kremenekd27f8162008-01-15 23:55:06 +000029#include "llvm/Support/Compiler.h"
30
Ted Kremenekaa66a322008-01-16 21:46:15 +000031#ifndef NDEBUG
32#include "llvm/Support/GraphWriter.h"
33#include <sstream>
34#endif
35
Ted Kremenekd27f8162008-01-15 23:55:06 +000036using namespace clang;
37using llvm::APInt;
38using llvm::APFloat;
39using llvm::dyn_cast;
40using llvm::cast;
41
42//===----------------------------------------------------------------------===//
Ted Kremenekaa66a322008-01-16 21:46:15 +000043/// DSPtr - A variant smart pointer that wraps either a ValueDecl* or a
Ted Kremenekd27f8162008-01-15 23:55:06 +000044/// Stmt*. Use cast<> or dyn_cast<> to get actual pointer type
45//===----------------------------------------------------------------------===//
46namespace {
Ted Kremenekcb448ca2008-01-16 00:53:15 +000047class VISIBILITY_HIDDEN DSPtr {
Ted Kremenek0525a4f2008-01-16 19:47:19 +000048 uintptr_t Raw;
Ted Kremenekd27f8162008-01-15 23:55:06 +000049public:
Ted Kremenekaa66a322008-01-16 21:46:15 +000050 enum VariantKind { IsValueDecl=0x1, IsBlkLvl=0x2, IsSubExp=0x3, Flags=0x3 };
Ted Kremenekd27f8162008-01-15 23:55:06 +000051 inline void* getPtr() const { return reinterpret_cast<void*>(Raw & ~Flags); }
52 inline VariantKind getKind() const { return (VariantKind) (Raw & Flags); }
53
Ted Kremenekaa66a322008-01-16 21:46:15 +000054 DSPtr(ValueDecl* D) : Raw(reinterpret_cast<uintptr_t>(D) | IsValueDecl) {}
Ted Kremenekcb448ca2008-01-16 00:53:15 +000055 DSPtr(Stmt* S, bool isBlkLvl)
Ted Kremenekd27f8162008-01-15 23:55:06 +000056 : Raw(reinterpret_cast<uintptr_t>(S) | (isBlkLvl ? IsBlkLvl : IsSubExp)) {}
57
58 bool isSubExpr() const { return getKind() == IsSubExp; }
59
60 inline void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek98491852008-01-16 05:51:13 +000061 ID.AddPointer(getPtr());
62 ID.AddInteger((unsigned) getKind());
Ted Kremenekd27f8162008-01-15 23:55:06 +000063 }
Ted Kremenekcb448ca2008-01-16 00:53:15 +000064 inline bool operator==(const DSPtr& X) const { return Raw == X.Raw; }
65 inline bool operator!=(const DSPtr& X) const { return Raw != X.Raw; }
66 inline bool operator<(const DSPtr& X) const { return Raw < X.Raw; }
Ted Kremenekd27f8162008-01-15 23:55:06 +000067};
68} // end anonymous namespace
69
Ted Kremenekcb448ca2008-01-16 00:53:15 +000070// Machinery to get cast<> and dyn_cast<> working with DSPtr.
Ted Kremenekd27f8162008-01-15 23:55:06 +000071namespace llvm {
Ted Kremenekaa66a322008-01-16 21:46:15 +000072 template<> inline bool isa<ValueDecl,DSPtr>(const DSPtr& V) {
73 return V.getKind() == DSPtr::IsValueDecl;
Ted Kremenekd27f8162008-01-15 23:55:06 +000074 }
Ted Kremenekcb448ca2008-01-16 00:53:15 +000075 template<> inline bool isa<Stmt,DSPtr>(const DSPtr& V) {
Ted Kremenekaa66a322008-01-16 21:46:15 +000076 return ((unsigned) V.getKind()) > DSPtr::IsValueDecl;
Ted Kremenekd27f8162008-01-15 23:55:06 +000077 }
Ted Kremenekaa66a322008-01-16 21:46:15 +000078 template<> struct VISIBILITY_HIDDEN cast_retty_impl<ValueDecl,DSPtr> {
79 typedef const ValueDecl* ret_type;
Ted Kremenekd27f8162008-01-15 23:55:06 +000080 };
Ted Kremenekcb448ca2008-01-16 00:53:15 +000081 template<> struct VISIBILITY_HIDDEN cast_retty_impl<Stmt,DSPtr> {
Ted Kremenekd27f8162008-01-15 23:55:06 +000082 typedef const Stmt* ret_type;
83 };
Ted Kremenekcb448ca2008-01-16 00:53:15 +000084 template<> struct VISIBILITY_HIDDEN simplify_type<DSPtr> {
Ted Kremenekd27f8162008-01-15 23:55:06 +000085 typedef void* SimpleType;
Ted Kremenekcb448ca2008-01-16 00:53:15 +000086 static inline SimpleType getSimplifiedValue(const DSPtr &V) {
Ted Kremenekd27f8162008-01-15 23:55:06 +000087 return V.getPtr();
88 }
89 };
90} // end llvm namespace
91
92//===----------------------------------------------------------------------===//
93// DeclStmtMapTy - A ImmutableMap type from Decl*/Stmt* to integers.
94//
95// FIXME: We may eventually use APSInt, or a mixture of APSInt and
96// integer primitives to do this right; this will handle both
97// different bit-widths and allow us to detect integer overflows, etc.
98//
99//===----------------------------------------------------------------------===//
100
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000101typedef llvm::ImmutableMap<DSPtr,uint64_t> DeclStmtMapTy;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000102
103namespace clang {
104template<>
105struct VISIBILITY_HIDDEN GRTrait<DeclStmtMapTy> {
106 static inline void* toPtr(DeclStmtMapTy M) {
107 return reinterpret_cast<void*>(M.getRoot());
108 }
109 static inline DeclStmtMapTy toState(void* P) {
110 return DeclStmtMapTy(static_cast<DeclStmtMapTy::TreeTy*>(P));
111 }
112};
113}
114
115//===----------------------------------------------------------------------===//
116// The Checker!
117//===----------------------------------------------------------------------===//
118
119namespace {
120class VISIBILITY_HIDDEN ExprVariantTy {
121 const uint64_t val;
122 const bool isConstant;
123public:
124 ExprVariantTy() : val(0), isConstant(false) {}
125 ExprVariantTy(uint64_t v) : val(v), isConstant(true) {}
126
127 operator bool() const { return isConstant; }
128 uint64_t getVal() const { assert (isConstant); return val; }
129
130 ExprVariantTy operator+(const ExprVariantTy& X) const {
131 if (!isConstant || !X.isConstant) return ExprVariantTy();
132 else return ExprVariantTy(val+X.val);
133 }
134
135 ExprVariantTy operator-(const ExprVariantTy& X) const {
136 if (!isConstant || !X.isConstant) return ExprVariantTy();
Ted Kremenek95b3f6f2008-01-16 22:20:36 +0000137 else return ExprVariantTy(val-X.val);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000138 }
139};
140} // end anonymous namespace
141
142//===----------------------------------------------------------------------===//
143// The Checker!
144//===----------------------------------------------------------------------===//
145
146namespace {
147class VISIBILITY_HIDDEN GRConstants : public CFGStmtVisitor<GRConstants> {
148
149public:
150 typedef DeclStmtMapTy StateTy;
151 typedef GRNodeBuilder<GRConstants> NodeBuilder;
152 typedef ExplodedNode<StateTy> NodeTy;
153
154protected:
Ted Kremenekaa66a322008-01-16 21:46:15 +0000155 // Liveness - live-variables information the ValueDecl* and Expr* (block-level)
Ted Kremenekd27f8162008-01-15 23:55:06 +0000156 // in the CFG. Used to prune out dead state.
157 LiveVariables* Liveness;
158
159 // Builder - The current GRNodeBuilder which is used when building the nodes
160 // for a given statement.
161 NodeBuilder* Builder;
162
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000163 DeclStmtMapTy::Factory StateMgr;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000164
165 // cfg - the current CFG.
166 CFG* cfg;
167
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000168 typedef llvm::SmallVector<NodeTy*,8> NodeSetTy;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000169 NodeSetTy NodeSetA;
170 NodeSetTy NodeSetB;
171 NodeSetTy* Nodes;
172 NodeSetTy* OldNodes;
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000173 StateTy CurrentState;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000174
Ted Kremenekd27f8162008-01-15 23:55:06 +0000175public:
176 GRConstants() : Liveness(NULL), Builder(NULL), cfg(NULL),
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000177 Nodes(&NodeSetA), OldNodes(&NodeSetB),
178 CurrentState(StateMgr.GetEmptyMap()) {}
Ted Kremenekd27f8162008-01-15 23:55:06 +0000179
180 ~GRConstants() { delete Liveness; }
181
182 CFG& getCFG() { assert (cfg); return *cfg; }
183
184 void Initialize(CFG& c) {
185 cfg = &c;
186 Liveness = new LiveVariables(c);
187 Liveness->runOnCFG(c);
188 }
189
190 StateTy getInitialState() {
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000191 return StateMgr.GetEmptyMap();
Ted Kremenekd27f8162008-01-15 23:55:06 +0000192 }
193
194 void ProcessStmt(Stmt* S, NodeBuilder& builder);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000195 void SwitchNodeSets();
Ted Kremenekd27f8162008-01-15 23:55:06 +0000196 void DoStmt(Stmt* S);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000197 StateTy RemoveGrandchildrenMappings(Stmt* S, StateTy M);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000198
199 void AddBinding(Expr* E, ExprVariantTy V, bool isBlkLvl = false);
Ted Kremenekaa66a322008-01-16 21:46:15 +0000200 void AddBinding(ValueDecl* D, ExprVariantTy V);
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000201
Ted Kremenekd27f8162008-01-15 23:55:06 +0000202 ExprVariantTy GetBinding(Expr* E);
203
204 void BlockStmt_VisitStmt(Stmt* S) { DoStmt(S); }
Ted Kremenekd27f8162008-01-15 23:55:06 +0000205
206 void VisitAssign(BinaryOperator* O);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000207 void VisitBinAdd(BinaryOperator* O);
208 void VisitBinSub(BinaryOperator* O);
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000209 void VisitBinAssign(BinaryOperator* D);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000210};
211} // end anonymous namespace
212
Ted Kremenekca3e8572008-01-16 22:28:08 +0000213static inline Expr* IgnoreParen(Expr* E) {
214 while (ParenExpr* P = dyn_cast<ParenExpr>(E))
215 E = P->getSubExpr();
216
217 return E;
218}
219
Ted Kremenekd27f8162008-01-15 23:55:06 +0000220void GRConstants::ProcessStmt(Stmt* S, NodeBuilder& builder) {
221 Builder = &builder;
222 Nodes->clear();
223 OldNodes->clear();
224 NodeTy* N = Builder->getLastNode();
225 assert (N);
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000226 OldNodes->push_back(N);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000227 BlockStmt_Visit(S);
228 Builder = NULL;
229}
230
231ExprVariantTy GRConstants::GetBinding(Expr* E) {
Ted Kremenek0525a4f2008-01-16 19:47:19 +0000232 DSPtr P(NULL);
Ted Kremenekca3e8572008-01-16 22:28:08 +0000233 E = IgnoreParen(E);
Ted Kremenek0525a4f2008-01-16 19:47:19 +0000234
Ted Kremenekca3e8572008-01-16 22:28:08 +0000235 switch (E->getStmtClass()) {
236 case Stmt::DeclRefExprClass:
237 P = DSPtr(cast<DeclRefExpr>(E)->getDecl());
238 break;
239
240 case Stmt::IntegerLiteralClass:
241 return cast<IntegerLiteral>(E)->getValue().getZExtValue();
242
243 default:
244 P = DSPtr(E, getCFG().isBlkExpr(E));
245 break;
246 }
Ted Kremenek0525a4f2008-01-16 19:47:19 +0000247
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000248 StateTy::iterator I = CurrentState.find(P);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000249
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000250 if (I == CurrentState.end())
Ted Kremenekd27f8162008-01-15 23:55:06 +0000251 return ExprVariantTy();
252
253 return (*I).second;
254}
255
256void GRConstants::AddBinding(Expr* E, ExprVariantTy V, bool isBlkLvl) {
Ted Kremenek22f0d972008-01-16 19:28:16 +0000257 if (V)
258 CurrentState = StateMgr.Add(CurrentState, DSPtr(E,isBlkLvl), V.getVal());
Ted Kremenekd27f8162008-01-15 23:55:06 +0000259}
260
Ted Kremenekaa66a322008-01-16 21:46:15 +0000261void GRConstants::AddBinding(ValueDecl* D, ExprVariantTy V) {
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000262 if (V)
263 CurrentState = StateMgr.Add(CurrentState, DSPtr(D), V.getVal());
264 else
265 CurrentState = StateMgr.Remove(CurrentState, DSPtr(D));
266}
267
Ted Kremenekd27f8162008-01-15 23:55:06 +0000268void GRConstants::SwitchNodeSets() {
269 NodeSetTy* Tmp = OldNodes;
270 OldNodes = Nodes;
271 Nodes = Tmp;
272 Nodes->clear();
273}
274
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000275GRConstants::StateTy
276GRConstants::RemoveGrandchildrenMappings(Stmt* S, GRConstants::StateTy State) {
277
278 typedef Stmt::child_iterator iterator;
279
280 for (iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I)
281 if (Stmt* C = *I)
282 for (iterator CI=C->child_begin(), CE=C->child_end(); CI!=CE; ++CI) {
283 // Observe that this will only remove mappings to non-block level
284 // expressions. This is valid even if *CI is a block-level expression,
285 // since it simply won't be in the map in the first place.
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000286 // Note: This should also work if 'C' is a block-level expression,
287 // although ideally we would want to skip processing C's children.
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000288 State = StateMgr.Remove(State, DSPtr(*CI,false));
289 }
290
291 return State;
292}
Ted Kremenekd27f8162008-01-15 23:55:06 +0000293
294void GRConstants::DoStmt(Stmt* S) {
295 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I)
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000296 if (*I) DoStmt(*I);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000297
Ted Kremenekd27f8162008-01-15 23:55:06 +0000298 for (NodeSetTy::iterator I=OldNodes->begin(), E=OldNodes->end(); I!=E; ++I) {
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000299 NodeTy* Pred = *I;
300 CurrentState = Pred->getState();
301
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000302 StateTy OldState = CurrentState;
303 CurrentState = RemoveGrandchildrenMappings(S, CurrentState);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000304
Ted Kremenekd27f8162008-01-15 23:55:06 +0000305 Visit(S);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000306
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000307 if (CurrentState != OldState) {
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000308 NodeTy* N = Builder->generateNode(S, CurrentState, Pred);
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000309 if (N) Nodes->push_back(N);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000310 }
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000311 else Nodes->push_back(Pred);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000312 }
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000313
314 SwitchNodeSets();
Ted Kremenekd27f8162008-01-15 23:55:06 +0000315}
316
Ted Kremenekd27f8162008-01-15 23:55:06 +0000317void GRConstants::VisitBinAdd(BinaryOperator* B) {
318 AddBinding(B, GetBinding(B->getLHS()) + GetBinding(B->getRHS()));
319}
320
321void GRConstants::VisitBinSub(BinaryOperator* B) {
322 AddBinding(B, GetBinding(B->getLHS()) - GetBinding(B->getRHS()));
323}
Ted Kremenekee985462008-01-16 18:18:48 +0000324
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000325
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000326void GRConstants::VisitBinAssign(BinaryOperator* B) {
327 if (DeclRefExpr* D = dyn_cast<DeclRefExpr>(IgnoreParen(B->getLHS())))
328 AddBinding(D->getDecl(), GetBinding(B->getRHS()));
329}
330
Ted Kremenekee985462008-01-16 18:18:48 +0000331//===----------------------------------------------------------------------===//
332// Driver.
333//===----------------------------------------------------------------------===//
334
Ted Kremenekaa66a322008-01-16 21:46:15 +0000335#ifndef NDEBUG
336namespace llvm {
337template<>
338struct VISIBILITY_HIDDEN DOTGraphTraits<GRConstants::NodeTy*> :
339 public DefaultDOTGraphTraits {
340
341 static std::string getNodeLabel(const GRConstants::NodeTy* N, void*) {
342 std::ostringstream Out;
343
344 Out << "Vertex: " << (void*) N << '\n';
345 ProgramPoint Loc = N->getLocation();
346
347 switch (Loc.getKind()) {
348 case ProgramPoint::BlockEntranceKind:
349 Out << "Block Entrance: B"
350 << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
351 break;
352
353 case ProgramPoint::BlockExitKind:
354 assert (false);
355 break;
356
357 case ProgramPoint::PostStmtKind: {
358 const PostStmt& L = cast<PostStmt>(Loc);
359 Out << "Stmt: " << (void*) L.getStmt() << '\n';
360 L.getStmt()->printPretty(Out);
361 break;
362 }
363
364 default: {
365 const BlockEdge& E = cast<BlockEdge>(Loc);
366 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
367 << E.getDst()->getBlockID() << ')';
368 }
369 }
370
371 Out << "\n{";
372
373 GRConstants::StateTy M = N->getState();
374 bool isFirst = true;
375
376 for (GRConstants::StateTy::iterator I=M.begin(), E=M.end(); I!=E; ++I) {
377 if (!isFirst)
378 Out << '\n';
379 else
380 isFirst = false;
381
382 if (ValueDecl* V = dyn_cast<ValueDecl>(I.getKey())) {
383 Out << "Decl: " << (void*) V << ", " << V->getName();
384 }
385 else {
386 Stmt* E = cast<Stmt>(I.getKey());
387 Out << "Stmt: " << (void*) E;
388 }
389
390 Out << " => " << I.getData();
391 }
392
393 Out << " }";
394
395 return Out.str();
396 }
397};
398} // end llvm namespace
399#endif
400
Ted Kremenekee985462008-01-16 18:18:48 +0000401namespace clang {
402void RunGRConstants(CFG& cfg) {
403 GREngine<GRConstants> Engine(cfg);
404 Engine.ExecuteWorkList();
Ted Kremenekaa66a322008-01-16 21:46:15 +0000405#ifndef NDEBUG
406 llvm::ViewGraph(*Engine.getGraph().roots_begin(),"GRConstants");
407#endif
Ted Kremenekee985462008-01-16 18:18:48 +0000408}
409}