blob: 1aadf8aeff87d09fd82612bc0fb4c3971ff93a18 [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 Kremeneke3d7c242008-01-16 23:35:31 +000050 enum VariantKind { IsSubExp=0x0, IsValueDecl=0x1, IsBlkLvl=0x2, 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; }
Ted Kremenekb3d2dca2008-01-16 23:33:44 +000066 inline bool operator<(const DSPtr& X) const {
67 VariantKind k = getKind(), Xk = X.getKind();
68 return k == Xk ? getPtr() < X.getPtr() : k < Xk;
69 }
Ted Kremenekd27f8162008-01-15 23:55:06 +000070};
71} // end anonymous namespace
72
Ted Kremenekcb448ca2008-01-16 00:53:15 +000073// Machinery to get cast<> and dyn_cast<> working with DSPtr.
Ted Kremenekd27f8162008-01-15 23:55:06 +000074namespace llvm {
Ted Kremenekaa66a322008-01-16 21:46:15 +000075 template<> inline bool isa<ValueDecl,DSPtr>(const DSPtr& V) {
76 return V.getKind() == DSPtr::IsValueDecl;
Ted Kremenekd27f8162008-01-15 23:55:06 +000077 }
Ted Kremenekcb448ca2008-01-16 00:53:15 +000078 template<> inline bool isa<Stmt,DSPtr>(const DSPtr& V) {
Ted Kremenekaa66a322008-01-16 21:46:15 +000079 return ((unsigned) V.getKind()) > DSPtr::IsValueDecl;
Ted Kremenekd27f8162008-01-15 23:55:06 +000080 }
Ted Kremenekaa66a322008-01-16 21:46:15 +000081 template<> struct VISIBILITY_HIDDEN cast_retty_impl<ValueDecl,DSPtr> {
82 typedef const ValueDecl* ret_type;
Ted Kremenekd27f8162008-01-15 23:55:06 +000083 };
Ted Kremenekcb448ca2008-01-16 00:53:15 +000084 template<> struct VISIBILITY_HIDDEN cast_retty_impl<Stmt,DSPtr> {
Ted Kremenekd27f8162008-01-15 23:55:06 +000085 typedef const Stmt* ret_type;
86 };
Ted Kremenekcb448ca2008-01-16 00:53:15 +000087 template<> struct VISIBILITY_HIDDEN simplify_type<DSPtr> {
Ted Kremenekd27f8162008-01-15 23:55:06 +000088 typedef void* SimpleType;
Ted Kremenekcb448ca2008-01-16 00:53:15 +000089 static inline SimpleType getSimplifiedValue(const DSPtr &V) {
Ted Kremenekd27f8162008-01-15 23:55:06 +000090 return V.getPtr();
91 }
92 };
93} // end llvm namespace
94
95//===----------------------------------------------------------------------===//
96// DeclStmtMapTy - A ImmutableMap type from Decl*/Stmt* to integers.
97//
98// FIXME: We may eventually use APSInt, or a mixture of APSInt and
99// integer primitives to do this right; this will handle both
100// different bit-widths and allow us to detect integer overflows, etc.
101//
102//===----------------------------------------------------------------------===//
103
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000104typedef llvm::ImmutableMap<DSPtr,uint64_t> DeclStmtMapTy;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000105
106namespace clang {
107template<>
108struct VISIBILITY_HIDDEN GRTrait<DeclStmtMapTy> {
109 static inline void* toPtr(DeclStmtMapTy M) {
110 return reinterpret_cast<void*>(M.getRoot());
111 }
112 static inline DeclStmtMapTy toState(void* P) {
113 return DeclStmtMapTy(static_cast<DeclStmtMapTy::TreeTy*>(P));
114 }
115};
116}
117
118//===----------------------------------------------------------------------===//
119// The Checker!
120//===----------------------------------------------------------------------===//
121
122namespace {
123class VISIBILITY_HIDDEN ExprVariantTy {
124 const uint64_t val;
125 const bool isConstant;
126public:
127 ExprVariantTy() : val(0), isConstant(false) {}
128 ExprVariantTy(uint64_t v) : val(v), isConstant(true) {}
129
130 operator bool() const { return isConstant; }
131 uint64_t getVal() const { assert (isConstant); return val; }
132
133 ExprVariantTy operator+(const ExprVariantTy& X) const {
134 if (!isConstant || !X.isConstant) return ExprVariantTy();
135 else return ExprVariantTy(val+X.val);
136 }
137
138 ExprVariantTy operator-(const ExprVariantTy& X) const {
139 if (!isConstant || !X.isConstant) return ExprVariantTy();
Ted Kremenek95b3f6f2008-01-16 22:20:36 +0000140 else return ExprVariantTy(val-X.val);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000141 }
142};
143} // end anonymous namespace
144
145//===----------------------------------------------------------------------===//
146// The Checker!
147//===----------------------------------------------------------------------===//
148
149namespace {
150class VISIBILITY_HIDDEN GRConstants : public CFGStmtVisitor<GRConstants> {
151
152public:
153 typedef DeclStmtMapTy StateTy;
154 typedef GRNodeBuilder<GRConstants> NodeBuilder;
155 typedef ExplodedNode<StateTy> NodeTy;
156
157protected:
Ted Kremenekaa66a322008-01-16 21:46:15 +0000158 // Liveness - live-variables information the ValueDecl* and Expr* (block-level)
Ted Kremenekd27f8162008-01-15 23:55:06 +0000159 // in the CFG. Used to prune out dead state.
160 LiveVariables* Liveness;
161
162 // Builder - The current GRNodeBuilder which is used when building the nodes
163 // for a given statement.
164 NodeBuilder* Builder;
165
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000166 DeclStmtMapTy::Factory StateMgr;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000167
168 // cfg - the current CFG.
169 CFG* cfg;
170
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000171 typedef llvm::SmallVector<NodeTy*,8> NodeSetTy;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000172 NodeSetTy NodeSetA;
173 NodeSetTy NodeSetB;
174 NodeSetTy* Nodes;
175 NodeSetTy* OldNodes;
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000176 StateTy CurrentState;
Ted Kremenekd27f8162008-01-15 23:55:06 +0000177
Ted Kremenekd27f8162008-01-15 23:55:06 +0000178public:
179 GRConstants() : Liveness(NULL), Builder(NULL), cfg(NULL),
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000180 Nodes(&NodeSetA), OldNodes(&NodeSetB),
181 CurrentState(StateMgr.GetEmptyMap()) {}
Ted Kremenekd27f8162008-01-15 23:55:06 +0000182
183 ~GRConstants() { delete Liveness; }
184
185 CFG& getCFG() { assert (cfg); return *cfg; }
186
187 void Initialize(CFG& c) {
188 cfg = &c;
189 Liveness = new LiveVariables(c);
190 Liveness->runOnCFG(c);
191 }
192
193 StateTy getInitialState() {
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000194 return StateMgr.GetEmptyMap();
Ted Kremenekd27f8162008-01-15 23:55:06 +0000195 }
196
197 void ProcessStmt(Stmt* S, NodeBuilder& builder);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000198 void SwitchNodeSets();
Ted Kremenekd27f8162008-01-15 23:55:06 +0000199 void DoStmt(Stmt* S);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000200 StateTy RemoveGrandchildrenMappings(Stmt* S, StateTy M);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000201
202 void AddBinding(Expr* E, ExprVariantTy V, bool isBlkLvl = false);
Ted Kremenekaa66a322008-01-16 21:46:15 +0000203 void AddBinding(ValueDecl* D, ExprVariantTy V);
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000204
Ted Kremenekd27f8162008-01-15 23:55:06 +0000205 ExprVariantTy GetBinding(Expr* E);
206
207 void BlockStmt_VisitStmt(Stmt* S) { DoStmt(S); }
Ted Kremenekd27f8162008-01-15 23:55:06 +0000208
209 void VisitAssign(BinaryOperator* O);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000210 void VisitBinAdd(BinaryOperator* O);
211 void VisitBinSub(BinaryOperator* O);
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000212 void VisitBinAssign(BinaryOperator* D);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000213};
214} // end anonymous namespace
215
Ted Kremenekca3e8572008-01-16 22:28:08 +0000216static inline Expr* IgnoreParen(Expr* E) {
217 while (ParenExpr* P = dyn_cast<ParenExpr>(E))
218 E = P->getSubExpr();
219
220 return E;
221}
222
Ted Kremenekd27f8162008-01-15 23:55:06 +0000223void GRConstants::ProcessStmt(Stmt* S, NodeBuilder& builder) {
224 Builder = &builder;
225 Nodes->clear();
226 OldNodes->clear();
227 NodeTy* N = Builder->getLastNode();
228 assert (N);
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000229 OldNodes->push_back(N);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000230 BlockStmt_Visit(S);
231 Builder = NULL;
232}
233
234ExprVariantTy GRConstants::GetBinding(Expr* E) {
Ted Kremenek0525a4f2008-01-16 19:47:19 +0000235 DSPtr P(NULL);
Ted Kremenekca3e8572008-01-16 22:28:08 +0000236 E = IgnoreParen(E);
Ted Kremenek0525a4f2008-01-16 19:47:19 +0000237
Ted Kremenekca3e8572008-01-16 22:28:08 +0000238 switch (E->getStmtClass()) {
239 case Stmt::DeclRefExprClass:
240 P = DSPtr(cast<DeclRefExpr>(E)->getDecl());
241 break;
242
243 case Stmt::IntegerLiteralClass:
244 return cast<IntegerLiteral>(E)->getValue().getZExtValue();
245
246 default:
247 P = DSPtr(E, getCFG().isBlkExpr(E));
248 break;
249 }
Ted Kremenek0525a4f2008-01-16 19:47:19 +0000250
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000251 StateTy::iterator I = CurrentState.find(P);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000252
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000253 if (I == CurrentState.end())
Ted Kremenekd27f8162008-01-15 23:55:06 +0000254 return ExprVariantTy();
255
256 return (*I).second;
257}
258
259void GRConstants::AddBinding(Expr* E, ExprVariantTy V, bool isBlkLvl) {
Ted Kremenek22f0d972008-01-16 19:28:16 +0000260 if (V)
261 CurrentState = StateMgr.Add(CurrentState, DSPtr(E,isBlkLvl), V.getVal());
Ted Kremenekd27f8162008-01-15 23:55:06 +0000262}
263
Ted Kremenekaa66a322008-01-16 21:46:15 +0000264void GRConstants::AddBinding(ValueDecl* D, ExprVariantTy V) {
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000265 if (V)
266 CurrentState = StateMgr.Add(CurrentState, DSPtr(D), V.getVal());
267 else
268 CurrentState = StateMgr.Remove(CurrentState, DSPtr(D));
269}
270
Ted Kremenekd27f8162008-01-15 23:55:06 +0000271void GRConstants::SwitchNodeSets() {
272 NodeSetTy* Tmp = OldNodes;
273 OldNodes = Nodes;
274 Nodes = Tmp;
275 Nodes->clear();
276}
277
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000278GRConstants::StateTy
279GRConstants::RemoveGrandchildrenMappings(Stmt* S, GRConstants::StateTy State) {
280
281 typedef Stmt::child_iterator iterator;
282
283 for (iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I)
284 if (Stmt* C = *I)
285 for (iterator CI=C->child_begin(), CE=C->child_end(); CI!=CE; ++CI) {
286 // Observe that this will only remove mappings to non-block level
287 // expressions. This is valid even if *CI is a block-level expression,
288 // since it simply won't be in the map in the first place.
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000289 // Note: This should also work if 'C' is a block-level expression,
290 // although ideally we would want to skip processing C's children.
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000291 State = StateMgr.Remove(State, DSPtr(*CI,false));
292 }
293
294 return State;
295}
Ted Kremenekd27f8162008-01-15 23:55:06 +0000296
297void GRConstants::DoStmt(Stmt* S) {
298 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I)
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000299 if (*I) DoStmt(*I);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000300
Ted Kremenekd27f8162008-01-15 23:55:06 +0000301 for (NodeSetTy::iterator I=OldNodes->begin(), E=OldNodes->end(); I!=E; ++I) {
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000302 NodeTy* Pred = *I;
303 CurrentState = Pred->getState();
304
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000305 StateTy OldState = CurrentState;
306 CurrentState = RemoveGrandchildrenMappings(S, CurrentState);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000307
Ted Kremenekd27f8162008-01-15 23:55:06 +0000308 Visit(S);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000309
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000310 if (CurrentState != OldState) {
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000311 NodeTy* N = Builder->generateNode(S, CurrentState, Pred);
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000312 if (N) Nodes->push_back(N);
Ted Kremenekcb448ca2008-01-16 00:53:15 +0000313 }
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000314 else Nodes->push_back(Pred);
Ted Kremenekd27f8162008-01-15 23:55:06 +0000315 }
Ted Kremenek3c6c6722008-01-16 17:56:25 +0000316
317 SwitchNodeSets();
Ted Kremenekd27f8162008-01-15 23:55:06 +0000318}
319
Ted Kremenekd27f8162008-01-15 23:55:06 +0000320void GRConstants::VisitBinAdd(BinaryOperator* B) {
321 AddBinding(B, GetBinding(B->getLHS()) + GetBinding(B->getRHS()));
322}
323
324void GRConstants::VisitBinSub(BinaryOperator* B) {
325 AddBinding(B, GetBinding(B->getLHS()) - GetBinding(B->getRHS()));
326}
Ted Kremenekee985462008-01-16 18:18:48 +0000327
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000328
Ted Kremenek1ccd31c2008-01-16 19:42:59 +0000329void GRConstants::VisitBinAssign(BinaryOperator* B) {
330 if (DeclRefExpr* D = dyn_cast<DeclRefExpr>(IgnoreParen(B->getLHS())))
331 AddBinding(D->getDecl(), GetBinding(B->getRHS()));
332}
333
Ted Kremenekee985462008-01-16 18:18:48 +0000334//===----------------------------------------------------------------------===//
335// Driver.
336//===----------------------------------------------------------------------===//
337
Ted Kremenekaa66a322008-01-16 21:46:15 +0000338#ifndef NDEBUG
339namespace llvm {
340template<>
341struct VISIBILITY_HIDDEN DOTGraphTraits<GRConstants::NodeTy*> :
342 public DefaultDOTGraphTraits {
343
344 static std::string getNodeLabel(const GRConstants::NodeTy* N, void*) {
345 std::ostringstream Out;
346
347 Out << "Vertex: " << (void*) N << '\n';
348 ProgramPoint Loc = N->getLocation();
349
350 switch (Loc.getKind()) {
351 case ProgramPoint::BlockEntranceKind:
352 Out << "Block Entrance: B"
353 << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
354 break;
355
356 case ProgramPoint::BlockExitKind:
357 assert (false);
358 break;
359
360 case ProgramPoint::PostStmtKind: {
361 const PostStmt& L = cast<PostStmt>(Loc);
362 Out << "Stmt: " << (void*) L.getStmt() << '\n';
363 L.getStmt()->printPretty(Out);
364 break;
365 }
366
367 default: {
368 const BlockEdge& E = cast<BlockEdge>(Loc);
369 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
370 << E.getDst()->getBlockID() << ')';
371 }
372 }
373
374 Out << "\n{";
375
376 GRConstants::StateTy M = N->getState();
377 bool isFirst = true;
378
379 for (GRConstants::StateTy::iterator I=M.begin(), E=M.end(); I!=E; ++I) {
380 if (!isFirst)
381 Out << '\n';
382 else
383 isFirst = false;
384
385 if (ValueDecl* V = dyn_cast<ValueDecl>(I.getKey())) {
386 Out << "Decl: " << (void*) V << ", " << V->getName();
387 }
388 else {
389 Stmt* E = cast<Stmt>(I.getKey());
390 Out << "Stmt: " << (void*) E;
391 }
392
393 Out << " => " << I.getData();
394 }
395
396 Out << " }";
397
398 return Out.str();
399 }
400};
401} // end llvm namespace
402#endif
403
Ted Kremenekee985462008-01-16 18:18:48 +0000404namespace clang {
405void RunGRConstants(CFG& cfg) {
406 GREngine<GRConstants> Engine(cfg);
407 Engine.ExecuteWorkList();
Ted Kremenekaa66a322008-01-16 21:46:15 +0000408#ifndef NDEBUG
409 llvm::ViewGraph(*Engine.getGraph().roots_begin(),"GRConstants");
410#endif
Ted Kremenekee985462008-01-16 18:18:48 +0000411}
412}