blob: c1b9a96f03a4187abc7d742398b4f0a102503e76 [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"
Argyrios Kyrtzidisb2c60b02012-03-01 19:45:56 +000024#include "llvm/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) {
David Blaikie262bc182012-04-30 02:36:29 +000064 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,
Richard Smith81891882012-05-24 23:45:35 +0000115 const CFGBlock *dstBlock);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000116
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
Richard Smithb86b8552012-04-30 00:16:51 +0000171 CFGElement front = block->front();
172 const CFGStmt *cstmt = front.getAs<CFGStmt>();
Ted Kremenek76709bf2011-03-15 05:22:28 +0000173 if (!cstmt)
174 return 0;
175
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000176 const BinaryOperator *b = dyn_cast_or_null<BinaryOperator>(cstmt->getStmt());
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000177
178 if (!b || !b->isLogicalOp())
Ted Kremenek13bd4232011-01-20 17:37:17 +0000179 return 0;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000180
Ted Kremeneke6c28032011-05-10 22:10:35 +0000181 if (block->pred_size() == 2) {
182 if (block->getTerminatorCondition() == b) {
183 if (block->succ_size() == 2)
184 return b;
185 }
186 else if (block->size() == 1)
187 return b;
188 }
189
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000190 return 0;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000191}
192
Ted Kremenek136f8f22011-03-15 04:57:27 +0000193ValueVector &CFGBlockValues::getValueVector(const CFGBlock *block,
194 const CFGBlock *dstBlock) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000195 unsigned idx = block->getBlockID();
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000196 if (dstBlock && getLogicalOperatorInChain(block)) {
197 if (*block->succ_begin() == dstBlock)
198 return lazyCreate(vals[idx].first);
199 assert(*(block->succ_begin()+1) == dstBlock);
200 return lazyCreate(vals[idx].second);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000201 }
202
203 assert(vals[idx].second == 0);
204 return lazyCreate(vals[idx].first);
205}
206
Ted Kremenek136f8f22011-03-15 04:57:27 +0000207BVPair &CFGBlockValues::getValueVectors(const clang::CFGBlock *block,
208 bool shouldLazyCreate) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000209 unsigned idx = block->getBlockID();
210 lazyCreate(vals[idx].first);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000211 if (shouldLazyCreate)
212 lazyCreate(vals[idx].second);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000213 return vals[idx];
214}
215
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000216#if 0
Ted Kremenek136f8f22011-03-15 04:57:27 +0000217static void printVector(const CFGBlock *block, ValueVector &bv,
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000218 unsigned num) {
219
220 llvm::errs() << block->getBlockID() << " :";
221 for (unsigned i = 0; i < bv.size(); ++i) {
222 llvm::errs() << ' ' << bv[i];
223 }
224 llvm::errs() << " : " << num << '\n';
225}
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000226
227static void printVector(const char *name, ValueVector const &bv) {
228 llvm::errs() << name << " : ";
229 for (unsigned i = 0; i < bv.size(); ++i) {
230 llvm::errs() << ' ' << bv[i];
231 }
232 llvm::errs() << "\n";
233}
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000234#endif
Ted Kremenek610068c2011-01-15 02:58:47 +0000235
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000236void CFGBlockValues::mergeIntoScratch(ValueVector const &source,
237 bool isFirst) {
238 if (isFirst)
239 scratch = source;
240 else
241 scratch |= source;
242}
243
Ted Kremenek136f8f22011-03-15 04:57:27 +0000244bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) {
245 ValueVector &dst = getValueVector(block, 0);
Ted Kremenek610068c2011-01-15 02:58:47 +0000246 bool changed = (dst != scratch);
247 if (changed)
248 dst = scratch;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000249#if 0
250 printVector(block, scratch, 0);
251#endif
Ted Kremenek13bd4232011-01-20 17:37:17 +0000252 return changed;
253}
254
Ted Kremenek136f8f22011-03-15 04:57:27 +0000255bool CFGBlockValues::updateValueVectors(const CFGBlock *block,
Ted Kremenek13bd4232011-01-20 17:37:17 +0000256 const BVPair &newVals) {
Ted Kremenek136f8f22011-03-15 04:57:27 +0000257 BVPair &vals = getValueVectors(block, true);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000258 bool changed = *newVals.first != *vals.first ||
259 *newVals.second != *vals.second;
260 *vals.first = *newVals.first;
261 *vals.second = *newVals.second;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000262#if 0
263 printVector(block, *vals.first, 1);
264 printVector(block, *vals.second, 2);
265#endif
Ted Kremenek610068c2011-01-15 02:58:47 +0000266 return changed;
267}
268
269void CFGBlockValues::resetScratch() {
270 scratch.reset();
271}
272
Ted Kremenek136f8f22011-03-15 04:57:27 +0000273ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000274 const llvm::Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
Ted Kremenek610068c2011-01-15 02:58:47 +0000275 assert(idx.hasValue());
276 return scratch[idx.getValue()];
277}
278
279//------------------------------------------------------------------------====//
280// Worklist: worklist for dataflow analysis.
281//====------------------------------------------------------------------------//
282
283namespace {
284class DataflowWorklist {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000285 SmallVector<const CFGBlock *, 20> worklist;
Ted Kremenek496398d2011-03-15 04:57:32 +0000286 llvm::BitVector enqueuedBlocks;
Ted Kremenek610068c2011-01-15 02:58:47 +0000287public:
288 DataflowWorklist(const CFG &cfg) : enqueuedBlocks(cfg.getNumBlockIDs()) {}
289
Ted Kremenek610068c2011-01-15 02:58:47 +0000290 void enqueueSuccessors(const CFGBlock *block);
291 const CFGBlock *dequeue();
Ted Kremenek610068c2011-01-15 02:58:47 +0000292};
293}
294
Ted Kremenek610068c2011-01-15 02:58:47 +0000295void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) {
Chandler Carruth80520502011-07-08 11:19:06 +0000296 unsigned OldWorklistSize = worklist.size();
Ted Kremenek610068c2011-01-15 02:58:47 +0000297 for (CFGBlock::const_succ_iterator I = block->succ_begin(),
298 E = block->succ_end(); I != E; ++I) {
Chandler Carruth80520502011-07-08 11:19:06 +0000299 const CFGBlock *Successor = *I;
300 if (!Successor || enqueuedBlocks[Successor->getBlockID()])
301 continue;
302 worklist.push_back(Successor);
303 enqueuedBlocks[Successor->getBlockID()] = true;
Ted Kremenek610068c2011-01-15 02:58:47 +0000304 }
Chandler Carruth80520502011-07-08 11:19:06 +0000305 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
306 return;
307
308 // Rotate the newly added blocks to the start of the worklist so that it forms
309 // a proper queue when we pop off the end of the worklist.
310 std::rotate(worklist.begin(), worklist.begin() + OldWorklistSize,
311 worklist.end());
Ted Kremenek610068c2011-01-15 02:58:47 +0000312}
313
314const CFGBlock *DataflowWorklist::dequeue() {
315 if (worklist.empty())
316 return 0;
317 const CFGBlock *b = worklist.back();
318 worklist.pop_back();
319 enqueuedBlocks[b->getBlockID()] = false;
320 return b;
321}
322
323//------------------------------------------------------------------------====//
324// Transfer function for uninitialized values analysis.
325//====------------------------------------------------------------------------//
326
Ted Kremenek610068c2011-01-15 02:58:47 +0000327namespace {
328class FindVarResult {
329 const VarDecl *vd;
330 const DeclRefExpr *dr;
331public:
332 FindVarResult(VarDecl *vd, DeclRefExpr *dr) : vd(vd), dr(dr) {}
333
334 const DeclRefExpr *getDeclRefExpr() const { return dr; }
335 const VarDecl *getDecl() const { return vd; }
336};
337
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000338class TransferFunctions : public StmtVisitor<TransferFunctions> {
Ted Kremenek610068c2011-01-15 02:58:47 +0000339 CFGBlockValues &vals;
340 const CFG &cfg;
Ted Kremenek1d26f482011-10-24 01:32:45 +0000341 AnalysisDeclContext &ac;
Ted Kremenek610068c2011-01-15 02:58:47 +0000342 UninitVariablesHandler *handler;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000343
344 /// The last DeclRefExpr seen when analyzing a block. Used to
345 /// cheat when detecting cases when the address of a variable is taken.
346 DeclRefExpr *lastDR;
347
348 /// The last lvalue-to-rvalue conversion of a variable whose value
349 /// was uninitialized. Normally this results in a warning, but it is
350 /// possible to either silence the warning in some cases, or we
351 /// propagate the uninitialized value.
352 CastExpr *lastLoad;
Ted Kremenek57fb5912011-08-04 22:40:57 +0000353
354 /// For some expressions, we want to ignore any post-processing after
355 /// visitation.
356 bool skipProcessUses;
357
Ted Kremenek610068c2011-01-15 02:58:47 +0000358public:
359 TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000360 AnalysisDeclContext &ac,
Ted Kremenek6f275422011-09-02 19:39:26 +0000361 UninitVariablesHandler *handler)
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000362 : vals(vals), cfg(cfg), ac(ac), handler(handler),
Ted Kremenek6f275422011-09-02 19:39:26 +0000363 lastDR(0), lastLoad(0),
Ted Kremenek57fb5912011-08-04 22:40:57 +0000364 skipProcessUses(false) {}
Ted Kremenek610068c2011-01-15 02:58:47 +0000365
Richard Smith81891882012-05-24 23:45:35 +0000366 void reportUse(const Expr *ex, const VarDecl *vd);
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
Richard Smith81891882012-05-24 23:45:35 +0000401void TransferFunctions::reportUse(const Expr *ex, const VarDecl *vd) {
402 if (!handler)
403 return;
404 Value v = vals[vd];
405 if (isUninitialized(v))
406 handler->handleUseOfUninitVariable(ex, vd, isAlwaysUninit(v));
Ted Kremenek610068c2011-01-15 02:58:47 +0000407}
408
Ted Kremenek9c378f72011-08-12 23:37:29 +0000409FindVarResult TransferFunctions::findBlockVarDecl(Expr *ex) {
410 if (DeclRefExpr *dr = dyn_cast<DeclRefExpr>(ex->IgnoreParenCasts()))
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000411 if (VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
412 if (isTrackedVar(vd))
Ted Kremenek40900ee2011-01-27 02:29:34 +0000413 return FindVarResult(vd, dr);
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000414 return FindVarResult(0, 0);
415}
416
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000417void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs) {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000418 // This represents an initialization of the 'element' value.
419 Stmt *element = fs->getElement();
Ted Kremenek9c378f72011-08-12 23:37:29 +0000420 const VarDecl *vd = 0;
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000421
Ted Kremenek9c378f72011-08-12 23:37:29 +0000422 if (DeclStmt *ds = dyn_cast<DeclStmt>(element)) {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000423 vd = cast<VarDecl>(ds->getSingleDecl());
424 if (!isTrackedVar(vd))
425 vd = 0;
Chad Rosier30601782011-08-17 23:08:45 +0000426 } else {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000427 // Initialize the value of the reference variable.
428 const FindVarResult &res = findBlockVarDecl(cast<Expr>(element));
429 vd = res.getDecl();
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000430 }
431
432 if (vd)
433 vals[vd] = Initialized;
434}
435
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000436void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000437 const BlockDecl *bd = be->getBlockDecl();
438 for (BlockDecl::capture_const_iterator i = bd->capture_begin(),
439 e = bd->capture_end() ; i != e; ++i) {
440 const VarDecl *vd = i->getVariable();
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000441 if (!isTrackedVar(vd))
442 continue;
443 if (i->isByRef()) {
444 vals[vd] = Initialized;
445 continue;
446 }
Richard Smith81891882012-05-24 23:45:35 +0000447 reportUse(be, vd);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000448 }
449}
450
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000451void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
452 // Record the last DeclRefExpr seen. This is an lvalue computation.
453 // We use this value to later detect if a variable "escapes" the analysis.
454 if (const VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
Ted Kremenekdd4286b2011-07-20 19:49:47 +0000455 if (isTrackedVar(vd)) {
456 ProcessUses();
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000457 lastDR = dr;
Ted Kremenekdd4286b2011-07-20 19:49:47 +0000458 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000459}
460
Ted Kremenek610068c2011-01-15 02:58:47 +0000461void TransferFunctions::VisitDeclStmt(DeclStmt *ds) {
462 for (DeclStmt::decl_iterator DI = ds->decl_begin(), DE = ds->decl_end();
463 DI != DE; ++DI) {
464 if (VarDecl *vd = dyn_cast<VarDecl>(*DI)) {
Ted Kremenek4dccb902011-01-18 05:00:42 +0000465 if (isTrackedVar(vd)) {
Chandler Carruthb88fb022011-04-05 21:36:30 +0000466 if (Expr *init = vd->getInit()) {
Chandler Carruthb88fb022011-04-05 21:36:30 +0000467 // If the initializer consists solely of a reference to itself, we
468 // explicitly mark the variable as uninitialized. This allows code
469 // like the following:
470 //
471 // int x = x;
472 //
473 // to deliberately leave a variable uninitialized. Different analysis
474 // clients can detect this pattern and adjust their reporting
475 // appropriately, but we need to continue to analyze subsequent uses
476 // of the variable.
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000477 if (init == lastLoad) {
Ted Kremenekde091ae2011-08-08 21:43:08 +0000478 const DeclRefExpr *DR
479 = cast<DeclRefExpr>(stripCasts(ac.getASTContext(),
480 lastLoad->getSubExpr()));
Ted Kremenek62d126e2011-07-19 21:41:51 +0000481 if (DR->getDecl() == vd) {
482 // int x = x;
483 // Propagate uninitialized value, but don't immediately report
484 // a problem.
485 vals[vd] = Uninitialized;
486 lastLoad = 0;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000487 lastDR = 0;
Ted Kremenek9e761722011-10-13 18:50:06 +0000488 if (handler)
489 handler->handleSelfInit(vd);
Ted Kremenek62d126e2011-07-19 21:41:51 +0000490 return;
491 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000492 }
Ted Kremenek62d126e2011-07-19 21:41:51 +0000493
494 // All other cases: treat the new variable as initialized.
Ted Kremenek9e761722011-10-13 18:50:06 +0000495 // This is a minor optimization to reduce the propagation
496 // of the analysis, since we will have already reported
497 // the use of the uninitialized value (which visiting the
498 // initializer).
Ted Kremenek62d126e2011-07-19 21:41:51 +0000499 vals[vd] = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000500 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000501 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000502 }
503 }
504}
505
Ted Kremenek610068c2011-01-15 02:58:47 +0000506void TransferFunctions::VisitBinaryOperator(clang::BinaryOperator *bo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000507 if (bo->isAssignmentOp()) {
508 const FindVarResult &res = findBlockVarDecl(bo->getLHS());
Ted Kremenek9c378f72011-08-12 23:37:29 +0000509 if (const VarDecl *vd = res.getDecl()) {
Richard Smith81891882012-05-24 23:45:35 +0000510 if (bo->getOpcode() != BO_Assign)
511 reportUse(res.getDeclRefExpr(), vd);
512 else
513 vals[vd] = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000514 }
515 }
516}
517
518void TransferFunctions::VisitUnaryOperator(clang::UnaryOperator *uo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000519 switch (uo->getOpcode()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000520 case clang::UO_PostDec:
521 case clang::UO_PostInc:
522 case clang::UO_PreDec:
523 case clang::UO_PreInc: {
524 const FindVarResult &res = findBlockVarDecl(uo->getSubExpr());
525 if (const VarDecl *vd = res.getDecl()) {
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000526 assert(res.getDeclRefExpr() == lastDR);
527 // We null out lastDR to indicate we have fully processed it
528 // and we don't want the auto-value setting in Visit().
529 lastDR = 0;
Richard Smith81891882012-05-24 23:45:35 +0000530 reportUse(res.getDeclRefExpr(), vd);
Ted Kremenek610068c2011-01-15 02:58:47 +0000531 }
532 break;
533 }
534 default:
535 break;
536 }
537}
538
539void TransferFunctions::VisitCastExpr(clang::CastExpr *ce) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000540 if (ce->getCastKind() == CK_LValueToRValue) {
541 const FindVarResult &res = findBlockVarDecl(ce->getSubExpr());
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000542 if (res.getDecl()) {
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000543 assert(res.getDeclRefExpr() == lastDR);
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000544 lastLoad = ce;
Ted Kremenekc21fed32011-01-18 21:18:58 +0000545 }
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000546 }
Ted Kremenekde091ae2011-08-08 21:43:08 +0000547 else if (ce->getCastKind() == CK_NoOp ||
548 ce->getCastKind() == CK_LValueBitCast) {
Ted Kremenek57fb5912011-08-04 22:40:57 +0000549 skipProcessUses = true;
550 }
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000551 else if (CStyleCastExpr *cse = dyn_cast<CStyleCastExpr>(ce)) {
552 if (cse->getType()->isVoidType()) {
553 // e.g. (void) x;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000554 if (lastLoad == cse->getSubExpr()) {
555 // Squelch any detected load of an uninitialized value if
556 // we cast it to void.
557 lastLoad = 0;
558 lastDR = 0;
559 }
560 }
561 }
562}
563
564void TransferFunctions::Visit(clang::Stmt *s) {
Ted Kremenek57fb5912011-08-04 22:40:57 +0000565 skipProcessUses = false;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000566 StmtVisitor<TransferFunctions>::Visit(s);
Ted Kremenek57fb5912011-08-04 22:40:57 +0000567 if (!skipProcessUses)
568 ProcessUses(s);
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000569}
570
571void TransferFunctions::ProcessUses(Stmt *s) {
572 // This method is typically called after visiting a CFGElement statement
573 // in the CFG. We delay processing of reporting many loads of uninitialized
574 // values until here.
575 if (lastLoad) {
576 // If we just visited the lvalue-to-rvalue cast, there is nothing
577 // left to do.
578 if (lastLoad == s)
579 return;
580
Ted Kremenekde091ae2011-08-08 21:43:08 +0000581 const DeclRefExpr *DR =
582 cast<DeclRefExpr>(stripCasts(ac.getASTContext(),
583 lastLoad->getSubExpr()));
584 const VarDecl *VD = cast<VarDecl>(DR->getDecl());
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000585
586 // If we reach here, we may have seen a load of an uninitialized value
587 // and it hasn't been casted to void or otherwise handled. In this
588 // situation, report the incident.
Richard Smith81891882012-05-24 23:45:35 +0000589 reportUse(DR, VD);
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000590
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000591 lastLoad = 0;
Ted Kremenekc5f740e2011-10-07 00:42:48 +0000592
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000593 if (DR == lastDR) {
594 lastDR = 0;
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000595 return;
596 }
597 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000598
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000599 // Any other uses of 'lastDR' involve taking an lvalue of variable.
600 // In this case, it "escapes" the analysis.
601 if (lastDR && lastDR != s) {
602 vals[cast<VarDecl>(lastDR->getDecl())] = Initialized;
603 lastDR = 0;
Chandler Carruth86684942011-04-13 08:18:42 +0000604 }
605}
606
Ted Kremenek610068c2011-01-15 02:58:47 +0000607//------------------------------------------------------------------------====//
608// High-level "driver" logic for uninitialized values analysis.
609//====------------------------------------------------------------------------//
610
Ted Kremenek13bd4232011-01-20 17:37:17 +0000611static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000612 AnalysisDeclContext &ac, CFGBlockValues &vals,
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000613 llvm::BitVector &wasAnalyzed,
Ted Kremenek6f275422011-09-02 19:39:26 +0000614 UninitVariablesHandler *handler = 0) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000615
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000616 wasAnalyzed[block->getBlockID()] = true;
617
Ted Kremenek13bd4232011-01-20 17:37:17 +0000618 if (const BinaryOperator *b = getLogicalOperatorInChain(block)) {
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000619 CFGBlock::const_pred_iterator itr = block->pred_begin();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000620 BVPair vA = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000621 ++itr;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000622 BVPair vB = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000623
624 BVPair valsAB;
625
626 if (b->getOpcode() == BO_LAnd) {
627 // Merge the 'F' bits from the first and second.
628 vals.mergeIntoScratch(*(vA.second ? vA.second : vA.first), true);
629 vals.mergeIntoScratch(*(vB.second ? vB.second : vB.first), false);
630 valsAB.first = vA.first;
Ted Kremenek2d4bed12011-01-20 21:25:31 +0000631 valsAB.second = &vals.getScratch();
Chad Rosier30601782011-08-17 23:08:45 +0000632 } else {
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000633 // Merge the 'T' bits from the first and second.
634 assert(b->getOpcode() == BO_LOr);
635 vals.mergeIntoScratch(*vA.first, true);
636 vals.mergeIntoScratch(*vB.first, false);
637 valsAB.first = &vals.getScratch();
638 valsAB.second = vA.second ? vA.second : vA.first;
639 }
Ted Kremenek136f8f22011-03-15 04:57:27 +0000640 return vals.updateValueVectors(block, valsAB);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000641 }
642
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000643 // Default behavior: merge in values of predecessor blocks.
Ted Kremenek610068c2011-01-15 02:58:47 +0000644 vals.resetScratch();
645 bool isFirst = true;
646 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
647 E = block->pred_end(); I != E; ++I) {
Ted Kremenek6f275422011-09-02 19:39:26 +0000648 const CFGBlock *pred = *I;
649 if (wasAnalyzed[pred->getBlockID()]) {
650 vals.mergeIntoScratch(vals.getValueVector(pred, block), isFirst);
651 isFirst = false;
652 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000653 }
654 // Apply the transfer function.
Ted Kremenek6f275422011-09-02 19:39:26 +0000655 TransferFunctions tf(vals, cfg, ac, handler);
Ted Kremenek610068c2011-01-15 02:58:47 +0000656 for (CFGBlock::const_iterator I = block->begin(), E = block->end();
657 I != E; ++I) {
658 if (const CFGStmt *cs = dyn_cast<CFGStmt>(&*I)) {
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000659 tf.Visit(const_cast<Stmt*>(cs->getStmt()));
Ted Kremenek610068c2011-01-15 02:58:47 +0000660 }
661 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000662 tf.ProcessUses();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000663 return vals.updateValueVectorWithScratch(block);
Ted Kremenek610068c2011-01-15 02:58:47 +0000664}
665
Chandler Carruth5d989942011-07-06 16:21:37 +0000666void clang::runUninitializedVariablesAnalysis(
667 const DeclContext &dc,
668 const CFG &cfg,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000669 AnalysisDeclContext &ac,
Chandler Carruth5d989942011-07-06 16:21:37 +0000670 UninitVariablesHandler &handler,
671 UninitVariablesAnalysisStats &stats) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000672 CFGBlockValues vals(cfg);
673 vals.computeSetOfDeclarations(dc);
674 if (vals.hasNoDeclarations())
675 return;
Richard Smith81891882012-05-24 23:45:35 +0000676#if 0
677 cfg.dump(dc.getParentASTContext().getLangOpts(), true);
678#endif
Ted Kremenekd40066b2011-04-04 23:29:12 +0000679
Chandler Carruth5d989942011-07-06 16:21:37 +0000680 stats.NumVariablesAnalyzed = vals.getNumEntries();
681
Ted Kremenekd40066b2011-04-04 23:29:12 +0000682 // Mark all variables uninitialized at the entry.
683 const CFGBlock &entry = cfg.getEntry();
684 for (CFGBlock::const_succ_iterator i = entry.succ_begin(),
685 e = entry.succ_end(); i != e; ++i) {
686 if (const CFGBlock *succ = *i) {
687 ValueVector &vec = vals.getValueVector(&entry, succ);
688 const unsigned n = vals.getNumEntries();
689 for (unsigned j = 0; j < n ; ++j) {
690 vec[j] = Uninitialized;
691 }
692 }
693 }
694
695 // Proceed with the workist.
Ted Kremenek610068c2011-01-15 02:58:47 +0000696 DataflowWorklist worklist(cfg);
Ted Kremenek496398d2011-03-15 04:57:32 +0000697 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
Ted Kremenek610068c2011-01-15 02:58:47 +0000698 worklist.enqueueSuccessors(&cfg.getEntry());
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000699 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
Ted Kremenek6f275422011-09-02 19:39:26 +0000700 wasAnalyzed[cfg.getEntry().getBlockID()] = true;
Ted Kremenek610068c2011-01-15 02:58:47 +0000701
702 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000703 // Did the block change?
Chandler Carruth5d989942011-07-06 16:21:37 +0000704 bool changed = runOnBlock(block, cfg, ac, vals, wasAnalyzed);
705 ++stats.NumBlockVisits;
Ted Kremenek610068c2011-01-15 02:58:47 +0000706 if (changed || !previouslyVisited[block->getBlockID()])
707 worklist.enqueueSuccessors(block);
708 previouslyVisited[block->getBlockID()] = true;
709 }
710
711 // Run through the blocks one more time, and report uninitialized variabes.
712 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) {
Ted Kremenek6f275422011-09-02 19:39:26 +0000713 const CFGBlock *block = *BI;
714 if (wasAnalyzed[block->getBlockID()]) {
715 runOnBlock(block, cfg, ac, vals, wasAnalyzed, &handler);
Chandler Carruth5d989942011-07-06 16:21:37 +0000716 ++stats.NumBlockVisits;
717 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000718 }
719}
720
721UninitVariablesHandler::~UninitVariablesHandler() {}