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 
13 #include "clang/Analysis/Analyses/UninitializedValues.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/OperationKinds.h"
19 #include "clang/AST/Stmt.h"
20 #include "clang/AST/StmtObjC.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
24 #include "clang/Analysis/AnalysisDeclContext.h"
25 #include "clang/Analysis/CFG.h"
26 #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h"
27 #include "clang/Analysis/FlowSensitive/DataflowWorklist.h"
28 #include "clang/Basic/LLVM.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/None.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/PackedVector.h"
34 #include "llvm/ADT/SmallBitVector.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/Support/Casting.h"
37 #include <algorithm>
38 #include <cassert>
39 
40 using namespace clang;
41 
42 #define DEBUG_LOGGING 0
43 
44 static bool isTrackedVar(const VarDecl *vd, const DeclContext *dc) {
45   if (vd->isLocalVarDecl() && !vd->hasGlobalStorage() &&
46       !vd->isExceptionVariable() && !vd->isInitCapture() &&
47       !vd->isImplicit() && vd->getDeclContext() == dc) {
48     QualType ty = vd->getType();
49     return ty->isScalarType() || ty->isVectorType() || ty->isRecordType();
50   }
51   return false;
52 }
53 
54 //------------------------------------------------------------------------====//
55 // DeclToIndex: a mapping from Decls we track to value indices.
56 //====------------------------------------------------------------------------//
57 
58 namespace {
59 
60 class DeclToIndex {
61   llvm::DenseMap<const VarDecl *, unsigned> map;
62 
63 public:
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   Optional<unsigned> getValueIndex(const VarDecl *d) const;
74 };
75 
76 } // namespace
77 
78 void DeclToIndex::computeMap(const DeclContext &dc) {
79   unsigned count = 0;
80   DeclContext::specific_decl_iterator<VarDecl> I(dc.decls_begin()),
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 
89 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 None;
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.
102 enum Value { Unknown = 0x0,         /* 00 */
103              Initialized = 0x1,     /* 01 */
104              Uninitialized = 0x2,   /* 10 */
105              MayUninitialized = 0x3 /* 11 */ };
106 
107 static bool isUninitialized(const Value v) {
108   return v >= Uninitialized;
109 }
110 
111 static bool isAlwaysUninit(const Value v) {
112   return v == Uninitialized;
113 }
114 
115 namespace {
116 
117 using ValueVector = llvm::PackedVector<Value, 2, llvm::SmallBitVector>;
118 
119 class CFGBlockValues {
120   const CFG &cfg;
121   SmallVector<ValueVector, 8> vals;
122   ValueVector scratch;
123   DeclToIndex declToIndex;
124 
125 public:
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     const Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
151     assert(idx.hasValue());
152     return getValueVector(block)[idx.getValue()];
153   }
154 };
155 
156 } // namespace
157 
158 CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {}
159 
160 void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) {
161   declToIndex.computeMap(dc);
162   unsigned decls = declToIndex.size();
163   scratch.resize(decls);
164   unsigned n = cfg.getNumBlockIDs();
165   if (!n)
166     return;
167   vals.resize(n);
168   for (auto &val : vals)
169     val.resize(decls);
170 }
171 
172 #if DEBUG_LOGGING
173 static void printVector(const CFGBlock *block, ValueVector &bv,
174                         unsigned num) {
175   llvm::errs() << block->getBlockID() << " :";
176   for (const auto &i : bv)
177     llvm::errs() << ' ' << i;
178   llvm::errs() << " : " << num << '\n';
179 }
180 #endif
181 
182 void CFGBlockValues::setAllScratchValues(Value V) {
183   for (unsigned I = 0, E = scratch.size(); I != E; ++I)
184     scratch[I] = V;
185 }
186 
187 void CFGBlockValues::mergeIntoScratch(ValueVector const &source,
188                                       bool isFirst) {
189   if (isFirst)
190     scratch = source;
191   else
192     scratch |= source;
193 }
194 
195 bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) {
196   ValueVector &dst = getValueVector(block);
197   bool changed = (dst != scratch);
198   if (changed)
199     dst = scratch;
200 #if DEBUG_LOGGING
201   printVector(block, scratch, 0);
202 #endif
203   return changed;
204 }
205 
206 void CFGBlockValues::resetScratch() {
207   scratch.reset();
208 }
209 
210 ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
211   const Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
212   assert(idx.hasValue());
213   return scratch[idx.getValue()];
214 }
215 
216 //------------------------------------------------------------------------====//
217 // Classification of DeclRefExprs as use or initialization.
218 //====------------------------------------------------------------------------//
219 
220 namespace {
221 
222 class FindVarResult {
223   const VarDecl *vd;
224   const DeclRefExpr *dr;
225 
226 public:
227   FindVarResult(const VarDecl *vd, const DeclRefExpr *dr) : vd(vd), dr(dr) {}
228 
229   const DeclRefExpr *getDeclRefExpr() const { return dr; }
230   const VarDecl *getDecl() const { return vd; }
231 };
232 
233 } // namespace
234 
235 static const Expr *stripCasts(ASTContext &C, const Expr *Ex) {
236   while (Ex) {
237     Ex = Ex->IgnoreParenNoopCasts(C);
238     if (const auto *CE = dyn_cast<CastExpr>(Ex)) {
239       if (CE->getCastKind() == CK_LValueBitCast) {
240         Ex = CE->getSubExpr();
241         continue;
242       }
243     }
244     break;
245   }
246   return Ex;
247 }
248 
249 /// If E is an expression comprising a reference to a single variable, find that
250 /// variable.
251 static FindVarResult findVar(const Expr *E, const DeclContext *DC) {
252   if (const auto *DRE =
253           dyn_cast<DeclRefExpr>(stripCasts(DC->getParentASTContext(), E)))
254     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
255       if (isTrackedVar(VD, DC))
256         return FindVarResult(VD, DRE);
257   return FindVarResult(nullptr, nullptr);
258 }
259 
260 namespace {
261 
262 /// Classify each DeclRefExpr as an initialization or a use. Any
263 /// DeclRefExpr which isn't explicitly classified will be assumed to have
264 /// escaped the analysis and will be treated as an initialization.
265 class ClassifyRefs : public StmtVisitor<ClassifyRefs> {
266 public:
267   enum Class {
268     Init,
269     Use,
270     SelfInit,
271     Ignore
272   };
273 
274 private:
275   const DeclContext *DC;
276   llvm::DenseMap<const DeclRefExpr *, Class> Classification;
277 
278   bool isTrackedVar(const VarDecl *VD) const {
279     return ::isTrackedVar(VD, DC);
280   }
281 
282   void classify(const Expr *E, Class C);
283 
284 public:
285   ClassifyRefs(AnalysisDeclContext &AC) : DC(cast<DeclContext>(AC.getDecl())) {}
286 
287   void VisitDeclStmt(DeclStmt *DS);
288   void VisitUnaryOperator(UnaryOperator *UO);
289   void VisitBinaryOperator(BinaryOperator *BO);
290   void VisitCallExpr(CallExpr *CE);
291   void VisitCastExpr(CastExpr *CE);
292   void VisitOMPExecutableDirective(OMPExecutableDirective *ED);
293 
294   void operator()(Stmt *S) { Visit(S); }
295 
296   Class get(const DeclRefExpr *DRE) const {
297     llvm::DenseMap<const DeclRefExpr*, Class>::const_iterator I
298         = Classification.find(DRE);
299     if (I != Classification.end())
300       return I->second;
301 
302     const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
303     if (!VD || !isTrackedVar(VD))
304       return Ignore;
305 
306     return Init;
307   }
308 };
309 
310 } // namespace
311 
312 static const DeclRefExpr *getSelfInitExpr(VarDecl *VD) {
313   if (VD->getType()->isRecordType())
314     return nullptr;
315   if (Expr *Init = VD->getInit()) {
316     const auto *DRE =
317         dyn_cast<DeclRefExpr>(stripCasts(VD->getASTContext(), Init));
318     if (DRE && DRE->getDecl() == VD)
319       return DRE;
320   }
321   return nullptr;
322 }
323 
324 void ClassifyRefs::classify(const Expr *E, Class C) {
325   // The result of a ?: could also be an lvalue.
326   E = E->IgnoreParens();
327   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
328     classify(CO->getTrueExpr(), C);
329     classify(CO->getFalseExpr(), C);
330     return;
331   }
332 
333   if (const auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) {
334     classify(BCO->getFalseExpr(), C);
335     return;
336   }
337 
338   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
339     classify(OVE->getSourceExpr(), C);
340     return;
341   }
342 
343   if (const auto *ME = dyn_cast<MemberExpr>(E)) {
344     if (const auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
345       if (!VD->isStaticDataMember())
346         classify(ME->getBase(), C);
347     }
348     return;
349   }
350 
351   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
352     switch (BO->getOpcode()) {
353     case BO_PtrMemD:
354     case BO_PtrMemI:
355       classify(BO->getLHS(), C);
356       return;
357     case BO_Comma:
358       classify(BO->getRHS(), C);
359       return;
360     default:
361       return;
362     }
363   }
364 
365   FindVarResult Var = findVar(E, DC);
366   if (const DeclRefExpr *DRE = Var.getDeclRefExpr())
367     Classification[DRE] = std::max(Classification[DRE], C);
368 }
369 
370 void ClassifyRefs::VisitDeclStmt(DeclStmt *DS) {
371   for (auto *DI : DS->decls()) {
372     auto *VD = dyn_cast<VarDecl>(DI);
373     if (VD && isTrackedVar(VD))
374       if (const DeclRefExpr *DRE = getSelfInitExpr(VD))
375         Classification[DRE] = SelfInit;
376   }
377 }
378 
379 void ClassifyRefs::VisitBinaryOperator(BinaryOperator *BO) {
380   // Ignore the evaluation of a DeclRefExpr on the LHS of an assignment. If this
381   // is not a compound-assignment, we will treat it as initializing the variable
382   // when TransferFunctions visits it. A compound-assignment does not affect
383   // whether a variable is uninitialized, and there's no point counting it as a
384   // use.
385   if (BO->isCompoundAssignmentOp())
386     classify(BO->getLHS(), Use);
387   else if (BO->getOpcode() == BO_Assign || BO->getOpcode() == BO_Comma)
388     classify(BO->getLHS(), Ignore);
389 }
390 
391 void ClassifyRefs::VisitUnaryOperator(UnaryOperator *UO) {
392   // Increment and decrement are uses despite there being no lvalue-to-rvalue
393   // conversion.
394   if (UO->isIncrementDecrementOp())
395     classify(UO->getSubExpr(), Use);
396 }
397 
398 void ClassifyRefs::VisitOMPExecutableDirective(OMPExecutableDirective *ED) {
399   for (Stmt *S : OMPExecutableDirective::used_clauses_children(ED->clauses()))
400     classify(cast<Expr>(S), Use);
401 }
402 
403 static bool isPointerToConst(const QualType &QT) {
404   return QT->isAnyPointerType() && QT->getPointeeType().isConstQualified();
405 }
406 
407 void ClassifyRefs::VisitCallExpr(CallExpr *CE) {
408   // Classify arguments to std::move as used.
409   if (CE->isCallToStdMove()) {
410     // RecordTypes are handled in SemaDeclCXX.cpp.
411     if (!CE->getArg(0)->getType()->isRecordType())
412       classify(CE->getArg(0), Use);
413     return;
414   }
415 
416   // If a value is passed by const pointer or by const reference to a function,
417   // we should not assume that it is initialized by the call, and we
418   // conservatively do not assume that it is used.
419   for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end();
420        I != E; ++I) {
421     if ((*I)->isGLValue()) {
422       if ((*I)->getType().isConstQualified())
423         classify((*I), Ignore);
424     } else if (isPointerToConst((*I)->getType())) {
425       const Expr *Ex = stripCasts(DC->getParentASTContext(), *I);
426       const auto *UO = dyn_cast<UnaryOperator>(Ex);
427       if (UO && UO->getOpcode() == UO_AddrOf)
428         Ex = UO->getSubExpr();
429       classify(Ex, Ignore);
430     }
431   }
432 }
433 
434 void ClassifyRefs::VisitCastExpr(CastExpr *CE) {
435   if (CE->getCastKind() == CK_LValueToRValue)
436     classify(CE->getSubExpr(), Use);
437   else if (const auto *CSE = dyn_cast<CStyleCastExpr>(CE)) {
438     if (CSE->getType()->isVoidType()) {
439       // Squelch any detected load of an uninitialized value if
440       // we cast it to void.
441       // e.g. (void) x;
442       classify(CSE->getSubExpr(), Ignore);
443     }
444   }
445 }
446 
447 //------------------------------------------------------------------------====//
448 // Transfer function for uninitialized values analysis.
449 //====------------------------------------------------------------------------//
450 
451 namespace {
452 
453 class TransferFunctions : public StmtVisitor<TransferFunctions> {
454   CFGBlockValues &vals;
455   const CFG &cfg;
456   const CFGBlock *block;
457   AnalysisDeclContext &ac;
458   const ClassifyRefs &classification;
459   ObjCNoReturn objCNoRet;
460   UninitVariablesHandler &handler;
461 
462 public:
463   TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
464                     const CFGBlock *block, AnalysisDeclContext &ac,
465                     const ClassifyRefs &classification,
466                     UninitVariablesHandler &handler)
467       : vals(vals), cfg(cfg), block(block), ac(ac),
468         classification(classification), objCNoRet(ac.getASTContext()),
469         handler(handler) {}
470 
471   void reportUse(const Expr *ex, const VarDecl *vd);
472 
473   void VisitBinaryOperator(BinaryOperator *bo);
474   void VisitBlockExpr(BlockExpr *be);
475   void VisitCallExpr(CallExpr *ce);
476   void VisitDeclRefExpr(DeclRefExpr *dr);
477   void VisitDeclStmt(DeclStmt *ds);
478   void VisitGCCAsmStmt(GCCAsmStmt *as);
479   void VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS);
480   void VisitObjCMessageExpr(ObjCMessageExpr *ME);
481   void VisitOMPExecutableDirective(OMPExecutableDirective *ED);
482 
483   bool isTrackedVar(const VarDecl *vd) {
484     return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl()));
485   }
486 
487   FindVarResult findVar(const Expr *ex) {
488     return ::findVar(ex, cast<DeclContext>(ac.getDecl()));
489   }
490 
491   UninitUse getUninitUse(const Expr *ex, const VarDecl *vd, Value v) {
492     UninitUse Use(ex, isAlwaysUninit(v));
493 
494     assert(isUninitialized(v));
495     if (Use.getKind() == UninitUse::Always)
496       return Use;
497 
498     // If an edge which leads unconditionally to this use did not initialize
499     // the variable, we can say something stronger than 'may be uninitialized':
500     // we can say 'either it's used uninitialized or you have dead code'.
501     //
502     // We track the number of successors of a node which have been visited, and
503     // visit a node once we have visited all of its successors. Only edges where
504     // the variable might still be uninitialized are followed. Since a variable
505     // can't transfer from being initialized to being uninitialized, this will
506     // trace out the subgraph which inevitably leads to the use and does not
507     // initialize the variable. We do not want to skip past loops, since their
508     // non-termination might be correlated with the initialization condition.
509     //
510     // For example:
511     //
512     //         void f(bool a, bool b) {
513     // block1:   int n;
514     //           if (a) {
515     // block2:     if (b)
516     // block3:       n = 1;
517     // block4:   } else if (b) {
518     // block5:     while (!a) {
519     // block6:       do_work(&a);
520     //               n = 2;
521     //             }
522     //           }
523     // block7:   if (a)
524     // block8:     g();
525     // block9:   return n;
526     //         }
527     //
528     // Starting from the maybe-uninitialized use in block 9:
529     //  * Block 7 is not visited because we have only visited one of its two
530     //    successors.
531     //  * Block 8 is visited because we've visited its only successor.
532     // From block 8:
533     //  * Block 7 is visited because we've now visited both of its successors.
534     // From block 7:
535     //  * Blocks 1, 2, 4, 5, and 6 are not visited because we didn't visit all
536     //    of their successors (we didn't visit 4, 3, 5, 6, and 5, respectively).
537     //  * Block 3 is not visited because it initializes 'n'.
538     // Now the algorithm terminates, having visited blocks 7 and 8, and having
539     // found the frontier is blocks 2, 4, and 5.
540     //
541     // 'n' is definitely uninitialized for two edges into block 7 (from blocks 2
542     // and 4), so we report that any time either of those edges is taken (in
543     // each case when 'b == false'), 'n' is used uninitialized.
544     SmallVector<const CFGBlock*, 32> Queue;
545     SmallVector<unsigned, 32> SuccsVisited(cfg.getNumBlockIDs(), 0);
546     Queue.push_back(block);
547     // Specify that we've already visited all successors of the starting block.
548     // This has the dual purpose of ensuring we never add it to the queue, and
549     // of marking it as not being a candidate element of the frontier.
550     SuccsVisited[block->getBlockID()] = block->succ_size();
551     while (!Queue.empty()) {
552       const CFGBlock *B = Queue.pop_back_val();
553 
554       // If the use is always reached from the entry block, make a note of that.
555       if (B == &cfg.getEntry())
556         Use.setUninitAfterCall();
557 
558       for (CFGBlock::const_pred_iterator I = B->pred_begin(), E = B->pred_end();
559            I != E; ++I) {
560         const CFGBlock *Pred = *I;
561         if (!Pred)
562           continue;
563 
564         Value AtPredExit = vals.getValue(Pred, B, vd);
565         if (AtPredExit == Initialized)
566           // This block initializes the variable.
567           continue;
568         if (AtPredExit == MayUninitialized &&
569             vals.getValue(B, nullptr, vd) == Uninitialized) {
570           // This block declares the variable (uninitialized), and is reachable
571           // from a block that initializes the variable. We can't guarantee to
572           // give an earlier location for the diagnostic (and it appears that
573           // this code is intended to be reachable) so give a diagnostic here
574           // and go no further down this path.
575           Use.setUninitAfterDecl();
576           continue;
577         }
578 
579         unsigned &SV = SuccsVisited[Pred->getBlockID()];
580         if (!SV) {
581           // When visiting the first successor of a block, mark all NULL
582           // successors as having been visited.
583           for (CFGBlock::const_succ_iterator SI = Pred->succ_begin(),
584                                              SE = Pred->succ_end();
585                SI != SE; ++SI)
586             if (!*SI)
587               ++SV;
588         }
589 
590         if (++SV == Pred->succ_size())
591           // All paths from this block lead to the use and don't initialize the
592           // variable.
593           Queue.push_back(Pred);
594       }
595     }
596 
597     // Scan the frontier, looking for blocks where the variable was
598     // uninitialized.
599     for (const auto *Block : cfg) {
600       unsigned BlockID = Block->getBlockID();
601       const Stmt *Term = Block->getTerminatorStmt();
602       if (SuccsVisited[BlockID] && SuccsVisited[BlockID] < Block->succ_size() &&
603           Term) {
604         // This block inevitably leads to the use. If we have an edge from here
605         // to a post-dominator block, and the variable is uninitialized on that
606         // edge, we have found a bug.
607         for (CFGBlock::const_succ_iterator I = Block->succ_begin(),
608              E = Block->succ_end(); I != E; ++I) {
609           const CFGBlock *Succ = *I;
610           if (Succ && SuccsVisited[Succ->getBlockID()] >= Succ->succ_size() &&
611               vals.getValue(Block, Succ, vd) == Uninitialized) {
612             // Switch cases are a special case: report the label to the caller
613             // as the 'terminator', not the switch statement itself. Suppress
614             // situations where no label matched: we can't be sure that's
615             // possible.
616             if (isa<SwitchStmt>(Term)) {
617               const Stmt *Label = Succ->getLabel();
618               if (!Label || !isa<SwitchCase>(Label))
619                 // Might not be possible.
620                 continue;
621               UninitUse::Branch Branch;
622               Branch.Terminator = Label;
623               Branch.Output = 0; // Ignored.
624               Use.addUninitBranch(Branch);
625             } else {
626               UninitUse::Branch Branch;
627               Branch.Terminator = Term;
628               Branch.Output = I - Block->succ_begin();
629               Use.addUninitBranch(Branch);
630             }
631           }
632         }
633       }
634     }
635 
636     return Use;
637   }
638 };
639 
640 } // namespace
641 
642 void TransferFunctions::reportUse(const Expr *ex, const VarDecl *vd) {
643   Value v = vals[vd];
644   if (isUninitialized(v))
645     handler.handleUseOfUninitVariable(vd, getUninitUse(ex, vd, v));
646 }
647 
648 void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS) {
649   // This represents an initialization of the 'element' value.
650   if (const auto *DS = dyn_cast<DeclStmt>(FS->getElement())) {
651     const auto *VD = cast<VarDecl>(DS->getSingleDecl());
652     if (isTrackedVar(VD))
653       vals[VD] = Initialized;
654   }
655 }
656 
657 void TransferFunctions::VisitOMPExecutableDirective(
658     OMPExecutableDirective *ED) {
659   for (Stmt *S : OMPExecutableDirective::used_clauses_children(ED->clauses())) {
660     assert(S && "Expected non-null used-in-clause child.");
661     Visit(S);
662   }
663   if (!ED->isStandaloneDirective())
664     Visit(ED->getStructuredBlock());
665 }
666 
667 void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
668   const BlockDecl *bd = be->getBlockDecl();
669   for (const auto &I : bd->captures()) {
670     const VarDecl *vd = I.getVariable();
671     if (!isTrackedVar(vd))
672       continue;
673     if (I.isByRef()) {
674       vals[vd] = Initialized;
675       continue;
676     }
677     reportUse(be, vd);
678   }
679 }
680 
681 void TransferFunctions::VisitCallExpr(CallExpr *ce) {
682   if (Decl *Callee = ce->getCalleeDecl()) {
683     if (Callee->hasAttr<ReturnsTwiceAttr>()) {
684       // After a call to a function like setjmp or vfork, any variable which is
685       // initialized anywhere within this function may now be initialized. For
686       // now, just assume such a call initializes all variables.  FIXME: Only
687       // mark variables as initialized if they have an initializer which is
688       // reachable from here.
689       vals.setAllScratchValues(Initialized);
690     }
691     else if (Callee->hasAttr<AnalyzerNoReturnAttr>()) {
692       // Functions labeled like "analyzer_noreturn" are often used to denote
693       // "panic" functions that in special debug situations can still return,
694       // but for the most part should not be treated as returning.  This is a
695       // useful annotation borrowed from the static analyzer that is useful for
696       // suppressing branch-specific false positives when we call one of these
697       // functions but keep pretending the path continues (when in reality the
698       // user doesn't care).
699       vals.setAllScratchValues(Unknown);
700     }
701   }
702 }
703 
704 void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
705   switch (classification.get(dr)) {
706   case ClassifyRefs::Ignore:
707     break;
708   case ClassifyRefs::Use:
709     reportUse(dr, cast<VarDecl>(dr->getDecl()));
710     break;
711   case ClassifyRefs::Init:
712     vals[cast<VarDecl>(dr->getDecl())] = Initialized;
713     break;
714   case ClassifyRefs::SelfInit:
715       handler.handleSelfInit(cast<VarDecl>(dr->getDecl()));
716     break;
717   }
718 }
719 
720 void TransferFunctions::VisitBinaryOperator(BinaryOperator *BO) {
721   if (BO->getOpcode() == BO_Assign) {
722     FindVarResult Var = findVar(BO->getLHS());
723     if (const VarDecl *VD = Var.getDecl())
724       vals[VD] = Initialized;
725   }
726 }
727 
728 void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
729   for (auto *DI : DS->decls()) {
730     auto *VD = dyn_cast<VarDecl>(DI);
731     if (VD && isTrackedVar(VD)) {
732       if (getSelfInitExpr(VD)) {
733         // If the initializer consists solely of a reference to itself, we
734         // explicitly mark the variable as uninitialized. This allows code
735         // like the following:
736         //
737         //   int x = x;
738         //
739         // to deliberately leave a variable uninitialized. Different analysis
740         // clients can detect this pattern and adjust their reporting
741         // appropriately, but we need to continue to analyze subsequent uses
742         // of the variable.
743         vals[VD] = Uninitialized;
744       } else if (VD->getInit()) {
745         // Treat the new variable as initialized.
746         vals[VD] = Initialized;
747       } else {
748         // No initializer: the variable is now uninitialized. This matters
749         // for cases like:
750         //   while (...) {
751         //     int n;
752         //     use(n);
753         //     n = 0;
754         //   }
755         // FIXME: Mark the variable as uninitialized whenever its scope is
756         // left, since its scope could be re-entered by a jump over the
757         // declaration.
758         vals[VD] = Uninitialized;
759       }
760     }
761   }
762 }
763 
764 void TransferFunctions::VisitGCCAsmStmt(GCCAsmStmt *as) {
765   // An "asm goto" statement is a terminator that may initialize some variables.
766   if (!as->isAsmGoto())
767     return;
768 
769   for (const Expr *o : as->outputs())
770     if (const VarDecl *VD = findVar(o).getDecl())
771       vals[VD] = Initialized;
772 }
773 
774 void TransferFunctions::VisitObjCMessageExpr(ObjCMessageExpr *ME) {
775   // If the Objective-C message expression is an implicit no-return that
776   // is not modeled in the CFG, set the tracked dataflow values to Unknown.
777   if (objCNoRet.isImplicitNoReturn(ME)) {
778     vals.setAllScratchValues(Unknown);
779   }
780 }
781 
782 //------------------------------------------------------------------------====//
783 // High-level "driver" logic for uninitialized values analysis.
784 //====------------------------------------------------------------------------//
785 
786 static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
787                        AnalysisDeclContext &ac, CFGBlockValues &vals,
788                        const ClassifyRefs &classification,
789                        llvm::BitVector &wasAnalyzed,
790                        UninitVariablesHandler &handler) {
791   wasAnalyzed[block->getBlockID()] = true;
792   vals.resetScratch();
793   // Merge in values of predecessor blocks.
794   bool isFirst = true;
795   for (CFGBlock::const_pred_iterator I = block->pred_begin(),
796        E = block->pred_end(); I != E; ++I) {
797     const CFGBlock *pred = *I;
798     if (!pred)
799       continue;
800     if (wasAnalyzed[pred->getBlockID()]) {
801       vals.mergeIntoScratch(vals.getValueVector(pred), isFirst);
802       isFirst = false;
803     }
804   }
805   // Apply the transfer function.
806   TransferFunctions tf(vals, cfg, block, ac, classification, handler);
807   for (const auto &I : *block) {
808     if (Optional<CFGStmt> cs = I.getAs<CFGStmt>())
809       tf.Visit(const_cast<Stmt *>(cs->getStmt()));
810   }
811   CFGTerminator terminator = block->getTerminator();
812   if (GCCAsmStmt *as = dyn_cast_or_null<GCCAsmStmt>(terminator.getStmt()))
813     if (as->isAsmGoto())
814       tf.Visit(as);
815   return vals.updateValueVectorWithScratch(block);
816 }
817 
818 namespace {
819 
820 /// PruneBlocksHandler is a special UninitVariablesHandler that is used
821 /// to detect when a CFGBlock has any *potential* use of an uninitialized
822 /// variable.  It is mainly used to prune out work during the final
823 /// reporting pass.
824 struct PruneBlocksHandler : public UninitVariablesHandler {
825   /// Records if a CFGBlock had a potential use of an uninitialized variable.
826   llvm::BitVector hadUse;
827 
828   /// Records if any CFGBlock had a potential use of an uninitialized variable.
829   bool hadAnyUse = false;
830 
831   /// The current block to scribble use information.
832   unsigned currentBlock = 0;
833 
834   PruneBlocksHandler(unsigned numBlocks) : hadUse(numBlocks, false) {}
835 
836   ~PruneBlocksHandler() override = default;
837 
838   void handleUseOfUninitVariable(const VarDecl *vd,
839                                  const UninitUse &use) override {
840     hadUse[currentBlock] = true;
841     hadAnyUse = true;
842   }
843 
844   /// Called when the uninitialized variable analysis detects the
845   /// idiom 'int x = x'.  All other uses of 'x' within the initializer
846   /// are handled by handleUseOfUninitVariable.
847   void handleSelfInit(const VarDecl *vd) override {
848     hadUse[currentBlock] = true;
849     hadAnyUse = true;
850   }
851 };
852 
853 } // namespace
854 
855 void clang::runUninitializedVariablesAnalysis(
856     const DeclContext &dc,
857     const CFG &cfg,
858     AnalysisDeclContext &ac,
859     UninitVariablesHandler &handler,
860     UninitVariablesAnalysisStats &stats) {
861   CFGBlockValues vals(cfg);
862   vals.computeSetOfDeclarations(dc);
863   if (vals.hasNoDeclarations())
864     return;
865 
866   stats.NumVariablesAnalyzed = vals.getNumEntries();
867 
868   // Precompute which expressions are uses and which are initializations.
869   ClassifyRefs classification(ac);
870   cfg.VisitBlockStmts(classification);
871 
872   // Mark all variables uninitialized at the entry.
873   const CFGBlock &entry = cfg.getEntry();
874   ValueVector &vec = vals.getValueVector(&entry);
875   const unsigned n = vals.getNumEntries();
876   for (unsigned j = 0; j < n; ++j) {
877     vec[j] = Uninitialized;
878   }
879 
880   // Proceed with the workist.
881   ForwardDataflowWorklist worklist(cfg, ac);
882   llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
883   worklist.enqueueSuccessors(&cfg.getEntry());
884   llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
885   wasAnalyzed[cfg.getEntry().getBlockID()] = true;
886   PruneBlocksHandler PBH(cfg.getNumBlockIDs());
887 
888   while (const CFGBlock *block = worklist.dequeue()) {
889     PBH.currentBlock = block->getBlockID();
890 
891     // Did the block change?
892     bool changed = runOnBlock(block, cfg, ac, vals,
893                               classification, wasAnalyzed, PBH);
894     ++stats.NumBlockVisits;
895     if (changed || !previouslyVisited[block->getBlockID()])
896       worklist.enqueueSuccessors(block);
897     previouslyVisited[block->getBlockID()] = true;
898   }
899 
900   if (!PBH.hadAnyUse)
901     return;
902 
903   // Run through the blocks one more time, and report uninitialized variables.
904   for (const auto *block : cfg)
905     if (PBH.hadUse[block->getBlockID()]) {
906       runOnBlock(block, cfg, ac, vals, classification, wasAnalyzed, handler);
907       ++stats.NumBlockVisits;
908     }
909 }
910 
911 UninitVariablesHandler::~UninitVariablesHandler() = default;
912