clang 17.0.0git
UninitializedValues.cpp
Go to the documentation of this file.
1//===- UninitializedValues.cpp - Find Uninitialized Values ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements uninitialized values analysis for source-level CFGs.
10//
11//===----------------------------------------------------------------------===//
12
14#include "clang/AST/Attr.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclBase.h"
17#include "clang/AST/Expr.h"
19#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtObjC.h"
22#include "clang/AST/Type.h"
25#include "clang/Analysis/CFG.h"
28#include "clang/Basic/LLVM.h"
29#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/PackedVector.h"
32#include "llvm/ADT/SmallBitVector.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/Support/Casting.h"
35#include <algorithm>
36#include <cassert>
37#include <optional>
38
39using namespace clang;
40
41#define DEBUG_LOGGING 0
42
43static bool isTrackedVar(const VarDecl *vd, const DeclContext *dc) {
44 if (vd->isLocalVarDecl() && !vd->hasGlobalStorage() &&
45 !vd->isExceptionVariable() && !vd->isInitCapture() &&
46 !vd->isImplicit() && vd->getDeclContext() == dc) {
47 QualType ty = vd->getType();
48 return ty->isScalarType() || ty->isVectorType() || ty->isRecordType() ||
49 ty->isRVVType();
50 }
51 return false;
52}
53
54//------------------------------------------------------------------------====//
55// DeclToIndex: a mapping from Decls we track to value indices.
56//====------------------------------------------------------------------------//
57
58namespace {
59
60class DeclToIndex {
61 llvm::DenseMap<const VarDecl *, unsigned> map;
62
63public:
64 DeclToIndex() = default;
65
66 /// Compute the actual mapping from declarations to bits.
67 void computeMap(const DeclContext &dc);
68
69 /// Return the number of declarations in the map.
70 unsigned size() const { return map.size(); }
71
72 /// Returns the bit vector index for a given declaration.
73 std::optional<unsigned> getValueIndex(const VarDecl *d) const;
74};
75
76} // namespace
77
78void DeclToIndex::computeMap(const DeclContext &dc) {
79 unsigned count = 0;
81 E(dc.decls_end());
82 for ( ; I != E; ++I) {
83 const VarDecl *vd = *I;
84 if (isTrackedVar(vd, &dc))
85 map[vd] = count++;
86 }
87}
88
89std::optional<unsigned> DeclToIndex::getValueIndex(const VarDecl *d) const {
90 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I = map.find(d);
91 if (I == map.end())
92 return std::nullopt;
93 return I->second;
94}
95
96//------------------------------------------------------------------------====//
97// CFGBlockValues: dataflow values for CFG blocks.
98//====------------------------------------------------------------------------//
99
100// These values are defined in such a way that a merge can be done using
101// a bitwise OR.
102enum Value { Unknown = 0x0, /* 00 */
103 Initialized = 0x1, /* 01 */
104 Uninitialized = 0x2, /* 10 */
105 MayUninitialized = 0x3 /* 11 */ };
106
107static bool isUninitialized(const Value v) {
108 return v >= Uninitialized;
109}
110
111static bool isAlwaysUninit(const Value v) {
112 return v == Uninitialized;
113}
114
115namespace {
116
117using ValueVector = llvm::PackedVector<Value, 2, llvm::SmallBitVector>;
118
119class CFGBlockValues {
120 const CFG &cfg;
122 ValueVector scratch;
123 DeclToIndex declToIndex;
124
125public:
126 CFGBlockValues(const CFG &cfg);
127
128 unsigned getNumEntries() const { return declToIndex.size(); }
129
130 void computeSetOfDeclarations(const DeclContext &dc);
131
132 ValueVector &getValueVector(const CFGBlock *block) {
133 return vals[block->getBlockID()];
134 }
135
136 void setAllScratchValues(Value V);
137 void mergeIntoScratch(ValueVector const &source, bool isFirst);
138 bool updateValueVectorWithScratch(const CFGBlock *block);
139
140 bool hasNoDeclarations() const {
141 return declToIndex.size() == 0;
142 }
143
144 void resetScratch();
145
146 ValueVector::reference operator[](const VarDecl *vd);
147
148 Value getValue(const CFGBlock *block, const CFGBlock *dstBlock,
149 const VarDecl *vd) {
150 std::optional<unsigned> idx = declToIndex.getValueIndex(vd);
151 return getValueVector(block)[*idx];
152 }
153};
154
155} // namespace
156
157CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {}
158
159void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) {
160 declToIndex.computeMap(dc);
161 unsigned decls = declToIndex.size();
162 scratch.resize(decls);
163 unsigned n = cfg.getNumBlockIDs();
164 if (!n)
165 return;
166 vals.resize(n);
167 for (auto &val : vals)
168 val.resize(decls);
169}
170
171#if DEBUG_LOGGING
172static void printVector(const CFGBlock *block, ValueVector &bv,
173 unsigned num) {
174 llvm::errs() << block->getBlockID() << " :";
175 for (const auto &i : bv)
176 llvm::errs() << ' ' << i;
177 llvm::errs() << " : " << num << '\n';
178}
179#endif
180
181void CFGBlockValues::setAllScratchValues(Value V) {
182 for (unsigned I = 0, E = scratch.size(); I != E; ++I)
183 scratch[I] = V;
184}
185
186void CFGBlockValues::mergeIntoScratch(ValueVector const &source,
187 bool isFirst) {
188 if (isFirst)
189 scratch = source;
190 else
191 scratch |= source;
192}
193
194bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) {
195 ValueVector &dst = getValueVector(block);
196 bool changed = (dst != scratch);
197 if (changed)
198 dst = scratch;
199#if DEBUG_LOGGING
200 printVector(block, scratch, 0);
201#endif
202 return changed;
203}
204
205void CFGBlockValues::resetScratch() {
206 scratch.reset();
207}
208
209ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
210 return scratch[*declToIndex.getValueIndex(vd)];
211}
212
213//------------------------------------------------------------------------====//
214// Classification of DeclRefExprs as use or initialization.
215//====------------------------------------------------------------------------//
216
217namespace {
218
219class FindVarResult {
220 const VarDecl *vd;
221 const DeclRefExpr *dr;
222
223public:
224 FindVarResult(const VarDecl *vd, const DeclRefExpr *dr) : vd(vd), dr(dr) {}
225
226 const DeclRefExpr *getDeclRefExpr() const { return dr; }
227 const VarDecl *getDecl() const { return vd; }
228};
229
230} // namespace
231
232static const Expr *stripCasts(ASTContext &C, const Expr *Ex) {
233 while (Ex) {
234 Ex = Ex->IgnoreParenNoopCasts(C);
235 if (const auto *CE = dyn_cast<CastExpr>(Ex)) {
236 if (CE->getCastKind() == CK_LValueBitCast) {
237 Ex = CE->getSubExpr();
238 continue;
239 }
240 }
241 break;
242 }
243 return Ex;
244}
245
246/// If E is an expression comprising a reference to a single variable, find that
247/// variable.
248static FindVarResult findVar(const Expr *E, const DeclContext *DC) {
249 if (const auto *DRE =
250 dyn_cast<DeclRefExpr>(stripCasts(DC->getParentASTContext(), E)))
251 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
252 if (isTrackedVar(VD, DC))
253 return FindVarResult(VD, DRE);
254 return FindVarResult(nullptr, nullptr);
255}
256
257namespace {
258
259/// Classify each DeclRefExpr as an initialization or a use. Any
260/// DeclRefExpr which isn't explicitly classified will be assumed to have
261/// escaped the analysis and will be treated as an initialization.
262class ClassifyRefs : public StmtVisitor<ClassifyRefs> {
263public:
264 enum Class {
265 Init,
266 Use,
267 SelfInit,
268 ConstRefUse,
269 Ignore
270 };
271
272private:
273 const DeclContext *DC;
274 llvm::DenseMap<const DeclRefExpr *, Class> Classification;
275
276 bool isTrackedVar(const VarDecl *VD) const {
277 return ::isTrackedVar(VD, DC);
278 }
279
280 void classify(const Expr *E, Class C);
281
282public:
283 ClassifyRefs(AnalysisDeclContext &AC) : DC(cast<DeclContext>(AC.getDecl())) {}
284
285 void VisitDeclStmt(DeclStmt *DS);
286 void VisitUnaryOperator(UnaryOperator *UO);
287 void VisitBinaryOperator(BinaryOperator *BO);
288 void VisitCallExpr(CallExpr *CE);
289 void VisitCastExpr(CastExpr *CE);
290 void VisitOMPExecutableDirective(OMPExecutableDirective *ED);
291
292 void operator()(Stmt *S) { Visit(S); }
293
294 Class get(const DeclRefExpr *DRE) const {
295 llvm::DenseMap<const DeclRefExpr*, Class>::const_iterator I
296 = Classification.find(DRE);
297 if (I != Classification.end())
298 return I->second;
299
300 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
301 if (!VD || !isTrackedVar(VD))
302 return Ignore;
303
304 return Init;
305 }
306};
307
308} // namespace
309
311 if (VD->getType()->isRecordType())
312 return nullptr;
313 if (Expr *Init = VD->getInit()) {
314 const auto *DRE =
315 dyn_cast<DeclRefExpr>(stripCasts(VD->getASTContext(), Init));
316 if (DRE && DRE->getDecl() == VD)
317 return DRE;
318 }
319 return nullptr;
320}
321
322void ClassifyRefs::classify(const Expr *E, Class C) {
323 // The result of a ?: could also be an lvalue.
324 E = E->IgnoreParens();
325 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
326 classify(CO->getTrueExpr(), C);
327 classify(CO->getFalseExpr(), C);
328 return;
329 }
330
331 if (const auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) {
332 classify(BCO->getFalseExpr(), C);
333 return;
334 }
335
336 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
337 classify(OVE->getSourceExpr(), C);
338 return;
339 }
340
341 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
342 if (const auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
343 if (!VD->isStaticDataMember())
344 classify(ME->getBase(), C);
345 }
346 return;
347 }
348
349 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
350 switch (BO->getOpcode()) {
351 case BO_PtrMemD:
352 case BO_PtrMemI:
353 classify(BO->getLHS(), C);
354 return;
355 case BO_Comma:
356 classify(BO->getRHS(), C);
357 return;
358 default:
359 return;
360 }
361 }
362
363 FindVarResult Var = findVar(E, DC);
364 if (const DeclRefExpr *DRE = Var.getDeclRefExpr())
365 Classification[DRE] = std::max(Classification[DRE], C);
366}
367
368void ClassifyRefs::VisitDeclStmt(DeclStmt *DS) {
369 for (auto *DI : DS->decls()) {
370 auto *VD = dyn_cast<VarDecl>(DI);
371 if (VD && isTrackedVar(VD))
372 if (const DeclRefExpr *DRE = getSelfInitExpr(VD))
373 Classification[DRE] = SelfInit;
374 }
375}
376
377void ClassifyRefs::VisitBinaryOperator(BinaryOperator *BO) {
378 // Ignore the evaluation of a DeclRefExpr on the LHS of an assignment. If this
379 // is not a compound-assignment, we will treat it as initializing the variable
380 // when TransferFunctions visits it. A compound-assignment does not affect
381 // whether a variable is uninitialized, and there's no point counting it as a
382 // use.
383 if (BO->isCompoundAssignmentOp())
384 classify(BO->getLHS(), Use);
385 else if (BO->getOpcode() == BO_Assign || BO->getOpcode() == BO_Comma)
386 classify(BO->getLHS(), Ignore);
387}
388
389void ClassifyRefs::VisitUnaryOperator(UnaryOperator *UO) {
390 // Increment and decrement are uses despite there being no lvalue-to-rvalue
391 // conversion.
392 if (UO->isIncrementDecrementOp())
393 classify(UO->getSubExpr(), Use);
394}
395
396void ClassifyRefs::VisitOMPExecutableDirective(OMPExecutableDirective *ED) {
398 classify(cast<Expr>(S), Use);
399}
400
401static bool isPointerToConst(const QualType &QT) {
402 return QT->isAnyPointerType() && QT->getPointeeType().isConstQualified();
403}
404
405static bool hasTrivialBody(CallExpr *CE) {
406 if (FunctionDecl *FD = CE->getDirectCallee()) {
407 if (FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
408 return FTD->getTemplatedDecl()->hasTrivialBody();
409 return FD->hasTrivialBody();
410 }
411 return false;
412}
413
414void ClassifyRefs::VisitCallExpr(CallExpr *CE) {
415 // Classify arguments to std::move as used.
416 if (CE->isCallToStdMove()) {
417 // RecordTypes are handled in SemaDeclCXX.cpp.
418 if (!CE->getArg(0)->getType()->isRecordType())
419 classify(CE->getArg(0), Use);
420 return;
421 }
422 bool isTrivialBody = hasTrivialBody(CE);
423 // If a value is passed by const pointer to a function,
424 // we should not assume that it is initialized by the call, and we
425 // conservatively do not assume that it is used.
426 // If a value is passed by const reference to a function,
427 // it should already be initialized.
428 for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end();
429 I != E; ++I) {
430 if ((*I)->isGLValue()) {
431 if ((*I)->getType().isConstQualified())
432 classify((*I), isTrivialBody ? Ignore : ConstRefUse);
433 } else if (isPointerToConst((*I)->getType())) {
434 const Expr *Ex = stripCasts(DC->getParentASTContext(), *I);
435 const auto *UO = dyn_cast<UnaryOperator>(Ex);
436 if (UO && UO->getOpcode() == UO_AddrOf)
437 Ex = UO->getSubExpr();
438 classify(Ex, Ignore);
439 }
440 }
441}
442
443void ClassifyRefs::VisitCastExpr(CastExpr *CE) {
444 if (CE->getCastKind() == CK_LValueToRValue)
445 classify(CE->getSubExpr(), Use);
446 else if (const auto *CSE = dyn_cast<CStyleCastExpr>(CE)) {
447 if (CSE->getType()->isVoidType()) {
448 // Squelch any detected load of an uninitialized value if
449 // we cast it to void.
450 // e.g. (void) x;
451 classify(CSE->getSubExpr(), Ignore);
452 }
453 }
454}
455
456//------------------------------------------------------------------------====//
457// Transfer function for uninitialized values analysis.
458//====------------------------------------------------------------------------//
459
460namespace {
461
462class TransferFunctions : public StmtVisitor<TransferFunctions> {
463 CFGBlockValues &vals;
464 const CFG &cfg;
465 const CFGBlock *block;
467 const ClassifyRefs &classification;
468 ObjCNoReturn objCNoRet;
469 UninitVariablesHandler &handler;
470
471public:
472 TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
473 const CFGBlock *block, AnalysisDeclContext &ac,
474 const ClassifyRefs &classification,
475 UninitVariablesHandler &handler)
476 : vals(vals), cfg(cfg), block(block), ac(ac),
477 classification(classification), objCNoRet(ac.getASTContext()),
478 handler(handler) {}
479
480 void reportUse(const Expr *ex, const VarDecl *vd);
481 void reportConstRefUse(const Expr *ex, const VarDecl *vd);
482
483 void VisitBinaryOperator(BinaryOperator *bo);
484 void VisitBlockExpr(BlockExpr *be);
485 void VisitCallExpr(CallExpr *ce);
486 void VisitDeclRefExpr(DeclRefExpr *dr);
487 void VisitDeclStmt(DeclStmt *ds);
488 void VisitGCCAsmStmt(GCCAsmStmt *as);
489 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS);
490 void VisitObjCMessageExpr(ObjCMessageExpr *ME);
491 void VisitOMPExecutableDirective(OMPExecutableDirective *ED);
492
493 bool isTrackedVar(const VarDecl *vd) {
494 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl()));
495 }
496
497 FindVarResult findVar(const Expr *ex) {
498 return ::findVar(ex, cast<DeclContext>(ac.getDecl()));
499 }
500
501 UninitUse getUninitUse(const Expr *ex, const VarDecl *vd, Value v) {
502 UninitUse Use(ex, isAlwaysUninit(v));
503
504 assert(isUninitialized(v));
505 if (Use.getKind() == UninitUse::Always)
506 return Use;
507
508 // If an edge which leads unconditionally to this use did not initialize
509 // the variable, we can say something stronger than 'may be uninitialized':
510 // we can say 'either it's used uninitialized or you have dead code'.
511 //
512 // We track the number of successors of a node which have been visited, and
513 // visit a node once we have visited all of its successors. Only edges where
514 // the variable might still be uninitialized are followed. Since a variable
515 // can't transfer from being initialized to being uninitialized, this will
516 // trace out the subgraph which inevitably leads to the use and does not
517 // initialize the variable. We do not want to skip past loops, since their
518 // non-termination might be correlated with the initialization condition.
519 //
520 // For example:
521 //
522 // void f(bool a, bool b) {
523 // block1: int n;
524 // if (a) {
525 // block2: if (b)
526 // block3: n = 1;
527 // block4: } else if (b) {
528 // block5: while (!a) {
529 // block6: do_work(&a);
530 // n = 2;
531 // }
532 // }
533 // block7: if (a)
534 // block8: g();
535 // block9: return n;
536 // }
537 //
538 // Starting from the maybe-uninitialized use in block 9:
539 // * Block 7 is not visited because we have only visited one of its two
540 // successors.
541 // * Block 8 is visited because we've visited its only successor.
542 // From block 8:
543 // * Block 7 is visited because we've now visited both of its successors.
544 // From block 7:
545 // * Blocks 1, 2, 4, 5, and 6 are not visited because we didn't visit all
546 // of their successors (we didn't visit 4, 3, 5, 6, and 5, respectively).
547 // * Block 3 is not visited because it initializes 'n'.
548 // Now the algorithm terminates, having visited blocks 7 and 8, and having
549 // found the frontier is blocks 2, 4, and 5.
550 //
551 // 'n' is definitely uninitialized for two edges into block 7 (from blocks 2
552 // and 4), so we report that any time either of those edges is taken (in
553 // each case when 'b == false'), 'n' is used uninitialized.
555 SmallVector<unsigned, 32> SuccsVisited(cfg.getNumBlockIDs(), 0);
556 Queue.push_back(block);
557 // Specify that we've already visited all successors of the starting block.
558 // This has the dual purpose of ensuring we never add it to the queue, and
559 // of marking it as not being a candidate element of the frontier.
560 SuccsVisited[block->getBlockID()] = block->succ_size();
561 while (!Queue.empty()) {
562 const CFGBlock *B = Queue.pop_back_val();
563
564 // If the use is always reached from the entry block, make a note of that.
565 if (B == &cfg.getEntry())
566 Use.setUninitAfterCall();
567
568 for (CFGBlock::const_pred_iterator I = B->pred_begin(), E = B->pred_end();
569 I != E; ++I) {
570 const CFGBlock *Pred = *I;
571 if (!Pred)
572 continue;
573
574 Value AtPredExit = vals.getValue(Pred, B, vd);
575 if (AtPredExit == Initialized)
576 // This block initializes the variable.
577 continue;
578 if (AtPredExit == MayUninitialized &&
579 vals.getValue(B, nullptr, vd) == Uninitialized) {
580 // This block declares the variable (uninitialized), and is reachable
581 // from a block that initializes the variable. We can't guarantee to
582 // give an earlier location for the diagnostic (and it appears that
583 // this code is intended to be reachable) so give a diagnostic here
584 // and go no further down this path.
585 Use.setUninitAfterDecl();
586 continue;
587 }
588
589 unsigned &SV = SuccsVisited[Pred->getBlockID()];
590 if (!SV) {
591 // When visiting the first successor of a block, mark all NULL
592 // successors as having been visited.
594 SE = Pred->succ_end();
595 SI != SE; ++SI)
596 if (!*SI)
597 ++SV;
598 }
599
600 if (++SV == Pred->succ_size())
601 // All paths from this block lead to the use and don't initialize the
602 // variable.
603 Queue.push_back(Pred);
604 }
605 }
606
607 // Scan the frontier, looking for blocks where the variable was
608 // uninitialized.
609 for (const auto *Block : cfg) {
610 unsigned BlockID = Block->getBlockID();
611 const Stmt *Term = Block->getTerminatorStmt();
612 if (SuccsVisited[BlockID] && SuccsVisited[BlockID] < Block->succ_size() &&
613 Term) {
614 // This block inevitably leads to the use. If we have an edge from here
615 // to a post-dominator block, and the variable is uninitialized on that
616 // edge, we have found a bug.
617 for (CFGBlock::const_succ_iterator I = Block->succ_begin(),
618 E = Block->succ_end(); I != E; ++I) {
619 const CFGBlock *Succ = *I;
620 if (Succ && SuccsVisited[Succ->getBlockID()] >= Succ->succ_size() &&
621 vals.getValue(Block, Succ, vd) == Uninitialized) {
622 // Switch cases are a special case: report the label to the caller
623 // as the 'terminator', not the switch statement itself. Suppress
624 // situations where no label matched: we can't be sure that's
625 // possible.
626 if (isa<SwitchStmt>(Term)) {
627 const Stmt *Label = Succ->getLabel();
628 if (!Label || !isa<SwitchCase>(Label))
629 // Might not be possible.
630 continue;
631 UninitUse::Branch Branch;
632 Branch.Terminator = Label;
633 Branch.Output = 0; // Ignored.
634 Use.addUninitBranch(Branch);
635 } else {
636 UninitUse::Branch Branch;
637 Branch.Terminator = Term;
638 Branch.Output = I - Block->succ_begin();
639 Use.addUninitBranch(Branch);
640 }
641 }
642 }
643 }
644 }
645
646 return Use;
647 }
648};
649
650} // namespace
651
652void TransferFunctions::reportUse(const Expr *ex, const VarDecl *vd) {
653 Value v = vals[vd];
654 if (isUninitialized(v))
655 handler.handleUseOfUninitVariable(vd, getUninitUse(ex, vd, v));
656}
657
658void TransferFunctions::reportConstRefUse(const Expr *ex, const VarDecl *vd) {
659 Value v = vals[vd];
660 if (isAlwaysUninit(v))
661 handler.handleConstRefUseOfUninitVariable(vd, getUninitUse(ex, vd, v));
662}
663
664void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS) {
665 // This represents an initialization of the 'element' value.
666 if (const auto *DS = dyn_cast<DeclStmt>(FS->getElement())) {
667 const auto *VD = cast<VarDecl>(DS->getSingleDecl());
668 if (isTrackedVar(VD))
669 vals[VD] = Initialized;
670 }
671}
672
673void TransferFunctions::VisitOMPExecutableDirective(
676 assert(S && "Expected non-null used-in-clause child.");
677 Visit(S);
678 }
679 if (!ED->isStandaloneDirective())
680 Visit(ED->getStructuredBlock());
681}
682
683void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
684 const BlockDecl *bd = be->getBlockDecl();
685 for (const auto &I : bd->captures()) {
686 const VarDecl *vd = I.getVariable();
687 if (!isTrackedVar(vd))
688 continue;
689 if (I.isByRef()) {
690 vals[vd] = Initialized;
691 continue;
692 }
693 reportUse(be, vd);
694 }
695}
696
697void TransferFunctions::VisitCallExpr(CallExpr *ce) {
698 if (Decl *Callee = ce->getCalleeDecl()) {
699 if (Callee->hasAttr<ReturnsTwiceAttr>()) {
700 // After a call to a function like setjmp or vfork, any variable which is
701 // initialized anywhere within this function may now be initialized. For
702 // now, just assume such a call initializes all variables. FIXME: Only
703 // mark variables as initialized if they have an initializer which is
704 // reachable from here.
705 vals.setAllScratchValues(Initialized);
706 }
707 else if (Callee->hasAttr<AnalyzerNoReturnAttr>()) {
708 // Functions labeled like "analyzer_noreturn" are often used to denote
709 // "panic" functions that in special debug situations can still return,
710 // but for the most part should not be treated as returning. This is a
711 // useful annotation borrowed from the static analyzer that is useful for
712 // suppressing branch-specific false positives when we call one of these
713 // functions but keep pretending the path continues (when in reality the
714 // user doesn't care).
715 vals.setAllScratchValues(Unknown);
716 }
717 }
718}
719
720void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
721 switch (classification.get(dr)) {
722 case ClassifyRefs::Ignore:
723 break;
724 case ClassifyRefs::Use:
725 reportUse(dr, cast<VarDecl>(dr->getDecl()));
726 break;
727 case ClassifyRefs::Init:
728 vals[cast<VarDecl>(dr->getDecl())] = Initialized;
729 break;
730 case ClassifyRefs::SelfInit:
731 handler.handleSelfInit(cast<VarDecl>(dr->getDecl()));
732 break;
733 case ClassifyRefs::ConstRefUse:
734 reportConstRefUse(dr, cast<VarDecl>(dr->getDecl()));
735 break;
736 }
737}
738
739void TransferFunctions::VisitBinaryOperator(BinaryOperator *BO) {
740 if (BO->getOpcode() == BO_Assign) {
741 FindVarResult Var = findVar(BO->getLHS());
742 if (const VarDecl *VD = Var.getDecl())
743 vals[VD] = Initialized;
744 }
745}
746
747void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
748 for (auto *DI : DS->decls()) {
749 auto *VD = dyn_cast<VarDecl>(DI);
750 if (VD && isTrackedVar(VD)) {
751 if (getSelfInitExpr(VD)) {
752 // If the initializer consists solely of a reference to itself, we
753 // explicitly mark the variable as uninitialized. This allows code
754 // like the following:
755 //
756 // int x = x;
757 //
758 // to deliberately leave a variable uninitialized. Different analysis
759 // clients can detect this pattern and adjust their reporting
760 // appropriately, but we need to continue to analyze subsequent uses
761 // of the variable.
762 vals[VD] = Uninitialized;
763 } else if (VD->getInit()) {
764 // Treat the new variable as initialized.
765 vals[VD] = Initialized;
766 } else {
767 // No initializer: the variable is now uninitialized. This matters
768 // for cases like:
769 // while (...) {
770 // int n;
771 // use(n);
772 // n = 0;
773 // }
774 // FIXME: Mark the variable as uninitialized whenever its scope is
775 // left, since its scope could be re-entered by a jump over the
776 // declaration.
777 vals[VD] = Uninitialized;
778 }
779 }
780 }
781}
782
783void TransferFunctions::VisitGCCAsmStmt(GCCAsmStmt *as) {
784 // An "asm goto" statement is a terminator that may initialize some variables.
785 if (!as->isAsmGoto())
786 return;
787
788 ASTContext &C = ac.getASTContext();
789 for (const Expr *O : as->outputs()) {
790 const Expr *Ex = stripCasts(C, O);
791
792 // Strip away any unary operators. Invalid l-values are reported by other
793 // semantic analysis passes.
794 while (const auto *UO = dyn_cast<UnaryOperator>(Ex))
795 Ex = stripCasts(C, UO->getSubExpr());
796
797 // Mark the variable as potentially uninitialized for those cases where
798 // it's used on an indirect path, where it's not guaranteed to be
799 // defined.
800 if (const VarDecl *VD = findVar(Ex).getDecl())
801 if (vals[VD] != Initialized)
802 vals[VD] = MayUninitialized;
803 }
804}
805
806void TransferFunctions::VisitObjCMessageExpr(ObjCMessageExpr *ME) {
807 // If the Objective-C message expression is an implicit no-return that
808 // is not modeled in the CFG, set the tracked dataflow values to Unknown.
809 if (objCNoRet.isImplicitNoReturn(ME)) {
810 vals.setAllScratchValues(Unknown);
811 }
812}
813
814//------------------------------------------------------------------------====//
815// High-level "driver" logic for uninitialized values analysis.
816//====------------------------------------------------------------------------//
817
818static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
819 AnalysisDeclContext &ac, CFGBlockValues &vals,
820 const ClassifyRefs &classification,
821 llvm::BitVector &wasAnalyzed,
822 UninitVariablesHandler &handler) {
823 wasAnalyzed[block->getBlockID()] = true;
824 vals.resetScratch();
825 // Merge in values of predecessor blocks.
826 bool isFirst = true;
828 E = block->pred_end(); I != E; ++I) {
829 const CFGBlock *pred = *I;
830 if (!pred)
831 continue;
832 if (wasAnalyzed[pred->getBlockID()]) {
833 vals.mergeIntoScratch(vals.getValueVector(pred), isFirst);
834 isFirst = false;
835 }
836 }
837 // Apply the transfer function.
838 TransferFunctions tf(vals, cfg, block, ac, classification, handler);
839 for (const auto &I : *block) {
840 if (std::optional<CFGStmt> cs = I.getAs<CFGStmt>())
841 tf.Visit(const_cast<Stmt *>(cs->getStmt()));
842 }
843 CFGTerminator terminator = block->getTerminator();
844 if (auto *as = dyn_cast_or_null<GCCAsmStmt>(terminator.getStmt()))
845 if (as->isAsmGoto())
846 tf.Visit(as);
847 return vals.updateValueVectorWithScratch(block);
848}
849
850namespace {
851
852/// PruneBlocksHandler is a special UninitVariablesHandler that is used
853/// to detect when a CFGBlock has any *potential* use of an uninitialized
854/// variable. It is mainly used to prune out work during the final
855/// reporting pass.
856struct PruneBlocksHandler : public UninitVariablesHandler {
857 /// Records if a CFGBlock had a potential use of an uninitialized variable.
858 llvm::BitVector hadUse;
859
860 /// Records if any CFGBlock had a potential use of an uninitialized variable.
861 bool hadAnyUse = false;
862
863 /// The current block to scribble use information.
864 unsigned currentBlock = 0;
865
866 PruneBlocksHandler(unsigned numBlocks) : hadUse(numBlocks, false) {}
867
868 ~PruneBlocksHandler() override = default;
869
870 void handleUseOfUninitVariable(const VarDecl *vd,
871 const UninitUse &use) override {
872 hadUse[currentBlock] = true;
873 hadAnyUse = true;
874 }
875
877 const UninitUse &use) override {
878 hadUse[currentBlock] = true;
879 hadAnyUse = true;
880 }
881
882 /// Called when the uninitialized variable analysis detects the
883 /// idiom 'int x = x'. All other uses of 'x' within the initializer
884 /// are handled by handleUseOfUninitVariable.
885 void handleSelfInit(const VarDecl *vd) override {
886 hadUse[currentBlock] = true;
887 hadAnyUse = true;
888 }
889};
890
891} // namespace
892
894 const DeclContext &dc,
895 const CFG &cfg,
897 UninitVariablesHandler &handler,
899 CFGBlockValues vals(cfg);
900 vals.computeSetOfDeclarations(dc);
901 if (vals.hasNoDeclarations())
902 return;
903
904 stats.NumVariablesAnalyzed = vals.getNumEntries();
905
906 // Precompute which expressions are uses and which are initializations.
907 ClassifyRefs classification(ac);
908 cfg.VisitBlockStmts(classification);
909
910 // Mark all variables uninitialized at the entry.
911 const CFGBlock &entry = cfg.getEntry();
912 ValueVector &vec = vals.getValueVector(&entry);
913 const unsigned n = vals.getNumEntries();
914 for (unsigned j = 0; j < n; ++j) {
915 vec[j] = Uninitialized;
916 }
917
918 // Proceed with the workist.
919 ForwardDataflowWorklist worklist(cfg, ac);
920 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
921 worklist.enqueueSuccessors(&cfg.getEntry());
922 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
923 wasAnalyzed[cfg.getEntry().getBlockID()] = true;
924 PruneBlocksHandler PBH(cfg.getNumBlockIDs());
925
926 while (const CFGBlock *block = worklist.dequeue()) {
927 PBH.currentBlock = block->getBlockID();
928
929 // Did the block change?
930 bool changed = runOnBlock(block, cfg, ac, vals,
931 classification, wasAnalyzed, PBH);
932 ++stats.NumBlockVisits;
933 if (changed || !previouslyVisited[block->getBlockID()])
934 worklist.enqueueSuccessors(block);
935 previouslyVisited[block->getBlockID()] = true;
936 }
937
938 if (!PBH.hadAnyUse)
939 return;
940
941 // Run through the blocks one more time, and report uninitialized variables.
942 for (const auto *block : cfg)
943 if (PBH.hadUse[block->getBlockID()]) {
944 runOnBlock(block, cfg, ac, vals, classification, wasAnalyzed, handler);
945 ++stats.NumBlockVisits;
946 }
947}
948
#define V(N, I)
Definition: ASTContext.h:3230
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the Objective-C statement AST node classes.
C Language Family Type Representation.
static bool isAlwaysUninit(const Value v)
static bool isTrackedVar(const VarDecl *vd, const DeclContext *dc)
static const Expr * stripCasts(ASTContext &C, const Expr *Ex)
static bool isUninitialized(const Value v)
@ Uninitialized
@ MayUninitialized
static bool isPointerToConst(const QualType &QT)
static FindVarResult findVar(const Expr *E, const DeclContext *DC)
If E is an expression comprising a reference to a single variable, find that variable.
static bool hasTrivialBody(CallExpr *CE)
static const DeclRefExpr * getSelfInitExpr(VarDecl *VD)
static bool runOnBlock(const CFGBlock *block, const CFG &cfg, AnalysisDeclContext &ac, CFGBlockValues &vals, const ClassifyRefs &classification, llvm::BitVector &wasAnalyzed, UninitVariablesHandler &handler)
std::string Label
__device__ __2f16 float c
do v
Definition: arm_acle.h:76
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
AnalysisDeclContext contains the context data for the function, method or block under analysis.
const Decl * getDecl() const
ASTContext & getASTContext() const
outputs_range outputs()
Definition: Stmt.h:3051
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3827
Expr * getLHS() const
Definition: Expr.h:3876
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3967
Opcode getOpcode() const
Definition: Expr.h:3871
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4370
ArrayRef< Capture > captures() const
Definition: Decl.h:4497
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6147
const BlockDecl * getBlockDecl() const
Definition: Expr.h:6159
Represents a single basic block in a source-level CFG.
Definition: CFG.h:576
pred_iterator pred_end()
Definition: CFG.h:938
succ_iterator succ_end()
Definition: CFG.h:956
Stmt * getLabel()
Definition: CFG.h:1069
CFGTerminator getTerminator() const
Definition: CFG.h:1048
succ_iterator succ_begin()
Definition: CFG.h:955
AdjacentBlocks::const_iterator const_pred_iterator
Definition: CFG.h:924
pred_iterator pred_begin()
Definition: CFG.h:937
unsigned getBlockID() const
Definition: CFG.h:1074
AdjacentBlocks::const_iterator const_succ_iterator
Definition: CFG.h:931
unsigned succ_size() const
Definition: CFG.h:973
Represents CFGBlock terminator statement.
Definition: CFG.h:503
Stmt * getStmt()
Definition: CFG.h:535
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition: CFG.h:1225
void VisitBlockStmts(Callback &O) const
Definition: CFG.h:1397
CFGBlock & getEntry()
Definition: CFG.h:1331
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
Definition: CFG.h:1411
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2825
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3016
arg_iterator arg_begin()
Definition: Expr.h:3069
arg_iterator arg_end()
Definition: Expr.h:3072
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2995
bool isCallToStdMove() const
Definition: Expr.cpp:3480
Decl * getCalleeDecl()
Definition: Expr.h:2989
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3495
CastKind getCastKind() const
Definition: Expr.h:3539
Expr * getSubExpr()
Definition: Expr.h:3545
const CFGBlock * dequeue()
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2219
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1402
ASTContext & getParentASTContext() const
Definition: DeclBase.h:1973
decl_iterator decls_end() const
Definition: DeclBase.h:2201
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1498
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1237
ValueDecl * getDecl()
Definition: Expr.h:1305
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1317
decl_range decls()
Definition: Stmt.h:1365
const Decl * getSingleDecl() const
Definition: Stmt.h:1332
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:429
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:576
DeclContext * getDeclContext()
Definition: DeclBase.h:441
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition: Expr.cpp:3084
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3053
QualType getType() const
Definition: Expr.h:142
Represents a function declaration or definition.
Definition: Decl.h:1917
Declaration of a template function.
This represents a GCC inline-assembly statement extension.
Definition: Stmt.h:3077
bool isAsmGoto() const
Definition: Stmt.h:3222
This is a basic class for representing single OpenMP executable directive.
Definition: StmtOpenMP.h:266
ArrayRef< OMPClause * > clauses() const
Definition: StmtOpenMP.h:573
const Stmt * getStructuredBlock() const
Returns the AST node representing OpenMP structured-block of this OpenMP executable directive,...
Definition: StmtOpenMP.h:588
bool isStandaloneDirective() const
Returns whether or not this is a Standalone directive.
Definition: StmtOpenMP.cpp:58
static llvm::iterator_range< used_clauses_child_iterator > used_clauses_children(ArrayRef< OMPClause * > Clauses)
Definition: StmtOpenMP.h:401
Represents Objective-C's collection statement.
Definition: StmtObjC.h:23
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:942
bool isImplicitNoReturn(const ObjCMessageExpr *ME)
Return true if the given message expression is known to never return.
A (possibly-)qualified type.
Definition: Type.h:736
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6741
RetTy Visit(PTR(Stmt) S, ParamTys... P)
Definition: StmtVisitor.h:43
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:184
Stmt - This represents one statement.
Definition: Stmt.h:72
bool isRVVType() const
Definition: Type.h:7175
bool isScalarType() const
Definition: Type.h:7316
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:631
bool isVectorType() const
Definition: Type.h:7023
bool isAnyPointerType() const
Definition: Type.h:6925
bool isRecordType() const
Definition: Type.h:7011
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2189
Expr * getSubExpr() const
Definition: Expr.h:2234
Opcode getOpcode() const
Definition: Expr.h:2229
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2289
A use of a variable, which might be uninitialized.
@ Always
The use is always uninitialized.
virtual void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use)
Called when the uninitialized variable is used at the given expression.
virtual void handleSelfInit(const VarDecl *vd)
Called when the uninitialized variable analysis detects the idiom 'int x = x'.
virtual void handleConstRefUseOfUninitVariable(const VarDecl *vd, const UninitUse &use)
Called when the uninitialized variable is used as const refernce argument.
QualType getType() const
Definition: Decl.h:712
Represents a variable declaration or definition.
Definition: Decl.h:913
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1528
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1183
bool isExceptionVariable() const
Determine whether this variable is the exception variable in a C++ catch statememt or an Objective-C ...
Definition: Decl.h:1444
const Expr * getInit() const
Definition: Decl.h:1325
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1210
BlockID
The various types of blocks that can occur within a API notes file.
@ C
Languages that the frontend can parse and compile.
void runUninitializedVariablesAnalysis(const DeclContext &dc, const CFG &cfg, AnalysisDeclContext &ac, UninitVariablesHandler &handler, UninitVariablesAnalysisStats &stats)
U cast(CodeGen::Address addr)
Definition: Address.h:148
#define false
Definition: stdbool.h:22
A worklist implementation for forward dataflow analysis.
void enqueueSuccessors(const CFGBlock *Block)
Iterator for iterating over Stmt * arrays that contain only T *.
Definition: Stmt.h:1141