blob: 86b96ce6230f70b5c33f99a65615586fc3250e96 [file] [log] [blame]
Ted Kremenek6f342132011-03-15 03:17:07 +00001//==- UninitializedValues.cpp - Find Uninitialized Values -------*- C++ --*-==//
Ted Kremenek610068c2011-01-15 02:58:47 +00002//
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// This file implements uninitialized values analysis for source-level CFGs.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek13bd4232011-01-20 17:37:17 +000014#include <utility>
Ted Kremenek610068c2011-01-15 02:58:47 +000015#include "llvm/ADT/Optional.h"
16#include "llvm/ADT/SmallVector.h"
Argyrios Kyrtzidis049f6d02011-05-31 03:56:09 +000017#include "llvm/ADT/PackedVector.h"
Ted Kremenek610068c2011-01-15 02:58:47 +000018#include "llvm/ADT/DenseMap.h"
19#include "clang/AST/Decl.h"
20#include "clang/Analysis/CFG.h"
Ted Kremeneka8c17a52011-01-25 19:13:48 +000021#include "clang/Analysis/AnalysisContext.h"
Ted Kremenek610068c2011-01-15 02:58:47 +000022#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000023#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekc21fed32011-01-18 21:18:58 +000024#include "clang/Analysis/Support/SaveAndRestore.h"
Ted Kremenek610068c2011-01-15 02:58:47 +000025
26using namespace clang;
27
Ted Kremenek40900ee2011-01-27 02:29:34 +000028static bool isTrackedVar(const VarDecl *vd, const DeclContext *dc) {
Ted Kremenek1cbc3152011-03-17 03:06:11 +000029 if (vd->isLocalVarDecl() && !vd->hasGlobalStorage() &&
Ted Kremeneka21612f2011-04-07 20:02:56 +000030 !vd->isExceptionVariable() &&
Ted Kremenek1cbc3152011-03-17 03:06:11 +000031 vd->getDeclContext() == dc) {
32 QualType ty = vd->getType();
33 return ty->isScalarType() || ty->isVectorType();
34 }
35 return false;
Ted Kremenekc104e532011-01-18 04:53:25 +000036}
37
Ted Kremenek610068c2011-01-15 02:58:47 +000038//------------------------------------------------------------------------====//
Ted Kremenek136f8f22011-03-15 04:57:27 +000039// DeclToIndex: a mapping from Decls we track to value indices.
Ted Kremenek610068c2011-01-15 02:58:47 +000040//====------------------------------------------------------------------------//
41
42namespace {
Ted Kremenek136f8f22011-03-15 04:57:27 +000043class DeclToIndex {
Ted Kremenek610068c2011-01-15 02:58:47 +000044 llvm::DenseMap<const VarDecl *, unsigned> map;
45public:
Ted Kremenek136f8f22011-03-15 04:57:27 +000046 DeclToIndex() {}
Ted Kremenek610068c2011-01-15 02:58:47 +000047
48 /// Compute the actual mapping from declarations to bits.
49 void computeMap(const DeclContext &dc);
50
51 /// Return the number of declarations in the map.
52 unsigned size() const { return map.size(); }
53
54 /// Returns the bit vector index for a given declaration.
Ted Kremenekb831c672011-03-29 01:40:00 +000055 llvm::Optional<unsigned> getValueIndex(const VarDecl *d) const;
Ted Kremenek610068c2011-01-15 02:58:47 +000056};
57}
58
Ted Kremenek136f8f22011-03-15 04:57:27 +000059void DeclToIndex::computeMap(const DeclContext &dc) {
Ted Kremenek610068c2011-01-15 02:58:47 +000060 unsigned count = 0;
61 DeclContext::specific_decl_iterator<VarDecl> I(dc.decls_begin()),
62 E(dc.decls_end());
63 for ( ; I != E; ++I) {
64 const VarDecl *vd = *I;
Ted Kremenek40900ee2011-01-27 02:29:34 +000065 if (isTrackedVar(vd, &dc))
Ted Kremenek610068c2011-01-15 02:58:47 +000066 map[vd] = count++;
67 }
68}
69
Ted Kremenekb831c672011-03-29 01:40:00 +000070llvm::Optional<unsigned> DeclToIndex::getValueIndex(const VarDecl *d) const {
71 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I = map.find(d);
Ted Kremenek610068c2011-01-15 02:58:47 +000072 if (I == map.end())
73 return llvm::Optional<unsigned>();
74 return I->second;
75}
76
77//------------------------------------------------------------------------====//
78// CFGBlockValues: dataflow values for CFG blocks.
79//====------------------------------------------------------------------------//
80
Ted Kremenekf7bafc72011-03-15 04:57:38 +000081// These values are defined in such a way that a merge can be done using
82// a bitwise OR.
83enum Value { Unknown = 0x0, /* 00 */
84 Initialized = 0x1, /* 01 */
85 Uninitialized = 0x2, /* 10 */
86 MayUninitialized = 0x3 /* 11 */ };
87
88static bool isUninitialized(const Value v) {
89 return v >= Uninitialized;
90}
91static bool isAlwaysUninit(const Value v) {
92 return v == Uninitialized;
93}
Ted Kremenekafb10c42011-03-15 04:57:29 +000094
Benjamin Kramerda57f3e2011-03-26 12:38:21 +000095namespace {
Ted Kremenek496398d2011-03-15 04:57:32 +000096
Argyrios Kyrtzidis049f6d02011-05-31 03:56:09 +000097typedef llvm::PackedVector<Value, 2> ValueVector;
Ted Kremenek136f8f22011-03-15 04:57:27 +000098typedef std::pair<ValueVector *, ValueVector *> BVPair;
Ted Kremenek13bd4232011-01-20 17:37:17 +000099
Ted Kremenek610068c2011-01-15 02:58:47 +0000100class CFGBlockValues {
101 const CFG &cfg;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000102 BVPair *vals;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000103 ValueVector scratch;
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000104 DeclToIndex declToIndex;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000105
Ted Kremenek136f8f22011-03-15 04:57:27 +0000106 ValueVector &lazyCreate(ValueVector *&bv);
Ted Kremenek610068c2011-01-15 02:58:47 +0000107public:
108 CFGBlockValues(const CFG &cfg);
109 ~CFGBlockValues();
110
Ted Kremenekd40066b2011-04-04 23:29:12 +0000111 unsigned getNumEntries() const { return declToIndex.size(); }
112
Ted Kremenek610068c2011-01-15 02:58:47 +0000113 void computeSetOfDeclarations(const DeclContext &dc);
Ted Kremenek136f8f22011-03-15 04:57:27 +0000114 ValueVector &getValueVector(const CFGBlock *block,
Ted Kremenek13bd4232011-01-20 17:37:17 +0000115 const CFGBlock *dstBlock);
116
Ted Kremenek136f8f22011-03-15 04:57:27 +0000117 BVPair &getValueVectors(const CFGBlock *block, bool shouldLazyCreate);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000118
Ted Kremenek136f8f22011-03-15 04:57:27 +0000119 void mergeIntoScratch(ValueVector const &source, bool isFirst);
120 bool updateValueVectorWithScratch(const CFGBlock *block);
121 bool updateValueVectors(const CFGBlock *block, const BVPair &newVals);
Ted Kremenek610068c2011-01-15 02:58:47 +0000122
123 bool hasNoDeclarations() const {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000124 return declToIndex.size() == 0;
Ted Kremenek610068c2011-01-15 02:58:47 +0000125 }
Ted Kremeneke0e29332011-08-20 01:15:28 +0000126
Ted Kremenek610068c2011-01-15 02:58:47 +0000127 void resetScratch();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000128 ValueVector &getScratch() { return scratch; }
Ted Kremenek13bd4232011-01-20 17:37:17 +0000129
Ted Kremenek136f8f22011-03-15 04:57:27 +0000130 ValueVector::reference operator[](const VarDecl *vd);
Ted Kremenek610068c2011-01-15 02:58:47 +0000131};
Benjamin Kramerda57f3e2011-03-26 12:38:21 +0000132} // end anonymous namespace
Ted Kremenek610068c2011-01-15 02:58:47 +0000133
134CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {
135 unsigned n = cfg.getNumBlockIDs();
136 if (!n)
137 return;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000138 vals = new std::pair<ValueVector*, ValueVector*>[n];
Chandler Carruth75c40642011-04-28 08:19:45 +0000139 memset((void*)vals, 0, sizeof(*vals) * n);
Ted Kremenek610068c2011-01-15 02:58:47 +0000140}
141
142CFGBlockValues::~CFGBlockValues() {
143 unsigned n = cfg.getNumBlockIDs();
144 if (n == 0)
145 return;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000146 for (unsigned i = 0; i < n; ++i) {
147 delete vals[i].first;
148 delete vals[i].second;
149 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000150 delete [] vals;
151}
152
153void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000154 declToIndex.computeMap(dc);
155 scratch.resize(declToIndex.size());
Ted Kremenek610068c2011-01-15 02:58:47 +0000156}
157
Ted Kremenek136f8f22011-03-15 04:57:27 +0000158ValueVector &CFGBlockValues::lazyCreate(ValueVector *&bv) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000159 if (!bv)
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000160 bv = new ValueVector(declToIndex.size());
Ted Kremenek610068c2011-01-15 02:58:47 +0000161 return *bv;
162}
163
Ted Kremenek13bd4232011-01-20 17:37:17 +0000164/// This function pattern matches for a '&&' or '||' that appears at
165/// the beginning of a CFGBlock that also (1) has a terminator and
166/// (2) has no other elements. If such an expression is found, it is returned.
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000167static const BinaryOperator *getLogicalOperatorInChain(const CFGBlock *block) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000168 if (block->empty())
169 return 0;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000170
Ted Kremenek3c0349e2011-03-01 03:15:10 +0000171 const CFGStmt *cstmt = block->front().getAs<CFGStmt>();
Ted Kremenek76709bf2011-03-15 05:22:28 +0000172 if (!cstmt)
173 return 0;
174
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000175 const BinaryOperator *b = dyn_cast_or_null<BinaryOperator>(cstmt->getStmt());
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000176
177 if (!b || !b->isLogicalOp())
Ted Kremenek13bd4232011-01-20 17:37:17 +0000178 return 0;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000179
Ted Kremeneke6c28032011-05-10 22:10:35 +0000180 if (block->pred_size() == 2) {
181 if (block->getTerminatorCondition() == b) {
182 if (block->succ_size() == 2)
183 return b;
184 }
185 else if (block->size() == 1)
186 return b;
187 }
188
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000189 return 0;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000190}
191
Ted Kremenek136f8f22011-03-15 04:57:27 +0000192ValueVector &CFGBlockValues::getValueVector(const CFGBlock *block,
193 const CFGBlock *dstBlock) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000194 unsigned idx = block->getBlockID();
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000195 if (dstBlock && getLogicalOperatorInChain(block)) {
196 if (*block->succ_begin() == dstBlock)
197 return lazyCreate(vals[idx].first);
198 assert(*(block->succ_begin()+1) == dstBlock);
199 return lazyCreate(vals[idx].second);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000200 }
201
202 assert(vals[idx].second == 0);
203 return lazyCreate(vals[idx].first);
204}
205
Ted Kremenek136f8f22011-03-15 04:57:27 +0000206BVPair &CFGBlockValues::getValueVectors(const clang::CFGBlock *block,
207 bool shouldLazyCreate) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000208 unsigned idx = block->getBlockID();
209 lazyCreate(vals[idx].first);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000210 if (shouldLazyCreate)
211 lazyCreate(vals[idx].second);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000212 return vals[idx];
213}
214
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000215#if 0
Ted Kremenek136f8f22011-03-15 04:57:27 +0000216static void printVector(const CFGBlock *block, ValueVector &bv,
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000217 unsigned num) {
218
219 llvm::errs() << block->getBlockID() << " :";
220 for (unsigned i = 0; i < bv.size(); ++i) {
221 llvm::errs() << ' ' << bv[i];
222 }
223 llvm::errs() << " : " << num << '\n';
224}
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000225
226static void printVector(const char *name, ValueVector const &bv) {
227 llvm::errs() << name << " : ";
228 for (unsigned i = 0; i < bv.size(); ++i) {
229 llvm::errs() << ' ' << bv[i];
230 }
231 llvm::errs() << "\n";
232}
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000233#endif
Ted Kremenek610068c2011-01-15 02:58:47 +0000234
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000235void CFGBlockValues::mergeIntoScratch(ValueVector const &source,
236 bool isFirst) {
237 if (isFirst)
238 scratch = source;
239 else
240 scratch |= source;
241}
242
Ted Kremenek136f8f22011-03-15 04:57:27 +0000243bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) {
244 ValueVector &dst = getValueVector(block, 0);
Ted Kremenek610068c2011-01-15 02:58:47 +0000245 bool changed = (dst != scratch);
246 if (changed)
247 dst = scratch;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000248#if 0
249 printVector(block, scratch, 0);
250#endif
Ted Kremenek13bd4232011-01-20 17:37:17 +0000251 return changed;
252}
253
Ted Kremenek136f8f22011-03-15 04:57:27 +0000254bool CFGBlockValues::updateValueVectors(const CFGBlock *block,
Ted Kremenek13bd4232011-01-20 17:37:17 +0000255 const BVPair &newVals) {
Ted Kremenek136f8f22011-03-15 04:57:27 +0000256 BVPair &vals = getValueVectors(block, true);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000257 bool changed = *newVals.first != *vals.first ||
258 *newVals.second != *vals.second;
259 *vals.first = *newVals.first;
260 *vals.second = *newVals.second;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000261#if 0
262 printVector(block, *vals.first, 1);
263 printVector(block, *vals.second, 2);
264#endif
Ted Kremenek610068c2011-01-15 02:58:47 +0000265 return changed;
266}
267
268void CFGBlockValues::resetScratch() {
269 scratch.reset();
270}
271
Ted Kremenek136f8f22011-03-15 04:57:27 +0000272ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000273 const llvm::Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
Ted Kremenek610068c2011-01-15 02:58:47 +0000274 assert(idx.hasValue());
275 return scratch[idx.getValue()];
276}
277
278//------------------------------------------------------------------------====//
279// Worklist: worklist for dataflow analysis.
280//====------------------------------------------------------------------------//
281
282namespace {
283class DataflowWorklist {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000284 SmallVector<const CFGBlock *, 20> worklist;
Ted Kremenek496398d2011-03-15 04:57:32 +0000285 llvm::BitVector enqueuedBlocks;
Ted Kremenek610068c2011-01-15 02:58:47 +0000286public:
287 DataflowWorklist(const CFG &cfg) : enqueuedBlocks(cfg.getNumBlockIDs()) {}
288
Ted Kremenek610068c2011-01-15 02:58:47 +0000289 void enqueueSuccessors(const CFGBlock *block);
290 const CFGBlock *dequeue();
Ted Kremenek610068c2011-01-15 02:58:47 +0000291};
292}
293
Ted Kremenek610068c2011-01-15 02:58:47 +0000294void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) {
Chandler Carruth80520502011-07-08 11:19:06 +0000295 unsigned OldWorklistSize = worklist.size();
Ted Kremenek610068c2011-01-15 02:58:47 +0000296 for (CFGBlock::const_succ_iterator I = block->succ_begin(),
297 E = block->succ_end(); I != E; ++I) {
Chandler Carruth80520502011-07-08 11:19:06 +0000298 const CFGBlock *Successor = *I;
299 if (!Successor || enqueuedBlocks[Successor->getBlockID()])
300 continue;
301 worklist.push_back(Successor);
302 enqueuedBlocks[Successor->getBlockID()] = true;
Ted Kremenek610068c2011-01-15 02:58:47 +0000303 }
Chandler Carruth80520502011-07-08 11:19:06 +0000304 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
305 return;
306
307 // Rotate the newly added blocks to the start of the worklist so that it forms
308 // a proper queue when we pop off the end of the worklist.
309 std::rotate(worklist.begin(), worklist.begin() + OldWorklistSize,
310 worklist.end());
Ted Kremenek610068c2011-01-15 02:58:47 +0000311}
312
313const CFGBlock *DataflowWorklist::dequeue() {
314 if (worklist.empty())
315 return 0;
316 const CFGBlock *b = worklist.back();
317 worklist.pop_back();
318 enqueuedBlocks[b->getBlockID()] = false;
319 return b;
320}
321
322//------------------------------------------------------------------------====//
323// Transfer function for uninitialized values analysis.
324//====------------------------------------------------------------------------//
325
Ted Kremenek610068c2011-01-15 02:58:47 +0000326namespace {
327class FindVarResult {
328 const VarDecl *vd;
329 const DeclRefExpr *dr;
330public:
331 FindVarResult(VarDecl *vd, DeclRefExpr *dr) : vd(vd), dr(dr) {}
332
333 const DeclRefExpr *getDeclRefExpr() const { return dr; }
334 const VarDecl *getDecl() const { return vd; }
335};
336
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000337class TransferFunctions : public StmtVisitor<TransferFunctions> {
Ted Kremenek610068c2011-01-15 02:58:47 +0000338 CFGBlockValues &vals;
339 const CFG &cfg;
Ted Kremenek1d26f482011-10-24 01:32:45 +0000340 AnalysisDeclContext &ac;
Ted Kremenek610068c2011-01-15 02:58:47 +0000341 UninitVariablesHandler *handler;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000342
343 /// The last DeclRefExpr seen when analyzing a block. Used to
344 /// cheat when detecting cases when the address of a variable is taken.
345 DeclRefExpr *lastDR;
346
347 /// The last lvalue-to-rvalue conversion of a variable whose value
348 /// was uninitialized. Normally this results in a warning, but it is
349 /// possible to either silence the warning in some cases, or we
350 /// propagate the uninitialized value.
351 CastExpr *lastLoad;
Ted Kremenek57fb5912011-08-04 22:40:57 +0000352
353 /// For some expressions, we want to ignore any post-processing after
354 /// visitation.
355 bool skipProcessUses;
356
Ted Kremenek610068c2011-01-15 02:58:47 +0000357public:
358 TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000359 AnalysisDeclContext &ac,
Ted Kremenek6f275422011-09-02 19:39:26 +0000360 UninitVariablesHandler *handler)
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000361 : vals(vals), cfg(cfg), ac(ac), handler(handler),
Ted Kremenek6f275422011-09-02 19:39:26 +0000362 lastDR(0), lastLoad(0),
Ted Kremenek57fb5912011-08-04 22:40:57 +0000363 skipProcessUses(false) {}
Ted Kremenek610068c2011-01-15 02:58:47 +0000364
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000365 void reportUninit(const DeclRefExpr *ex, const VarDecl *vd,
366 bool isAlwaysUninit);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000367
368 void VisitBlockExpr(BlockExpr *be);
Ted Kremenek610068c2011-01-15 02:58:47 +0000369 void VisitDeclStmt(DeclStmt *ds);
Ted Kremenekc21fed32011-01-18 21:18:58 +0000370 void VisitDeclRefExpr(DeclRefExpr *dr);
Ted Kremenek610068c2011-01-15 02:58:47 +0000371 void VisitUnaryOperator(UnaryOperator *uo);
372 void VisitBinaryOperator(BinaryOperator *bo);
373 void VisitCastExpr(CastExpr *ce);
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000374 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs);
375 void Visit(Stmt *s);
Ted Kremenek40900ee2011-01-27 02:29:34 +0000376
377 bool isTrackedVar(const VarDecl *vd) {
378 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl()));
379 }
380
381 FindVarResult findBlockVarDecl(Expr *ex);
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000382
383 void ProcessUses(Stmt *s = 0);
Ted Kremenek610068c2011-01-15 02:58:47 +0000384};
385}
386
Ted Kremenekde091ae2011-08-08 21:43:08 +0000387static const Expr *stripCasts(ASTContext &C, const Expr *Ex) {
388 while (Ex) {
389 Ex = Ex->IgnoreParenNoopCasts(C);
390 if (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
391 if (CE->getCastKind() == CK_LValueBitCast) {
392 Ex = CE->getSubExpr();
393 continue;
394 }
395 }
396 break;
397 }
398 return Ex;
399}
400
Ted Kremenek610068c2011-01-15 02:58:47 +0000401void TransferFunctions::reportUninit(const DeclRefExpr *ex,
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000402 const VarDecl *vd, bool isAlwaysUnit) {
403 if (handler) handler->handleUseOfUninitVariable(ex, vd, isAlwaysUnit);
Ted Kremenek610068c2011-01-15 02:58:47 +0000404}
405
Ted Kremenek9c378f72011-08-12 23:37:29 +0000406FindVarResult TransferFunctions::findBlockVarDecl(Expr *ex) {
407 if (DeclRefExpr *dr = dyn_cast<DeclRefExpr>(ex->IgnoreParenCasts()))
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000408 if (VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
409 if (isTrackedVar(vd))
Ted Kremenek40900ee2011-01-27 02:29:34 +0000410 return FindVarResult(vd, dr);
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000411 return FindVarResult(0, 0);
412}
413
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000414void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs) {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000415 // This represents an initialization of the 'element' value.
416 Stmt *element = fs->getElement();
Ted Kremenek9c378f72011-08-12 23:37:29 +0000417 const VarDecl *vd = 0;
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000418
Ted Kremenek9c378f72011-08-12 23:37:29 +0000419 if (DeclStmt *ds = dyn_cast<DeclStmt>(element)) {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000420 vd = cast<VarDecl>(ds->getSingleDecl());
421 if (!isTrackedVar(vd))
422 vd = 0;
Chad Rosier30601782011-08-17 23:08:45 +0000423 } else {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000424 // Initialize the value of the reference variable.
425 const FindVarResult &res = findBlockVarDecl(cast<Expr>(element));
426 vd = res.getDecl();
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000427 }
428
429 if (vd)
430 vals[vd] = Initialized;
431}
432
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000433void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000434 const BlockDecl *bd = be->getBlockDecl();
435 for (BlockDecl::capture_const_iterator i = bd->capture_begin(),
436 e = bd->capture_end() ; i != e; ++i) {
437 const VarDecl *vd = i->getVariable();
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000438 if (!isTrackedVar(vd))
439 continue;
440 if (i->isByRef()) {
441 vals[vd] = Initialized;
442 continue;
443 }
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000444 Value v = vals[vd];
Ted Kremenek6f275422011-09-02 19:39:26 +0000445 if (handler && isUninitialized(v))
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000446 handler->handleUseOfUninitVariable(be, vd, isAlwaysUninit(v));
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000447 }
448}
449
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000450void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
451 // Record the last DeclRefExpr seen. This is an lvalue computation.
452 // We use this value to later detect if a variable "escapes" the analysis.
453 if (const VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
Ted Kremenekdd4286b2011-07-20 19:49:47 +0000454 if (isTrackedVar(vd)) {
455 ProcessUses();
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000456 lastDR = dr;
Ted Kremenekdd4286b2011-07-20 19:49:47 +0000457 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000458}
459
Ted Kremenek610068c2011-01-15 02:58:47 +0000460void TransferFunctions::VisitDeclStmt(DeclStmt *ds) {
461 for (DeclStmt::decl_iterator DI = ds->decl_begin(), DE = ds->decl_end();
462 DI != DE; ++DI) {
463 if (VarDecl *vd = dyn_cast<VarDecl>(*DI)) {
Ted Kremenek4dccb902011-01-18 05:00:42 +0000464 if (isTrackedVar(vd)) {
Chandler Carruthb88fb022011-04-05 21:36:30 +0000465 if (Expr *init = vd->getInit()) {
Chandler Carruthb88fb022011-04-05 21:36:30 +0000466 // If the initializer consists solely of a reference to itself, we
467 // explicitly mark the variable as uninitialized. This allows code
468 // like the following:
469 //
470 // int x = x;
471 //
472 // to deliberately leave a variable uninitialized. Different analysis
473 // clients can detect this pattern and adjust their reporting
474 // appropriately, but we need to continue to analyze subsequent uses
475 // of the variable.
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000476 if (init == lastLoad) {
Ted Kremenekde091ae2011-08-08 21:43:08 +0000477 const DeclRefExpr *DR
478 = cast<DeclRefExpr>(stripCasts(ac.getASTContext(),
479 lastLoad->getSubExpr()));
Ted Kremenek62d126e2011-07-19 21:41:51 +0000480 if (DR->getDecl() == vd) {
481 // int x = x;
482 // Propagate uninitialized value, but don't immediately report
483 // a problem.
484 vals[vd] = Uninitialized;
485 lastLoad = 0;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000486 lastDR = 0;
Ted Kremenek9e761722011-10-13 18:50:06 +0000487 if (handler)
488 handler->handleSelfInit(vd);
Ted Kremenek62d126e2011-07-19 21:41:51 +0000489 return;
490 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000491 }
Ted Kremenek62d126e2011-07-19 21:41:51 +0000492
493 // All other cases: treat the new variable as initialized.
Ted Kremenek9e761722011-10-13 18:50:06 +0000494 // This is a minor optimization to reduce the propagation
495 // of the analysis, since we will have already reported
496 // the use of the uninitialized value (which visiting the
497 // initializer).
Ted Kremenek62d126e2011-07-19 21:41:51 +0000498 vals[vd] = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000499 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000500 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000501 }
502 }
503}
504
Ted Kremenek610068c2011-01-15 02:58:47 +0000505void TransferFunctions::VisitBinaryOperator(clang::BinaryOperator *bo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000506 if (bo->isAssignmentOp()) {
507 const FindVarResult &res = findBlockVarDecl(bo->getLHS());
Ted Kremenek9c378f72011-08-12 23:37:29 +0000508 if (const VarDecl *vd = res.getDecl()) {
Ted Kremenek496398d2011-03-15 04:57:32 +0000509 ValueVector::reference val = vals[vd];
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000510 if (isUninitialized(val)) {
Chandler Carruth84350692011-07-16 22:27:02 +0000511 if (bo->getOpcode() != BO_Assign)
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000512 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
Chandler Carruthd837c0d2011-07-22 05:27:52 +0000513 else
514 val = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000515 }
516 }
517 }
518}
519
520void TransferFunctions::VisitUnaryOperator(clang::UnaryOperator *uo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000521 switch (uo->getOpcode()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000522 case clang::UO_PostDec:
523 case clang::UO_PostInc:
524 case clang::UO_PreDec:
525 case clang::UO_PreInc: {
526 const FindVarResult &res = findBlockVarDecl(uo->getSubExpr());
527 if (const VarDecl *vd = res.getDecl()) {
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000528 assert(res.getDeclRefExpr() == lastDR);
529 // We null out lastDR to indicate we have fully processed it
530 // and we don't want the auto-value setting in Visit().
531 lastDR = 0;
Ted Kremenekc21fed32011-01-18 21:18:58 +0000532
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000533 ValueVector::reference val = vals[vd];
Chandler Carruthd837c0d2011-07-22 05:27:52 +0000534 if (isUninitialized(val))
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000535 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
Ted Kremenek610068c2011-01-15 02:58:47 +0000536 }
537 break;
538 }
539 default:
540 break;
541 }
542}
543
544void TransferFunctions::VisitCastExpr(clang::CastExpr *ce) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000545 if (ce->getCastKind() == CK_LValueToRValue) {
546 const FindVarResult &res = findBlockVarDecl(ce->getSubExpr());
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000547 if (res.getDecl()) {
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000548 assert(res.getDeclRefExpr() == lastDR);
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000549 lastLoad = ce;
Ted Kremenekc21fed32011-01-18 21:18:58 +0000550 }
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000551 }
Ted Kremenekde091ae2011-08-08 21:43:08 +0000552 else if (ce->getCastKind() == CK_NoOp ||
553 ce->getCastKind() == CK_LValueBitCast) {
Ted Kremenek57fb5912011-08-04 22:40:57 +0000554 skipProcessUses = true;
555 }
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000556 else if (CStyleCastExpr *cse = dyn_cast<CStyleCastExpr>(ce)) {
557 if (cse->getType()->isVoidType()) {
558 // e.g. (void) x;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000559 if (lastLoad == cse->getSubExpr()) {
560 // Squelch any detected load of an uninitialized value if
561 // we cast it to void.
562 lastLoad = 0;
563 lastDR = 0;
564 }
565 }
566 }
567}
568
569void TransferFunctions::Visit(clang::Stmt *s) {
Ted Kremenek57fb5912011-08-04 22:40:57 +0000570 skipProcessUses = false;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000571 StmtVisitor<TransferFunctions>::Visit(s);
Ted Kremenek57fb5912011-08-04 22:40:57 +0000572 if (!skipProcessUses)
573 ProcessUses(s);
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000574}
575
576void TransferFunctions::ProcessUses(Stmt *s) {
577 // This method is typically called after visiting a CFGElement statement
578 // in the CFG. We delay processing of reporting many loads of uninitialized
579 // values until here.
580 if (lastLoad) {
581 // If we just visited the lvalue-to-rvalue cast, there is nothing
582 // left to do.
583 if (lastLoad == s)
584 return;
585
Ted Kremenekde091ae2011-08-08 21:43:08 +0000586 const DeclRefExpr *DR =
587 cast<DeclRefExpr>(stripCasts(ac.getASTContext(),
588 lastLoad->getSubExpr()));
589 const VarDecl *VD = cast<VarDecl>(DR->getDecl());
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000590
591 // If we reach here, we may have seen a load of an uninitialized value
592 // and it hasn't been casted to void or otherwise handled. In this
593 // situation, report the incident.
594 if (isUninitialized(vals[VD]))
595 reportUninit(DR, VD, isAlwaysUninit(vals[VD]));
596
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000597 lastLoad = 0;
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000598
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000599 if (DR == lastDR) {
600 lastDR = 0;
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000601 return;
602 }
603 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000604
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000605 // Any other uses of 'lastDR' involve taking an lvalue of variable.
606 // In this case, it "escapes" the analysis.
607 if (lastDR && lastDR != s) {
608 vals[cast<VarDecl>(lastDR->getDecl())] = Initialized;
609 lastDR = 0;
Chandler Carruth86684942011-04-13 08:18:42 +0000610 }
611}
612
Ted Kremenek610068c2011-01-15 02:58:47 +0000613//------------------------------------------------------------------------====//
614// High-level "driver" logic for uninitialized values analysis.
615//====------------------------------------------------------------------------//
616
Ted Kremenek13bd4232011-01-20 17:37:17 +0000617static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000618 AnalysisDeclContext &ac, CFGBlockValues &vals,
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000619 llvm::BitVector &wasAnalyzed,
Ted Kremenek6f275422011-09-02 19:39:26 +0000620 UninitVariablesHandler *handler = 0) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000621
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000622 wasAnalyzed[block->getBlockID()] = true;
623
Ted Kremenek13bd4232011-01-20 17:37:17 +0000624 if (const BinaryOperator *b = getLogicalOperatorInChain(block)) {
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000625 CFGBlock::const_pred_iterator itr = block->pred_begin();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000626 BVPair vA = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000627 ++itr;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000628 BVPair vB = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000629
630 BVPair valsAB;
631
632 if (b->getOpcode() == BO_LAnd) {
633 // Merge the 'F' bits from the first and second.
634 vals.mergeIntoScratch(*(vA.second ? vA.second : vA.first), true);
635 vals.mergeIntoScratch(*(vB.second ? vB.second : vB.first), false);
636 valsAB.first = vA.first;
Ted Kremenek2d4bed12011-01-20 21:25:31 +0000637 valsAB.second = &vals.getScratch();
Chad Rosier30601782011-08-17 23:08:45 +0000638 } else {
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000639 // Merge the 'T' bits from the first and second.
640 assert(b->getOpcode() == BO_LOr);
641 vals.mergeIntoScratch(*vA.first, true);
642 vals.mergeIntoScratch(*vB.first, false);
643 valsAB.first = &vals.getScratch();
644 valsAB.second = vA.second ? vA.second : vA.first;
645 }
Ted Kremenek136f8f22011-03-15 04:57:27 +0000646 return vals.updateValueVectors(block, valsAB);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000647 }
648
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000649 // Default behavior: merge in values of predecessor blocks.
Ted Kremenek610068c2011-01-15 02:58:47 +0000650 vals.resetScratch();
651 bool isFirst = true;
652 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
653 E = block->pred_end(); I != E; ++I) {
Ted Kremenek6f275422011-09-02 19:39:26 +0000654 const CFGBlock *pred = *I;
655 if (wasAnalyzed[pred->getBlockID()]) {
656 vals.mergeIntoScratch(vals.getValueVector(pred, block), isFirst);
657 isFirst = false;
658 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000659 }
660 // Apply the transfer function.
Ted Kremenek6f275422011-09-02 19:39:26 +0000661 TransferFunctions tf(vals, cfg, ac, handler);
Ted Kremenek610068c2011-01-15 02:58:47 +0000662 for (CFGBlock::const_iterator I = block->begin(), E = block->end();
663 I != E; ++I) {
664 if (const CFGStmt *cs = dyn_cast<CFGStmt>(&*I)) {
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000665 tf.Visit(const_cast<Stmt*>(cs->getStmt()));
Ted Kremenek610068c2011-01-15 02:58:47 +0000666 }
667 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000668 tf.ProcessUses();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000669 return vals.updateValueVectorWithScratch(block);
Ted Kremenek610068c2011-01-15 02:58:47 +0000670}
671
Chandler Carruth5d989942011-07-06 16:21:37 +0000672void clang::runUninitializedVariablesAnalysis(
673 const DeclContext &dc,
674 const CFG &cfg,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000675 AnalysisDeclContext &ac,
Chandler Carruth5d989942011-07-06 16:21:37 +0000676 UninitVariablesHandler &handler,
677 UninitVariablesAnalysisStats &stats) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000678 CFGBlockValues vals(cfg);
679 vals.computeSetOfDeclarations(dc);
680 if (vals.hasNoDeclarations())
681 return;
Ted Kremenekd40066b2011-04-04 23:29:12 +0000682
Chandler Carruth5d989942011-07-06 16:21:37 +0000683 stats.NumVariablesAnalyzed = vals.getNumEntries();
684
Ted Kremenekd40066b2011-04-04 23:29:12 +0000685 // Mark all variables uninitialized at the entry.
686 const CFGBlock &entry = cfg.getEntry();
687 for (CFGBlock::const_succ_iterator i = entry.succ_begin(),
688 e = entry.succ_end(); i != e; ++i) {
689 if (const CFGBlock *succ = *i) {
690 ValueVector &vec = vals.getValueVector(&entry, succ);
691 const unsigned n = vals.getNumEntries();
692 for (unsigned j = 0; j < n ; ++j) {
693 vec[j] = Uninitialized;
694 }
695 }
696 }
697
698 // Proceed with the workist.
Ted Kremenek610068c2011-01-15 02:58:47 +0000699 DataflowWorklist worklist(cfg);
Ted Kremenek496398d2011-03-15 04:57:32 +0000700 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
Ted Kremenek610068c2011-01-15 02:58:47 +0000701 worklist.enqueueSuccessors(&cfg.getEntry());
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000702 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
Ted Kremenek6f275422011-09-02 19:39:26 +0000703 wasAnalyzed[cfg.getEntry().getBlockID()] = true;
Ted Kremenek610068c2011-01-15 02:58:47 +0000704
705 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000706 // Did the block change?
Chandler Carruth5d989942011-07-06 16:21:37 +0000707 bool changed = runOnBlock(block, cfg, ac, vals, wasAnalyzed);
708 ++stats.NumBlockVisits;
Ted Kremenek610068c2011-01-15 02:58:47 +0000709 if (changed || !previouslyVisited[block->getBlockID()])
710 worklist.enqueueSuccessors(block);
711 previouslyVisited[block->getBlockID()] = true;
712 }
713
714 // Run through the blocks one more time, and report uninitialized variabes.
715 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) {
Ted Kremenek6f275422011-09-02 19:39:26 +0000716 const CFGBlock *block = *BI;
717 if (wasAnalyzed[block->getBlockID()]) {
718 runOnBlock(block, cfg, ac, vals, wasAnalyzed, &handler);
Chandler Carruth5d989942011-07-06 16:21:37 +0000719 ++stats.NumBlockVisits;
720 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000721 }
722}
723
724UninitVariablesHandler::~UninitVariablesHandler() {}