clang 24.0.0git
DataflowEnvironment.cpp
Go to the documentation of this file.
1//===-- DataflowEnvironment.cpp ---------------------------------*- C++ -*-===//
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 defines an Environment class that is used by dataflow analyses
10// that run over Control-Flow Graphs (CFGs) to keep track of the state of the
11// program at given program points.
12//
13//===----------------------------------------------------------------------===//
14
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/Stmt.h"
21#include "clang/AST/Type.h"
28#include "clang/Basic/LLVM.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/MapVector.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/ScopeExit.h"
34#include "llvm/ADT/SetVector.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/Support/ErrorHandling.h"
37#include <cassert>
38#include <memory>
39#include <optional>
40#include <stack>
41#include <utility>
42
43#define DEBUG_TYPE "dataflow"
44
45namespace clang {
46namespace dataflow {
47
48namespace {
49
50class SimpleBoolModel final : public Environment::BoolModel {
51public:
52 SimpleBoolModel() : BoolModel(BoolModelKind::Simple) {}
53
54 static bool classof(const BoolModel *M) {
55 return M->getKind() == BoolModelKind::Simple;
56 }
57
58 std::unique_ptr<BoolModel> clone() const override {
59 return std::make_unique<SimpleBoolModel>(*this);
60 }
61
62 void onFork() override {}
63
64 void assume(const Formula &F) override {
65 if (HasContradiction)
66 return;
67 unsigned PrevSize = AtomToVal.size();
68 // Given that F is assumed true, see if we can force the assignment
69 // of any atoms and ultimately reduce F to a literal (if possible).
70 // For example, if F is `A && B`, we will force `A` and `B` to be true.
71 // If F is `A || B`, we will only force an assignment if one of A or B is
72 // already known to be false.
73 assumeFormula(/*AssumedVal=*/true, F);
74 if (HasContradiction)
75 return;
76
77 if (std::optional<bool> Val = getLiteralValue(F)) {
78 if (!*Val) {
79 HasContradiction = true;
80 return;
81 }
82 } else {
83 // Retain `F` in `AssumedFormulas` only if it has not yet been reduced to
84 // a known truth value in `AtomToVal` (e.g., `A || B` or `A == B` where
85 // neither side is known yet).
86 //
87 // - Why save unresolved formulas: a compound formula (like
88 // `EqVal => (LHS == RHS)` from a comparison expression) is often
89 // assumed while its atoms are still unknown; when we later follow a
90 // branch that fixes one of those atoms, the propagation loop below can
91 // reduce the saved formula to concrete `AtomToVal` entries.
92 //
93 // - Skipping formulas that already evaluate to `true` avoids bloating
94 // `AssumedFormulas` with single-atom and conjunctive assumptions that
95 // are already fully represented by `AtomToVal` (though it also drops
96 // disjunctive formulas that were reduced using a branch-local atom,
97 // such as on the RHS of a short-circuit `&&` or `||`).
98 // TODO: We may want to retain some disjunctive formulas, but would need
99 // to profile and see how much it helps vs how much it costs.
100 AssumedFormulas.insert(&F);
101 }
102
103 if (AtomToVal.size() == PrevSize)
104 return;
105
106 // Propagate newly learned atom values through any pending assumed formulas.
107 // Note: Do not remove formulas from `AssumedFormulas` when they evaluate to
108 // `true` in a branch, because the atoms that satisfied them may be
109 // branch-local and discarded at a subsequent `join`, where the formula
110 // itself still holds on both branches.
111 bool Changed = true;
112 while (Changed) {
113 Changed = false;
114 for (const Formula *Pending : AssumedFormulas) {
115 unsigned Before = AtomToVal.size();
116 assumeFormula(/*AssumedVal=*/true, *Pending);
117 if (HasContradiction)
118 return;
119 if (auto V = getLiteralValue(*Pending); V.has_value() && *V == false) {
120 HasContradiction = true;
121 return;
122 }
123 if (AtomToVal.size() > Before)
124 Changed = true;
125 }
126 }
127 }
128
129 bool proves(const Formula &F) const override {
130 if (HasContradiction)
131 return true;
132 auto V = getLiteralValue(F);
133 return V.value_or(false);
134 }
135
136 bool allows(const Formula &F) const override {
137 if (HasContradiction)
138 return false;
139 auto V = getLiteralValue(F);
140 // We are conservative in the negative direction: if we can't determine the
141 // value, assume it is allowed.
142 return V.value_or(true);
143 }
144
145 BoolValue &joinBoolValues(BoolValue &Val1, const BoolModel &Model1,
146 BoolValue &Val2, const BoolModel &Model2,
147 Environment &JoinedEnv) override {
148 const auto &S1 = cast<SimpleBoolModel>(Model1);
149 const auto &S2 = cast<SimpleBoolModel>(Model2);
150 if (S1.HasContradiction)
151 return Val2;
152 if (S2.HasContradiction)
153 return Val1;
154 if (auto V1 = S1.getLiteralValue(Val1.formula());
155 V1.has_value() && V1 == S2.getLiteralValue(Val2.formula()))
156 return JoinedEnv.getBoolLiteralValue(*V1);
157 return JoinedEnv.makeAtomicBoolValue();
158 }
159
160 void join(const BoolModel &ModelA, const BoolModel &ModelB) override {
161 const auto &SA = cast<SimpleBoolModel>(ModelA);
162 const auto &SB = cast<SimpleBoolModel>(ModelB);
163 AtomToVal.clear();
164 AssumedFormulas.clear();
165 HasContradiction = false;
166
167 if (SA.HasContradiction && SB.HasContradiction) {
168 HasContradiction = true;
169 } else if (SA.HasContradiction) {
170 AtomToVal = SB.AtomToVal;
171 AssumedFormulas = SB.AssumedFormulas;
172 } else if (SB.HasContradiction) {
173 AtomToVal = SA.AtomToVal;
174 AssumedFormulas = SA.AssumedFormulas;
175 } else {
176 // Intersect the AtomToVal maps.
177 for (const auto &[A, V] : SA.AtomToVal) {
178 auto It = SB.AtomToVal.find(A);
179 if (It != SB.AtomToVal.end() && V == It->second)
180 AtomToVal.insert({A, V});
181 }
182
183 // Keep assumed formulas that hold on both branches (and are not already
184 // reduced to `true` by the joined `AtomToVal`): either because both
185 // environments still carry `F` as an unresolved formula, or because one
186 // branch carries `F` and the other branch's `AtomToVal` assignments
187 // already prove `F`. Any branch-local formulas not proved by the other
188 // branch are dropped here, which shrinks `AssumedFormulas` at joins.
189 for (const Formula *F : SA.AssumedFormulas) {
190 if (!proves(*F) && (SB.AssumedFormulas.contains(F) || SB.proves(*F)))
191 AssumedFormulas.insert(F);
192 }
193 for (const Formula *F : SB.AssumedFormulas) {
194 if (!proves(*F) && SA.proves(*F))
195 AssumedFormulas.insert(F);
196 }
197 }
198 }
199
200 LatticeEffect widen(const BoolModel &PrevModel) override {
201 const auto &PrevSimple = cast<SimpleBoolModel>(PrevModel);
202 SimpleBoolModel Widened;
203 Widened.join(*this, PrevSimple);
204 LatticeEffect Effect = Widened.isEquivalentTo(PrevSimple)
207 *this = std::move(Widened);
208 return Effect;
209 }
210
211 bool isEquivalentTo(const BoolModel &Other) const override {
212 const auto &OtherSimple = cast<SimpleBoolModel>(Other);
213 if (HasContradiction != OtherSimple.HasContradiction)
214 return false;
215 if (HasContradiction)
216 return true;
217 return AtomToVal == OtherSimple.AtomToVal &&
218 AssumedFormulas.size() == OtherSimple.AssumedFormulas.size() &&
219 // SetVector::operator== compares insertion order, so check set
220 // membership.
221 llvm::all_of(AssumedFormulas, [&](const Formula *F) {
222 return OtherSimple.AssumedFormulas.contains(F);
223 });
224 }
225
226 Atom getFlowConditionToken() const override {
227 llvm_unreachable(
228 "getFlowConditionToken() is only supported in SatBoolModel");
229 }
230
231 void dump(raw_ostream &OS) const override {
232 OS << "SimpleBoolModel:\n";
233 OS << " HasContradiction: " << HasContradiction << "\n";
234 OS << " AtomToVal:\n";
235 SmallVector<std::pair<Atom, bool>> SortedAtomToVal(AtomToVal.begin(),
236 AtomToVal.end());
237 llvm::sort(SortedAtomToVal, llvm::less_first());
238 for (auto [A, V] : SortedAtomToVal)
239 OS << " " << A << " = " << (V ? "true" : "false") << "\n";
240 OS << " AssumedFormulas:\n";
241 for (const Formula *F : AssumedFormulas)
242 OS << " " << *F << "\n";
243 }
244
245private:
246 std::optional<bool> getAtomValue(Atom A) const {
247 auto It = AtomToVal.find(A);
248 if (It == AtomToVal.end())
249 return std::nullopt;
250 return It->second;
251 }
252
253 std::optional<bool> getLiteralValue(const Formula &F) const {
254 switch (F.kind()) {
255 case Formula::AtomRef:
256 return getAtomValue(F.getAtom());
257 case Formula::Literal:
258 return F.literal();
259 case Formula::Not: {
260 ArrayRef<const Formula *> Operands = F.operands();
261 assert(Operands.size() == 1);
262 if (std::optional<bool> V = getLiteralValue(*Operands[0]))
263 return !*V;
264 return std::nullopt;
265 }
266 case Formula::And: {
267 ArrayRef<const Formula *> Operands = F.operands();
268 assert(Operands.size() == 2);
269 auto &LHS = *Operands[0];
270 auto &RHS = *Operands[1];
271 if (std::optional<bool> Left = getLiteralValue(LHS))
272 return !*Left ? Left : getLiteralValue(RHS);
273 if (std::optional<bool> Right = getLiteralValue(RHS);
274 Right.has_value() && *Right == false)
275 return Right;
276 return std::nullopt;
277 }
278 case Formula::Or: {
279 ArrayRef<const Formula *> Operands = F.operands();
280 assert(Operands.size() == 2);
281 auto &LHS = *Operands[0];
282 auto &RHS = *Operands[1];
283 if (std::optional<bool> Left = getLiteralValue(LHS))
284 return *Left ? Left : getLiteralValue(RHS);
285 if (std::optional<bool> Right = getLiteralValue(RHS);
286 Right.has_value() && *Right == true)
287 return Right;
288 return std::nullopt;
289 }
290 case Formula::Implies: {
291 ArrayRef<const Formula *> Operands = F.operands();
292 assert(Operands.size() == 2);
293 auto &LHS = *Operands[0];
294 auto &RHS = *Operands[1];
295 if (std::optional<bool> Left = getLiteralValue(LHS))
296 return !*Left ? true : getLiteralValue(RHS);
297 if (std::optional<bool> Right = getLiteralValue(RHS);
298 Right.has_value() && *Right == true)
299 return true;
300 return std::nullopt;
301 }
302 case Formula::Equal: {
303 ArrayRef<const Formula *> Operands = F.operands();
304 assert(Operands.size() == 2);
305 auto &LHS = *Operands[0];
306 auto &RHS = *Operands[1];
307 // If the formula is of the form `A == A`, then we can simplify to
308 // true, without needing to know A is set to a literal value.
309 if (&LHS == &RHS)
310 return true;
311 // Similarly, if the formula is of the form `A == !A` (or !A == A),
312 // then we can simplify to false.
313 // We should consider lifting such simplification with identities into a
314 // a separate function (there are more cases, e.g., `A OR !A` is true),
315 // while keeping this function focused on cases where the operands are
316 // literal values.
317 if ((LHS.kind() == Formula::Not && LHS.operands()[0] == &RHS) ||
318 (RHS.kind() == Formula::Not && RHS.operands()[0] == &LHS))
319 return false;
320 auto V_L = getLiteralValue(LHS);
321 if (!V_L.has_value())
322 return std::nullopt;
323 auto V_R = getLiteralValue(RHS);
324 if (!V_R.has_value())
325 return std::nullopt;
326 return *V_L == *V_R;
327 }
328 }
329 }
330
331 // Updates atom assignments under the assumption that subformula `F`
332 // evaluates to `AssumedVal` (i.e., `F == AssumedVal`).
333 //
334 // Top-level `assume(F)` starts with `AssumedVal = true`, and recursive
335 // calls flip `AssumedVal` when traversing negations (`Formula::Not`) or
336 // comparisons (`Formula::Equal`) against known boolean values.
337 //
338 // For example:
339 // - for `assume(!A)`, then `A` must be `false`
340 // - for `assume(A && B)`, then both `A` and `B` must be `true`.
341 void assumeFormula(bool AssumedVal, const Formula &F) {
342 if (HasContradiction)
343 return;
344 switch (F.kind()) {
345 case Formula::AtomRef: {
346 // Base case: `F` is a single atom, so assuming `F == AssumedVal` directly
347 // binds this atom to `AssumedVal`, or marks the environment as having a
348 // contradiction if the atom was already bound to the opposite value.
349 auto [It, Inserted] = AtomToVal.try_emplace(F.getAtom(), AssumedVal);
350 if (!Inserted && It->second != AssumedVal)
351 HasContradiction = true;
352 break;
353 }
354 case Formula::Literal:
355 if (F.literal() != AssumedVal)
356 HasContradiction = true;
357 break;
358 case Formula::Not: {
359 // Assuming `(!Operand) == AssumedVal` is equivalent to assuming
360 // `Operand == !AssumedVal`.
361 ArrayRef<const Formula *> Operands = F.operands();
362 assert(Operands.size() == 1);
363 assumeFormula(!AssumedVal, *Operands[0]);
364 break;
365 }
366 case Formula::And: {
367 // - If `AssumedVal == true` (`LHS && RHS`), both operands must be `true`.
368 // - If `AssumedVal == false` (`!(LHS && RHS)` <=> `!LHS || !RHS`), at
369 // least one operand is `false`; if one operand is already known `true`,
370 // the other must be `false`.
371 ArrayRef<const Formula *> Operands = F.operands();
372 assert(Operands.size() == 2);
373 auto &LHS = *Operands[0];
374 auto &RHS = *Operands[1];
375 if (AssumedVal == true) {
376 assumeFormula(true, LHS);
377 assumeFormula(true, RHS);
378 } else {
379 if (auto V = getLiteralValue(LHS); V.has_value() && *V == true)
380 assumeFormula(false, RHS);
381 else if (auto V = getLiteralValue(RHS); V.has_value() && *V == true)
382 assumeFormula(false, LHS);
383 }
384 break;
385 }
386 case Formula::Or: {
387 // - If `AssumedVal == false` (`!(LHS || RHS)` <=> `!LHS && !RHS`), both
388 // operands must be `false`.
389 // - If `AssumedVal == true` (`LHS || RHS`), at least one operand is
390 // `true`; if one operand is already known `false`, the other must be
391 // `true`.
392 ArrayRef<const Formula *> Operands = F.operands();
393 assert(Operands.size() == 2);
394 auto &LHS = *Operands[0];
395 auto &RHS = *Operands[1];
396 if (AssumedVal == false) {
397 assumeFormula(false, LHS);
398 assumeFormula(false, RHS);
399 } else {
400 if (auto V = getLiteralValue(LHS); V.has_value() && *V == false)
401 assumeFormula(true, RHS);
402 else if (auto V = getLiteralValue(RHS); V.has_value() && *V == false)
403 assumeFormula(true, LHS);
404 }
405 break;
406 }
407 case Formula::Implies: {
408 // `LHS => RHS` is equivalent to `!LHS || RHS`.
409 // - If `AssumedVal == false` (`!(LHS => RHS)`), then `LHS` must be `true`
410 // and `RHS` must be `false`.
411 // - If `AssumedVal == true` (`LHS => RHS`):
412 // - Modus ponens: if `LHS` is known `true`, then `RHS` must be `true`.
413 // - Modus tollens: if `RHS` is known `false`, then `LHS` must be
414 // `false`.
415 ArrayRef<const Formula *> Operands = F.operands();
416 assert(Operands.size() == 2);
417 auto &LHS = *Operands[0];
418 auto &RHS = *Operands[1];
419 if (AssumedVal == false) {
420 assumeFormula(true, LHS);
421 assumeFormula(false, RHS);
422 } else {
423 if (auto V = getLiteralValue(LHS); V.has_value() && *V == true)
424 assumeFormula(true, RHS);
425 else if (auto V = getLiteralValue(RHS); V.has_value() && *V == false)
426 assumeFormula(false, LHS);
427 }
428 break;
429 }
430 case Formula::Equal: {
431 // Assuming `(LHS == RHS) == AssumedVal`: if one side already has a known
432 // truth value `*V`, then the other side must evaluate to
433 // `(AssumedVal == *V)`.
434 ArrayRef<const Formula *> Operands = F.operands();
435 assert(Operands.size() == 2);
436 auto &LHS = *Operands[0];
437 auto &RHS = *Operands[1];
438 if (auto V = getLiteralValue(LHS)) {
439 assumeFormula(AssumedVal == *V, RHS);
440 } else if (auto V = getLiteralValue(RHS)) {
441 assumeFormula(AssumedVal == *V, LHS);
442 }
443 break;
444 }
445 }
446 }
447
448 llvm::DenseMap<Atom, bool> AtomToVal;
450 bool HasContradiction = false;
451};
452
453class SatBoolModel final : public Environment::BoolModel {
454public:
455 SatBoolModel(DataflowAnalysisContext &DACtx, Atom FlowConditionToken)
456 : BoolModel(BoolModelKind::SAT), DACtx(DACtx),
457 FlowConditionToken(FlowConditionToken) {}
458
459 explicit SatBoolModel(DataflowAnalysisContext &DACtx)
460 : SatBoolModel(DACtx, DACtx.arena().makeFlowConditionToken()) {}
461
462 static bool classof(const BoolModel *M) {
463 return M->getKind() == BoolModelKind::SAT;
464 }
465
466 std::unique_ptr<BoolModel> clone() const override {
467 return std::make_unique<SatBoolModel>(*this);
468 }
469
470 void onFork() override {
471 FlowConditionToken = DACtx.forkFlowCondition(FlowConditionToken);
472 }
473
474 void assume(const Formula &F) override {
475 DACtx.addFlowConditionConstraint(FlowConditionToken, F);
476 }
477
478 bool proves(const Formula &F) const override {
479 return DACtx.flowConditionImplies(FlowConditionToken, F);
480 }
481
482 bool allows(const Formula &F) const override {
483 return DACtx.flowConditionAllows(FlowConditionToken, F);
484 }
485
486 BoolValue &joinBoolValues(BoolValue &Val1, const BoolModel &Model1,
487 BoolValue &Val2, const BoolModel &Model2,
488 Environment &JoinedEnv) override {
489 const auto &Sat1 = cast<SatBoolModel>(Model1);
490 const auto &Sat2 = cast<SatBoolModel>(Model2);
491 auto &A = JoinedEnv.arena();
492 auto &JoinedVal = A.makeAtomRef(A.makeAtom());
493 JoinedEnv.assume(
494 A.makeOr(A.makeAnd(A.makeAtomRef(Sat1.getFlowConditionToken()),
495 A.makeEquals(JoinedVal, Val1.formula())),
496 A.makeAnd(A.makeAtomRef(Sat2.getFlowConditionToken()),
497 A.makeEquals(JoinedVal, Val2.formula()))));
498 return A.makeBoolValue(JoinedVal);
499 }
500
501 void join(const BoolModel &ModelA, const BoolModel &ModelB) override {
502 const auto &SatA = cast<SatBoolModel>(ModelA);
503 const auto &SatB = cast<SatBoolModel>(ModelB);
504 // FIXME: update join to detect backedges and simplify the flow condition
505 // accordingly.
506 FlowConditionToken = DACtx.joinFlowConditions(SatA.FlowConditionToken,
507 SatB.FlowConditionToken);
508 }
509
510 LatticeEffect widen(const BoolModel &PrevModel) override {
511 (void)cast<SatBoolModel>(PrevModel);
513 }
514
515 bool isEquivalentTo(const BoolModel &Other) const override {
517 return true;
518 }
519
520 Atom getFlowConditionToken() const override { return FlowConditionToken; }
521
522 void dump(raw_ostream &OS) const override {
523 DACtx.dumpFlowCondition(FlowConditionToken, OS);
524 }
525
526private:
527 DataflowAnalysisContext &DACtx;
528 Atom FlowConditionToken;
529};
530
531} // namespace
532
533// FIXME: convert these to parameters of the analysis or environment. Current
534// settings have been experimentaly validated, but only for a particular
535// analysis.
536static constexpr int MaxCompositeValueDepth = 3;
537static constexpr int MaxCompositeValueSize = 1000;
538
539/// Returns a map consisting of key-value entries that are present in both maps.
540static llvm::DenseMap<const ValueDecl *, StorageLocation *> intersectDeclToLoc(
541 const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc1,
542 const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc2) {
543 llvm::DenseMap<const ValueDecl *, StorageLocation *> Result;
544 for (auto &Entry : DeclToLoc1) {
545 auto It = DeclToLoc2.find(Entry.first);
546 if (It != DeclToLoc2.end() && Entry.second == It->second)
547 Result.insert({Entry.first, Entry.second});
548 }
549 return Result;
550}
551
552// Performs a join on either `ExprToLoc` or `ExprToVal`.
553// The maps must be consistent in the sense that any entries for the same
554// expression must map to the same location / value. This is the case if we are
555// performing a join for control flow within a full-expression (which is the
556// only case when this function should be used).
557template <typename MapT>
558static MapT joinExprMaps(const MapT &Map1, const MapT &Map2) {
559 MapT Result = Map1;
560
561 for (const auto &Entry : Map2) {
562 [[maybe_unused]] auto [It, Inserted] = Result.insert(Entry);
563 // If there was an existing entry, its value should be the same as for the
564 // entry we were trying to insert.
565 assert(It->second == Entry.second);
566 }
567
568 return Result;
569}
570
571// Whether to consider equivalent two values with an unknown relation.
572//
573// FIXME: this function is a hack enabling unsoundness to support
574// convergence. Once we have widening support for the reference/pointer and
575// struct built-in models, this should be unconditionally `false` (and inlined
576// as such at its call sites).
577static bool equateUnknownValues(Value::Kind K) {
578 switch (K) {
579 case Value::Kind::Integer:
580 case Value::Kind::Pointer:
581 return true;
582 default:
583 return false;
584 }
585}
586
588 const Environment &Env1, Value &Val2,
589 const Environment &Env2,
591 // Note: Potentially costly, but, for booleans, we could check whether both
592 // can be proven equivalent in their respective environments.
593
594 // FIXME: move the reference/pointers logic from `areEquivalentValues` to here
595 // and implement separate, join/widen specific handling for
596 // reference/pointers.
597 switch (Model.compare(Type, Val1, Env1, Val2, Env2)) {
599 return true;
601 return false;
603 return equateUnknownValues(Val1.getKind());
604 }
605 llvm_unreachable("All cases covered in switch");
606}
607
608/// Attempts to join distinct values `Val1` and `Val2` in `Env1` and `Env2`,
609/// respectively, of the same type `Type`. Joining generally produces a single
610/// value that (soundly) approximates the two inputs, although the actual
611/// meaning depends on `Model`.
613 const Environment &Env1, Value &Val2,
614 const Environment &Env2,
615 Environment &JoinedEnv,
617 // Join distinct boolean values preserving information about the constraints
618 // in the respective path conditions.
619 if (isa<BoolValue>(&Val1) && isa<BoolValue>(&Val2)) {
620 // FIXME: Checking both values should be unnecessary, since they should have
621 // a consistent shape. However, right now we can end up with BoolValue's in
622 // integer-typed variables due to our incorrect handling of
623 // boolean-to-integer casts (we just propagate the BoolValue to the result
624 // of the cast). So, a join can encounter an integer in one branch but a
625 // bool in the other.
626 // For example:
627 // ```
628 // std::optional<bool> o;
629 // int x;
630 // if (o.has_value())
631 // x = o.value();
632 // ```
633 return &JoinedEnv.joinBoolValues(cast<BoolValue>(Val1), Env1,
634 cast<BoolValue>(Val2), Env2);
635 }
636
637 Value *JoinedVal = JoinedEnv.createValue(Type);
638 if (JoinedVal)
639 Model.join(Type, Val1, Env1, Val2, Env2, *JoinedVal, JoinedEnv);
640
641 return JoinedVal;
642}
643
645 const Environment &PrevEnv,
646 Value &Current, Environment &CurrentEnv,
648 // Boolean-model widening.
649 if (isa<BoolValue>(Prev) && isa<BoolValue>(Current)) {
650 // FIXME: Checking both values should be unnecessary, but we can currently
651 // end up with `BoolValue`s in integer-typed variables. See comment in
652 // `joinDistinctValues()` for details.
653 auto &PrevBool = cast<BoolValue>(Prev);
654 auto &CurBool = cast<BoolValue>(Current);
655
656 if (isa<TopBoolValue>(Prev))
657 // Safe to return `Prev` here, because Top is never dependent on the
658 // environment.
659 return {&Prev, LatticeEffect::Unchanged};
660
661 // We may need to widen to Top, but before we do so, check whether both
662 // values are implied to be either true or false in the current environment.
663 // In that case, we can simply return a literal instead.
664 bool TruePrev = PrevEnv.proves(PrevBool.formula());
665 bool TrueCur = CurrentEnv.proves(CurBool.formula());
666 if (TruePrev && TrueCur)
667 return {&CurrentEnv.getBoolLiteralValue(true), LatticeEffect::Unchanged};
668 if (!TruePrev && !TrueCur &&
669 PrevEnv.proves(PrevEnv.arena().makeNot(PrevBool.formula())) &&
670 CurrentEnv.proves(CurrentEnv.arena().makeNot(CurBool.formula())))
671 return {&CurrentEnv.getBoolLiteralValue(false), LatticeEffect::Unchanged};
672
673 return {&CurrentEnv.makeTopBoolValue(), LatticeEffect::Changed};
674 }
675
676 // FIXME: Add other built-in model widening.
677
678 // Custom-model widening.
679 if (auto Result = Model.widen(Type, Prev, PrevEnv, Current, CurrentEnv))
680 return *Result;
681
682 return {&Current, equateUnknownValues(Prev.getKind())
685}
686
687// Returns whether the values in `Map1` and `Map2` compare equal for those
688// keys that `Map1` and `Map2` have in common.
689template <typename Key>
690static bool compareKeyToValueMaps(const llvm::MapVector<Key, Value *> &Map1,
691 const llvm::MapVector<Key, Value *> &Map2,
692 const Environment &Env1,
693 const Environment &Env2,
695 for (auto &Entry : Map1) {
696 Key K = Entry.first;
697 assert(K != nullptr);
698
699 Value *Val = Entry.second;
700 assert(Val != nullptr);
701
702 auto It = Map2.find(K);
703 if (It == Map2.end())
704 continue;
705 assert(It->second != nullptr);
706
707 if (!areEquivalentValues(*Val, *It->second) &&
708 !compareDistinctValues(K->getType(), *Val, Env1, *It->second, Env2,
709 Model))
710 return false;
711 }
712
713 return true;
714}
715
716// Perform a join on two `LocToVal` maps.
717static llvm::MapVector<const StorageLocation *, Value *>
718joinLocToVal(const llvm::MapVector<const StorageLocation *, Value *> &LocToVal,
719 const llvm::MapVector<const StorageLocation *, Value *> &LocToVal2,
720 const Environment &Env1, const Environment &Env2,
721 Environment &JoinedEnv, Environment::ValueModel &Model) {
722 llvm::MapVector<const StorageLocation *, Value *> Result;
723 for (auto &Entry : LocToVal) {
724 const StorageLocation *Loc = Entry.first;
725 assert(Loc != nullptr);
726
727 Value *Val = Entry.second;
728 assert(Val != nullptr);
729
730 auto It = LocToVal2.find(Loc);
731 if (It == LocToVal2.end())
732 continue;
733 assert(It->second != nullptr);
734
735 if (Value *JoinedVal = Environment::joinValues(
736 Loc->getType(), Val, Env1, It->second, Env2, JoinedEnv, Model)) {
737 Result.insert({Loc, JoinedVal});
738 }
739 }
740
741 return Result;
742}
743
744// Perform widening on either `LocToVal` or `ExprToVal`. `Key` must be either
745// `const StorageLocation *` or `const Expr *`.
746template <typename Key>
747static llvm::MapVector<Key, Value *>
748widenKeyToValueMap(const llvm::MapVector<Key, Value *> &CurMap,
749 const llvm::MapVector<Key, Value *> &PrevMap,
750 Environment &CurEnv, const Environment &PrevEnv,
751 Environment::ValueModel &Model, LatticeEffect &Effect) {
752 llvm::MapVector<Key, Value *> WidenedMap;
753 for (auto &Entry : CurMap) {
754 Key K = Entry.first;
755 assert(K != nullptr);
756
757 Value *Val = Entry.second;
758 assert(Val != nullptr);
759
760 auto PrevIt = PrevMap.find(K);
761 if (PrevIt == PrevMap.end())
762 continue;
763 assert(PrevIt->second != nullptr);
764
765 if (areEquivalentValues(*Val, *PrevIt->second)) {
766 WidenedMap.insert({K, Val});
767 continue;
768 }
769
770 auto [WidenedVal, ValEffect] = widenDistinctValues(
771 K->getType(), *PrevIt->second, PrevEnv, *Val, CurEnv, Model);
772 WidenedMap.insert({K, WidenedVal});
773 if (ValEffect == LatticeEffect::Changed)
774 Effect = LatticeEffect::Changed;
775 }
776
777 return WidenedMap;
778}
779
780namespace {
781
782// Visitor that builds a map from record prvalues to result objects.
783// For each result object that it encounters, it propagates the storage location
784// of the result object to all record prvalues that can initialize it.
785class ResultObjectVisitor : public AnalysisASTVisitor {
786public:
787 // `ResultObjectMap` will be filled with a map from record prvalues to result
788 // object. If this visitor will traverse a function that returns a record by
789 // value, `LocForRecordReturnVal` is the location to which this record should
790 // be written; otherwise, it is null.
791 explicit ResultObjectVisitor(
792 llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap,
793 RecordStorageLocation *LocForRecordReturnVal,
794 DataflowAnalysisContext &DACtx)
795 : ResultObjectMap(ResultObjectMap),
796 LocForRecordReturnVal(LocForRecordReturnVal), DACtx(DACtx) {}
797
798 // Traverse all member and base initializers of `Ctor`. This function is not
799 // called by `RecursiveASTVisitor`; it should be called manually if we are
800 // analyzing a constructor. `ThisPointeeLoc` is the storage location that
801 // `this` points to.
802 void traverseConstructorInits(const CXXConstructorDecl *Ctor,
803 RecordStorageLocation *ThisPointeeLoc) {
804 assert(ThisPointeeLoc != nullptr);
805 for (const CXXCtorInitializer *Init : Ctor->inits()) {
806 Expr *InitExpr = Init->getInit();
807 if (FieldDecl *Field = Init->getMember();
808 Field != nullptr && Field->getType()->isRecordType()) {
809 PropagateResultObject(InitExpr, cast<RecordStorageLocation>(
810 ThisPointeeLoc->getChild(*Field)));
811 } else if (Init->getBaseClass()) {
812 PropagateResultObject(InitExpr, ThisPointeeLoc);
813 }
814
815 // Ensure that any result objects within `InitExpr` (e.g. temporaries)
816 // are also propagated to the prvalues that initialize them.
817 TraverseStmt(InitExpr);
818
819 // If this is a `CXXDefaultInitExpr`, also propagate any result objects
820 // within the default expression.
821 if (auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(InitExpr))
822 TraverseStmt(DefaultInit->getExpr());
823 }
824 }
825
826 bool VisitVarDecl(VarDecl *VD) override {
827 if (VD->getType()->isRecordType() && VD->hasInit())
828 PropagateResultObject(
829 VD->getInit(),
830 &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*VD)));
831 return true;
832 }
833
834 bool VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE) override {
835 if (MTE->getType()->isRecordType())
836 PropagateResultObject(
837 MTE->getSubExpr(),
838 &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*MTE)));
839 return true;
840 }
841
842 bool VisitReturnStmt(ReturnStmt *Return) override {
843 Expr *RetValue = Return->getRetValue();
844 if (RetValue != nullptr && RetValue->getType()->isRecordType() &&
845 RetValue->isPRValue())
846 PropagateResultObject(RetValue, LocForRecordReturnVal);
847 return true;
848 }
849
850 bool VisitExpr(Expr *E) override {
851 // Clang's AST can have record-type prvalues without a result object -- for
852 // example as full-expressions contained in a compound statement or as
853 // arguments of call expressions. We notice this if we get here and a
854 // storage location has not yet been associated with `E`. In this case,
855 // treat this as if it was a `MaterializeTemporaryExpr`.
856 if (E->isPRValue() && E->getType()->isRecordType() &&
857 !ResultObjectMap.contains(E))
858 PropagateResultObject(
859 E, &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*E)));
860 return true;
861 }
862
863 void
864 PropagateResultObjectToRecordInitList(const RecordInitListHelper &InitList,
865 RecordStorageLocation *Loc) {
866 for (auto [Base, Init] : InitList.base_inits()) {
867 assert(Base->getType().getCanonicalType() ==
868 Init->getType().getCanonicalType());
869
870 // Storage location for the base class is the same as that of the
871 // derived class because we "flatten" the object hierarchy and put all
872 // fields in `RecordStorageLocation` of the derived class.
873 PropagateResultObject(Init, Loc);
874 }
875
876 for (auto [Field, Init] : InitList.field_inits()) {
877 // Fields of non-record type are handled in
878 // `TransferVisitor::VisitInitListExpr()`.
879 if (Field->getType()->isRecordType())
880 PropagateResultObject(
881 Init, cast<RecordStorageLocation>(Loc->getChild(*Field)));
882 }
883 }
884
885 // Assigns `Loc` as the result object location of `E`, then propagates the
886 // location to all lower-level prvalues that initialize the same object as
887 // `E` (or one of its base classes or member variables).
888 void PropagateResultObject(Expr *E, RecordStorageLocation *Loc) {
889 if (!E->isPRValue() || !E->getType()->isRecordType()) {
890 assert(false);
891 // Ensure we don't propagate the result object if we hit this in a
892 // release build.
893 return;
894 }
895
896 ResultObjectMap[E] = Loc;
897
898 // The following AST node kinds are "original initializers": They are the
899 // lowest-level AST node that initializes a given object, and nothing
900 // below them can initialize the same object (or part of it).
904 // We treat `BuiltinBitCastExpr` as an "original initializer" too as
905 // it may not even be casting from a record type -- and even if it is,
906 // the two objects are in general of unrelated type.
908 // This covers both co_await and co_yield.
909 // The result object of co_await is <op>.await_resume(), but there is
910 // no expression for that to propagate to.
911 // co_yield is equivalent to `co_await promise.yield_value(expr)`.
913 return;
914 }
915 if (auto *Op = dyn_cast<BinaryOperator>(E);
916 Op && Op->getOpcode() == BO_Cmp) {
917 // Builtin `<=>` returns a `std::strong_ordering` object.
918 return;
919 }
920
921 if (auto *InitList = dyn_cast<InitListExpr>(E)) {
922 if (!InitList->isSemanticForm())
923 return;
924 if (InitList->isTransparent()) {
925 PropagateResultObject(InitList->getInit(0), Loc);
926 return;
927 }
928
929 PropagateResultObjectToRecordInitList(RecordInitListHelper(InitList),
930 Loc);
931 return;
932 }
933
934 if (auto *ParenInitList = dyn_cast<CXXParenListInitExpr>(E)) {
935 PropagateResultObjectToRecordInitList(RecordInitListHelper(ParenInitList),
936 Loc);
937 return;
938 }
939
940 if (auto *Op = dyn_cast<BinaryOperator>(E); Op && Op->isCommaOp()) {
941 PropagateResultObject(Op->getRHS(), Loc);
942 return;
943 }
944
945 if (auto *Cond = dyn_cast<AbstractConditionalOperator>(E)) {
946 PropagateResultObject(Cond->getTrueExpr(), Loc);
947 PropagateResultObject(Cond->getFalseExpr(), Loc);
948 return;
949 }
950
951 if (auto *SE = dyn_cast<StmtExpr>(E)) {
952 PropagateResultObject(cast<Expr>(SE->getSubStmt()->body_back()), Loc);
953 return;
954 }
955
956 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(E)) {
957 PropagateResultObject(DIE->getExpr(), Loc);
958 return;
959 }
960
961 // All other expression nodes that propagate a record prvalue should have
962 // exactly one child.
963 SmallVector<Stmt *, 1> Children(E->child_begin(), E->child_end());
964 LLVM_DEBUG({
965 if (Children.size() != 1)
966 E->dump();
967 });
968 assert(Children.size() == 1);
969 for (Stmt *S : Children)
970 PropagateResultObject(cast<Expr>(S), Loc);
971 }
972
973private:
974 llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap;
975 RecordStorageLocation *LocForRecordReturnVal;
976 DataflowAnalysisContext &DACtx;
977};
978
979/// A visitor that finds `CXXThisExpr` that can refer to an object other than
980/// the `this` of a member function.
981class ThisExprOverridesVisitor : public AnalysisASTVisitor {
982 using BaseVisitor = AnalysisASTVisitor;
983
984public:
985 ThisExprOverridesVisitor(
986 RecordStorageLocation *ThisPointeeLoc,
987 const llvm::DenseMap<const Expr *, RecordStorageLocation *>
988 &ResultObjectMap,
989 llvm::DenseMap<const CXXThisExpr *, RecordStorageLocation *>
990 &ThisExprOverrides)
991 : DefaultThisPointeeLoc(ThisPointeeLoc), ResultObjectMap(ResultObjectMap),
992 ThisExprOverrides(ThisExprOverrides) {
993 ThisLocations.push(DefaultThisPointeeLoc);
994 }
995
996 void traverseConstructorInits(const CXXConstructorDecl *Ctor) {
997 for (const CXXCtorInitializer *Init : Ctor->inits()) {
998 TraverseStmt(Init->getInit());
999 }
1000 }
1001
1002 bool TraverseInitListExpr(InitListExpr *ILE) override {
1003 if (!ILE->isSemanticForm() || ILE->isTransparent()) {
1004 BaseVisitor::TraverseInitListExpr(ILE);
1005 return true;
1006 }
1007 bool IsRecordType = ILE->getType()->isRecordType();
1008 if (IsRecordType) {
1009 auto It = ResultObjectMap.find(ILE);
1010 if (It == ResultObjectMap.end()) {
1011 llvm_unreachable("InitListExpr not found in ResultObjectMap");
1012 return false;
1013 }
1014 InitListLocations.push(It->second);
1015 }
1016 BaseVisitor::TraverseInitListExpr(ILE);
1017 if (IsRecordType)
1018 InitListLocations.pop();
1019 return true;
1020 }
1021
1022 bool TraverseCXXParenListInitExpr(CXXParenListInitExpr *PLIE) override {
1023 auto It = ResultObjectMap.find(PLIE);
1024 if (It == ResultObjectMap.end()) {
1025 llvm_unreachable("CXXParenListInitExpr not found in ResultObjectMap");
1026 return false;
1027 }
1028 InitListLocations.push(It->second);
1029 BaseVisitor::TraverseCXXParenListInitExpr(PLIE);
1030 InitListLocations.pop();
1031 return true;
1032 }
1033
1034 bool TraverseCXXDefaultInitExpr(CXXDefaultInitExpr *CDIE) override {
1035 bool HasInitListLocations = !InitListLocations.empty();
1036 if (HasInitListLocations) {
1037 auto *Loc = InitListLocations.top();
1038 ThisLocations.push(Loc);
1039 }
1040 BaseVisitor::TraverseCXXDefaultInitExpr(CDIE);
1041 if (HasInitListLocations)
1042 ThisLocations.pop();
1043 return true;
1044 }
1045
1046 bool TraverseCXXThisExpr(CXXThisExpr *This) override {
1047 assert(!ThisLocations.empty());
1048 auto *Loc = ThisLocations.top();
1049 if (Loc != DefaultThisPointeeLoc)
1050 ThisExprOverrides[This] = Loc;
1051 return true;
1052 }
1053
1054 // The default `this` pointee location (null if not in a member function).
1055 RecordStorageLocation *DefaultThisPointeeLoc;
1056 // Locations to use for `this`, with the most recent scope on top.
1057 std::stack<RecordStorageLocation *> ThisLocations;
1058 // A stack of nested InitListExpr and CXXParenListInitExprs storage
1059 // locations that may be used for `this` if we enter a CXXDefaultInitExpr.
1060 std::stack<RecordStorageLocation *> InitListLocations;
1061 // Map to look up a storage location, e.g., when encountering an
1062 // InitListExpr.
1063 const llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap;
1064 // The visitor will update this map with locations to use for `this`,
1065 // if different from `DefaultThisPointeeLoc`.
1066 llvm::DenseMap<const CXXThisExpr *, RecordStorageLocation *>
1067 &ThisExprOverrides;
1068};
1069
1070} // namespace
1071
1073 Atom FlowConditionToken)
1074 : DACtx(&DACtx),
1075 BoolState(std::make_unique<SatBoolModel>(DACtx, FlowConditionToken)) {
1076 assert(DACtx.getOptions().BoolModel == BoolModelKind::SAT &&
1077 "FlowConditionToken constructor requires BoolModelKind::SAT");
1078}
1079
1081 switch (DACtx.getOptions().BoolModel) {
1082 case BoolModelKind::SAT:
1083 BoolState = std::make_unique<SatBoolModel>(DACtx);
1084 break;
1085 case BoolModelKind::Simple:
1086 BoolState = std::make_unique<SimpleBoolModel>();
1087 break;
1088 }
1089}
1090
1092 : DACtx(Other.DACtx), CallStack(Other.CallStack),
1093 InitialTargetFunc(Other.InitialTargetFunc),
1094 InitialTargetStmt(Other.InitialTargetStmt),
1095 ResultObjectMap(Other.ResultObjectMap), ReturnVal(Other.ReturnVal),
1096 ReturnLoc(Other.ReturnLoc),
1097 LocForRecordReturnVal(Other.LocForRecordReturnVal),
1098 ThisPointeeLoc(Other.ThisPointeeLoc),
1099 ThisExprOverrides(Other.ThisExprOverrides), DeclToLoc(Other.DeclToLoc),
1100 ExprToLoc(Other.ExprToLoc), ExprToVal(Other.ExprToVal),
1101 LocToVal(Other.LocToVal), BoolState(Other.BoolState->clone()) {}
1102
1104 if (InitialTargetStmt == nullptr)
1105 return;
1106
1107 if (InitialTargetFunc == nullptr) {
1108 initFieldsGlobalsAndFuncs(getReferencedDecls(*InitialTargetStmt));
1109 ResultObjectMap =
1110 std::make_shared<PrValueToResultObject>(buildResultObjectMap(
1111 DACtx, InitialTargetStmt, getThisPointeeStorageLocation(),
1112 /*LocForRecordReturnValue=*/nullptr));
1113
1114 ThisExprOverrides =
1115 std::make_shared<ThisExprOverridesMap>(buildThisExprOverridesMap(
1116 InitialTargetStmt, getThisPointeeStorageLocation(),
1117 *ResultObjectMap));
1118 return;
1119 }
1120
1121 initFieldsGlobalsAndFuncs(getReferencedDecls(*InitialTargetFunc));
1122
1123 for (const auto *ParamDecl : InitialTargetFunc->parameters()) {
1124 assert(ParamDecl != nullptr);
1125 setStorageLocation(*ParamDecl, createObject(*ParamDecl, nullptr));
1126 }
1127
1128 if (InitialTargetFunc->getReturnType()->isRecordType())
1129 LocForRecordReturnVal = &cast<RecordStorageLocation>(
1130 createStorageLocation(InitialTargetFunc->getReturnType()));
1131
1132 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(InitialTargetFunc)) {
1133 auto *Parent = MethodDecl->getParent();
1134 assert(Parent != nullptr);
1135
1136 if (Parent->isLambda()) {
1137 for (const auto &Capture : Parent->captures()) {
1138 if (Capture.capturesVariable()) {
1139 const auto *VarDecl = Capture.getCapturedVar();
1140 assert(VarDecl != nullptr);
1142 } else if (Capture.capturesThis()) {
1143 if (auto *Ancestor = InitialTargetFunc->getNonClosureAncestor()) {
1144 const auto *SurroundingMethodDecl = cast<CXXMethodDecl>(Ancestor);
1145 QualType ThisPointeeType =
1146 SurroundingMethodDecl->getFunctionObjectParameterType();
1148 cast<RecordStorageLocation>(createObject(ThisPointeeType)));
1149 } else if (auto *FieldBeingInitialized =
1150 dyn_cast<FieldDecl>(Parent->getLambdaContextDecl())) {
1151 // This is in a field initializer, rather than a method.
1152 const RecordDecl *RD = FieldBeingInitialized->getParent();
1153 const ASTContext &Ctx = RD->getASTContext();
1157 } else {
1158 assert(false && "Unexpected this-capturing lambda context.");
1159 }
1160 }
1161 }
1162 } else if (MethodDecl->isImplicitObjectMemberFunction()) {
1163 QualType ThisPointeeType = MethodDecl->getFunctionObjectParameterType();
1164 auto &ThisLoc =
1167 // Initialize fields of `*this` with values, but only if we're not
1168 // analyzing a constructor; after all, it's the constructor's job to do
1169 // this (and we want to be able to test that).
1170 if (!isa<CXXConstructorDecl>(MethodDecl))
1172 }
1173 }
1174
1175 // We do this below the handling of `CXXMethodDecl` above so that we can
1176 // be sure that the storage location for `this` has been set.
1177 ResultObjectMap =
1178 std::make_shared<PrValueToResultObject>(buildResultObjectMap(
1179 DACtx, InitialTargetFunc, getThisPointeeStorageLocation(),
1180 LocForRecordReturnVal));
1181
1182 ThisExprOverrides =
1183 std::make_shared<ThisExprOverridesMap>(buildThisExprOverridesMap(
1184 InitialTargetFunc, getThisPointeeStorageLocation(),
1185 *ResultObjectMap));
1186}
1187
1188// FIXME: Add support for resetting globals after function calls to enable the
1189// implementation of sound analyses.
1190
1191void Environment::initFieldsGlobalsAndFuncs(const ReferencedDecls &Referenced) {
1192 // These have to be added before the lines that follow to ensure that
1193 // `create*` work correctly for structs.
1194 DACtx->addModeledFields(Referenced.Fields);
1195
1196 for (const VarDecl *D : Referenced.Globals) {
1197 if (getStorageLocation(*D) != nullptr)
1198 continue;
1199
1200 // We don't run transfer functions on the initializers of global variables,
1201 // so they won't be associated with a value or storage location. We
1202 // therefore intentionally don't pass an initializer to `createObject()`; in
1203 // particular, this ensures that `createObject()` will initialize the fields
1204 // of record-type variables with values.
1205 setStorageLocation(*D, createObject(*D, nullptr));
1206 }
1207
1208 for (const FunctionDecl *FD : Referenced.Functions) {
1209 if (getStorageLocation(*FD) != nullptr)
1210 continue;
1211 auto &Loc = createStorageLocation(*FD);
1212 setStorageLocation(*FD, Loc);
1213 }
1214}
1215
1217 Environment Copy(*this);
1218 Copy.BoolState->onFork();
1219 return Copy;
1220}
1221
1222bool Environment::canDescend(unsigned MaxDepth,
1223 const FunctionDecl *Callee) const {
1224 return CallStack.size() < MaxDepth && !llvm::is_contained(CallStack, Callee);
1225}
1226
1228 Environment Env(*this);
1229
1230 if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
1231 if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
1232 if (!isa<CXXThisExpr>(Arg))
1233 Env.ThisPointeeLoc =
1235 // Otherwise (when the argument is `this`), retain the current
1236 // environment's `ThisPointeeLoc`.
1237 }
1238 }
1239
1240 if (Call->getType()->isRecordType() && Call->isPRValue())
1241 Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call);
1242
1243 Env.pushCallInternal(Call->getDirectCallee(),
1244 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
1245
1246 return Env;
1247}
1248
1250 Environment Env(*this);
1251
1252 Env.ThisPointeeLoc = &Env.getResultObjectLocation(*Call);
1253 Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call);
1254
1255 Env.pushCallInternal(Call->getConstructor(),
1256 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
1257
1258 return Env;
1259}
1260
1261void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
1263 // Canonicalize to the definition of the function. This ensures that we're
1264 // putting arguments into the same `ParamVarDecl`s` that the callee will later
1265 // be retrieving them from.
1266 assert(FuncDecl->getDefinition() != nullptr);
1267 FuncDecl = FuncDecl->getDefinition();
1268
1269 CallStack.push_back(FuncDecl);
1270
1271 initFieldsGlobalsAndFuncs(getReferencedDecls(*FuncDecl));
1272
1273 const auto *ParamIt = FuncDecl->param_begin();
1274
1275 // FIXME: Parameters don't always map to arguments 1:1; examples include
1276 // overloaded operators implemented as member functions, and parameter packs.
1277 for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
1278 assert(ParamIt != FuncDecl->param_end());
1279 const VarDecl *Param = *ParamIt;
1280 setStorageLocation(*Param, createObject(*Param, Args[ArgIndex]));
1281 }
1282
1283 ResultObjectMap = std::make_shared<PrValueToResultObject>(
1284 buildResultObjectMap(DACtx, FuncDecl, getThisPointeeStorageLocation(),
1285 LocForRecordReturnVal));
1286 ThisExprOverrides =
1287 std::make_shared<ThisExprOverridesMap>(buildThisExprOverridesMap(
1288 FuncDecl, getThisPointeeStorageLocation(), *ResultObjectMap));
1289}
1290
1291void Environment::popCall(const CallExpr *Call, const Environment &CalleeEnv) {
1292 // We ignore some entries of `CalleeEnv`:
1293 // - `DACtx` because is already the same in both
1294 // - We don't want the callee's `DeclCtx`, `ReturnVal`, `ReturnLoc` or
1295 // `ThisPointeeLoc` because they don't apply to us.
1296 // - `DeclToLoc`, `ExprToLoc`, and `ExprToVal` capture information from the
1297 // callee's local scope, so when popping that scope, we do not propagate
1298 // the maps.
1299 this->LocToVal = std::move(CalleeEnv.LocToVal);
1300 this->BoolState = CalleeEnv.BoolState->clone();
1301
1302 if (Call->isGLValue()) {
1303 if (CalleeEnv.ReturnLoc != nullptr)
1304 setStorageLocation(*Call, *CalleeEnv.ReturnLoc);
1305 } else if (!Call->getType()->isVoidType()) {
1306 if (CalleeEnv.ReturnVal != nullptr)
1307 setValue(*Call, *CalleeEnv.ReturnVal);
1308 }
1309}
1310
1312 const Environment &CalleeEnv) {
1313 // See also comment in `popCall(const CallExpr *, const Environment &)` above.
1314 this->LocToVal = std::move(CalleeEnv.LocToVal);
1315 this->BoolState = CalleeEnv.BoolState->clone();
1316}
1317
1319 Environment::ValueModel &Model) const {
1320 assert(DACtx == Other.DACtx);
1321
1322 if (ReturnVal != Other.ReturnVal)
1323 return false;
1324
1325 if (ReturnLoc != Other.ReturnLoc)
1326 return false;
1327
1328 if (LocForRecordReturnVal != Other.LocForRecordReturnVal)
1329 return false;
1330
1331 if (ThisPointeeLoc != Other.ThisPointeeLoc)
1332 return false;
1333
1334 if (DeclToLoc != Other.DeclToLoc)
1335 return false;
1336
1337 if (ExprToLoc != Other.ExprToLoc)
1338 return false;
1339
1340 if (!compareKeyToValueMaps(ExprToVal, Other.ExprToVal, *this, Other, Model))
1341 return false;
1342
1343 if (!compareKeyToValueMaps(LocToVal, Other.LocToVal, *this, Other, Model))
1344 return false;
1345 if (!BoolState->isEquivalentTo(*Other.BoolState))
1346 return false;
1347
1348 return true;
1349}
1350
1352 Environment::ValueModel &Model) {
1353 assert(DACtx == PrevEnv.DACtx);
1354 assert(ReturnVal == PrevEnv.ReturnVal);
1355 assert(ReturnLoc == PrevEnv.ReturnLoc);
1356 assert(LocForRecordReturnVal == PrevEnv.LocForRecordReturnVal);
1357 assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc);
1358 assert(ThisExprOverrides == PrevEnv.ThisExprOverrides);
1359 assert(CallStack == PrevEnv.CallStack);
1360 assert(ResultObjectMap == PrevEnv.ResultObjectMap);
1361 assert(InitialTargetFunc == PrevEnv.InitialTargetFunc);
1362 assert(InitialTargetStmt == PrevEnv.InitialTargetStmt);
1363
1364 auto Effect = LatticeEffect::Unchanged;
1365
1366 // By the API, `PrevEnv` is a previous version of the environment for the same
1367 // block, so we have some guarantees about its shape. In particular, it will
1368 // be the result of a join or widen operation on previous values for this
1369 // block. For `DeclToLoc`, `ExprToVal`, and `ExprToLoc`, join guarantees that
1370 // these maps are subsets of the maps in `PrevEnv`. So, as long as we maintain
1371 // this property here, we don't need change their current values to widen.
1372 assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
1373 assert(ExprToVal.size() <= PrevEnv.ExprToVal.size());
1374 assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
1375
1376 ExprToVal = widenKeyToValueMap(ExprToVal, PrevEnv.ExprToVal, *this, PrevEnv,
1377 Model, Effect);
1378
1379 LocToVal = widenKeyToValueMap(LocToVal, PrevEnv.LocToVal, *this, PrevEnv,
1380 Model, Effect);
1381 if (BoolState->widen(*PrevEnv.BoolState) == LatticeEffect::Changed)
1382 Effect = LatticeEffect::Changed;
1383 if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
1384 ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
1385 ExprToVal.size() != PrevEnv.ExprToVal.size() ||
1386 LocToVal.size() != PrevEnv.LocToVal.size())
1387 Effect = LatticeEffect::Changed;
1388
1389 return Effect;
1390}
1391
1394 ExprJoinBehavior ExprBehavior) {
1395 assert(EnvA.DACtx == EnvB.DACtx);
1396 assert(EnvA.LocForRecordReturnVal == EnvB.LocForRecordReturnVal);
1397 assert(EnvA.ThisPointeeLoc == EnvB.ThisPointeeLoc);
1398 assert(EnvA.ThisExprOverrides == EnvB.ThisExprOverrides);
1399 assert(EnvA.CallStack == EnvB.CallStack);
1400 assert(EnvA.ResultObjectMap == EnvB.ResultObjectMap);
1401 assert(EnvA.InitialTargetFunc == EnvB.InitialTargetFunc);
1402 assert(EnvA.InitialTargetStmt == EnvB.InitialTargetStmt);
1403
1404 Environment JoinedEnv(*EnvA.DACtx);
1405
1406 JoinedEnv.CallStack = EnvA.CallStack;
1407 JoinedEnv.ResultObjectMap = EnvA.ResultObjectMap;
1408 JoinedEnv.LocForRecordReturnVal = EnvA.LocForRecordReturnVal;
1409 JoinedEnv.ThisPointeeLoc = EnvA.ThisPointeeLoc;
1410 JoinedEnv.ThisExprOverrides = EnvA.ThisExprOverrides;
1411 JoinedEnv.InitialTargetFunc = EnvA.InitialTargetFunc;
1412 JoinedEnv.InitialTargetStmt = EnvA.InitialTargetStmt;
1413
1414 const FunctionDecl *Func = EnvA.getCurrentFunc();
1415 if (!Func) {
1416 JoinedEnv.ReturnVal = nullptr;
1417 } else {
1418 JoinedEnv.ReturnVal =
1419 joinValues(Func->getReturnType(), EnvA.ReturnVal, EnvA, EnvB.ReturnVal,
1420 EnvB, JoinedEnv, Model);
1421 }
1422
1423 if (EnvA.ReturnLoc == EnvB.ReturnLoc)
1424 JoinedEnv.ReturnLoc = EnvA.ReturnLoc;
1425 else
1426 JoinedEnv.ReturnLoc = nullptr;
1427
1428 JoinedEnv.DeclToLoc = intersectDeclToLoc(EnvA.DeclToLoc, EnvB.DeclToLoc);
1429
1430 JoinedEnv.BoolState->join(*EnvA.BoolState, *EnvB.BoolState);
1431
1432 JoinedEnv.LocToVal =
1433 joinLocToVal(EnvA.LocToVal, EnvB.LocToVal, EnvA, EnvB, JoinedEnv, Model);
1434
1435 if (ExprBehavior == KeepExprState) {
1436 JoinedEnv.ExprToVal = joinExprMaps(EnvA.ExprToVal, EnvB.ExprToVal);
1437 JoinedEnv.ExprToLoc = joinExprMaps(EnvA.ExprToLoc, EnvB.ExprToLoc);
1438 }
1439
1440 return JoinedEnv;
1441}
1442
1444 const Environment &Env1, Value *Val2,
1445 const Environment &Env2, Environment &JoinedEnv,
1446 Environment::ValueModel &Model) {
1447 if (Val1 == nullptr || Val2 == nullptr)
1448 // We can't say anything about the joined value -- even if one of the values
1449 // is non-null, we don't want to simply propagate it, because it would be
1450 // too specific: Because the other value is null, that means we have no
1451 // information at all about the value (i.e. the value is unconstrained).
1452 return nullptr;
1453
1454 if (areEquivalentValues(*Val1, *Val2))
1455 // Arbitrarily return one of the two values.
1456 return Val1;
1457
1458 return joinDistinctValues(Ty, *Val1, Env1, *Val2, Env2, JoinedEnv, Model);
1459}
1460
1462 return DACtx->createStorageLocation(Type);
1463}
1464
1466 // Evaluated declarations are always assigned the same storage locations to
1467 // ensure that the environment stabilizes across loop iterations. Storage
1468 // locations for evaluated declarations are stored in the analysis context.
1469 return DACtx->getStableStorageLocation(D);
1470}
1471
1473 // Evaluated expressions are always assigned the same storage locations to
1474 // ensure that the environment stabilizes across loop iterations. Storage
1475 // locations for evaluated expressions are stored in the analysis context.
1476 return DACtx->getStableStorageLocation(E);
1477}
1478
1480 assert(!DeclToLoc.contains(&D));
1481 // The only kinds of declarations that may have a "variable" storage location
1482 // are declarations of reference type and `BindingDecl`. For all other
1483 // declaration, the storage location should be the stable storage location
1484 // returned by `createStorageLocation()`.
1485 assert(D.getType()->isReferenceType() || isa<BindingDecl>(D) ||
1486 &Loc == &createStorageLocation(D));
1487 DeclToLoc[&D] = &Loc;
1488}
1489
1491 auto It = DeclToLoc.find(&D);
1492 if (It == DeclToLoc.end())
1493 return nullptr;
1494
1495 StorageLocation *Loc = It->second;
1496
1497 return Loc;
1498}
1499
1500void Environment::removeDecl(const ValueDecl &D) { DeclToLoc.erase(&D); }
1501
1503 // `DeclRefExpr`s to builtin function types aren't glvalues, for some reason,
1504 // but we still want to be able to associate a `StorageLocation` with them,
1505 // so allow these as an exception.
1506 assert(E.isGLValue() ||
1507 E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
1508 const Expr &CanonE = ignoreCFGOmittedNodes(E);
1509 assert(!ExprToLoc.contains(&CanonE));
1510 ExprToLoc[&CanonE] = &Loc;
1511}
1512
1514 // See comment in `setStorageLocation()`.
1515 assert(E.isGLValue() ||
1516 E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
1517 auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
1518 return It == ExprToLoc.end() ? nullptr : &*It->second;
1519}
1520
1522Environment::getResultObjectLocation(const Expr &RecordPRValue) const {
1523 assert(RecordPRValue.getType()->isRecordType());
1524 assert(RecordPRValue.isPRValue());
1525
1526 assert(ResultObjectMap != nullptr);
1527 RecordStorageLocation *Loc = ResultObjectMap->lookup(&RecordPRValue);
1528 assert(Loc != nullptr);
1529 // In release builds, use the "stable" storage location if the map lookup
1530 // failed.
1531 if (Loc == nullptr)
1533 DACtx->getStableStorageLocation(RecordPRValue));
1534 return *Loc;
1535}
1536
1538 return DACtx->getOrCreateNullPointerValue(PointeeType);
1539}
1540
1542 QualType Type) {
1543 llvm::DenseSet<QualType> Visited;
1544 int CreatedValuesCount = 0;
1545 initializeFieldsWithValues(Loc, Type, Visited, 0, CreatedValuesCount);
1546 if (CreatedValuesCount > MaxCompositeValueSize) {
1547 llvm::errs() << "Attempting to initialize a huge value of type: " << Type
1548 << '\n';
1549 }
1550}
1551
1553 // Records should not be associated with values.
1554 assert(!isa<RecordStorageLocation>(Loc));
1555 LocToVal[&Loc] = &Val;
1556}
1557
1558void Environment::setValue(const Expr &E, Value &Val) {
1559 const Expr &CanonE = ignoreCFGOmittedNodes(E);
1560
1561 assert(CanonE.isPRValue());
1562 // Records should not be associated with values.
1563 assert(!CanonE.getType()->isRecordType());
1564 ExprToVal[&CanonE] = &Val;
1565}
1566
1568 // Records should not be associated with values.
1569 assert(!isa<RecordStorageLocation>(Loc));
1570 return LocToVal.lookup(&Loc);
1571}
1572
1574 auto *Loc = getStorageLocation(D);
1575 if (Loc == nullptr)
1576 return nullptr;
1577 return getValue(*Loc);
1578}
1579
1581 // Records should not be associated with values.
1582 assert(!E.getType()->isRecordType());
1583
1584 if (E.isPRValue()) {
1585 auto It = ExprToVal.find(&ignoreCFGOmittedNodes(E));
1586 return It == ExprToVal.end() ? nullptr : It->second;
1587 }
1588
1589 auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
1590 if (It == ExprToLoc.end())
1591 return nullptr;
1592 return getValue(*It->second);
1593}
1594
1596 llvm::DenseSet<QualType> Visited;
1597 int CreatedValuesCount = 0;
1598 Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
1599 CreatedValuesCount);
1600 if (CreatedValuesCount > MaxCompositeValueSize) {
1601 llvm::errs() << "Attempting to initialize a huge value of type: " << Type
1602 << '\n';
1603 }
1604 return Val;
1605}
1606
1607Value *Environment::createValueUnlessSelfReferential(
1608 QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
1609 int &CreatedValuesCount) {
1610 assert(!Type.isNull());
1611 assert(!Type->isReferenceType());
1612 assert(!Type->isRecordType());
1613
1614 // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
1615 if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
1616 Depth > MaxCompositeValueDepth)
1617 return nullptr;
1618
1619 if (Type->isBooleanType()) {
1620 CreatedValuesCount++;
1621 return &makeAtomicBoolValue();
1622 }
1623
1624 if (Type->isIntegerType()) {
1625 // FIXME: consider instead `return nullptr`, given that we do nothing useful
1626 // with integers, and so distinguishing them serves no purpose, but could
1627 // prevent convergence.
1628 CreatedValuesCount++;
1629 return &arena().create<IntegerValue>();
1630 }
1631
1632 if (Type->isPointerType()) {
1633 CreatedValuesCount++;
1634 QualType PointeeType = Type->getPointeeType();
1635 StorageLocation &PointeeLoc =
1636 createLocAndMaybeValue(PointeeType, Visited, Depth, CreatedValuesCount);
1637
1638 return &arena().create<PointerValue>(PointeeLoc);
1639 }
1640
1641 return nullptr;
1642}
1643
1645Environment::createLocAndMaybeValue(QualType Ty,
1646 llvm::DenseSet<QualType> &Visited,
1647 int Depth, int &CreatedValuesCount) {
1648 if (!Visited.insert(Ty.getCanonicalType()).second)
1649 return createStorageLocation(Ty.getNonReferenceType());
1650 llvm::scope_exit EraseVisited(
1651 [&Visited, Ty] { Visited.erase(Ty.getCanonicalType()); });
1652
1653 Ty = Ty.getNonReferenceType();
1654
1655 if (Ty->isRecordType()) {
1657 initializeFieldsWithValues(Loc, Ty, Visited, Depth, CreatedValuesCount);
1658 return Loc;
1659 }
1660
1661 StorageLocation &Loc = createStorageLocation(Ty);
1662
1663 if (Value *Val = createValueUnlessSelfReferential(Ty, Visited, Depth,
1664 CreatedValuesCount))
1665 setValue(Loc, *Val);
1666
1667 return Loc;
1668}
1669
1671 QualType Type,
1672 llvm::DenseSet<QualType> &Visited,
1673 int Depth,
1674 int &CreatedValuesCount) {
1675 auto initField = [&](QualType FieldType, StorageLocation &FieldLoc) {
1676 if (FieldType->isRecordType()) {
1677 auto &FieldRecordLoc = cast<RecordStorageLocation>(FieldLoc);
1678 initializeFieldsWithValues(FieldRecordLoc, FieldRecordLoc.getType(),
1679 Visited, Depth + 1, CreatedValuesCount);
1680 } else {
1681 if (getValue(FieldLoc) != nullptr)
1682 return;
1683 if (!Visited.insert(FieldType.getCanonicalType()).second)
1684 return;
1685 if (Value *Val = createValueUnlessSelfReferential(
1686 FieldType, Visited, Depth + 1, CreatedValuesCount))
1687 setValue(FieldLoc, *Val);
1688 Visited.erase(FieldType.getCanonicalType());
1689 }
1690 };
1691
1692 for (const FieldDecl *Field : DACtx->getModeledFields(Type)) {
1693 assert(Field != nullptr);
1694 QualType FieldType = Field->getType();
1695
1696 if (FieldType->isReferenceType()) {
1697 Loc.setChild(*Field,
1698 &createLocAndMaybeValue(FieldType, Visited, Depth + 1,
1699 CreatedValuesCount));
1700 } else {
1701 StorageLocation *FieldLoc = Loc.getChild(*Field);
1702 assert(FieldLoc != nullptr);
1703 initField(FieldType, *FieldLoc);
1704 }
1705 }
1706 for (const auto &[FieldName, FieldType] : DACtx->getSyntheticFields(Type)) {
1707 // Synthetic fields cannot have reference type, so we don't need to deal
1708 // with this case.
1709 assert(!FieldType->isReferenceType());
1710 initField(FieldType, Loc.getSyntheticField(FieldName));
1711 }
1712}
1713
1714StorageLocation &Environment::createObjectInternal(const ValueDecl *D,
1715 QualType Ty,
1716 const Expr *InitExpr) {
1717 if (Ty->isReferenceType()) {
1718 // Although variables of reference type always need to be initialized, it
1719 // can happen that we can't see the initializer, so `InitExpr` may still
1720 // be null.
1721 if (InitExpr) {
1722 if (auto *InitExprLoc = getStorageLocation(*InitExpr))
1723 return *InitExprLoc;
1724 }
1725
1726 // Even though we have an initializer, we might not get an
1727 // InitExprLoc, for example if the InitExpr is a CallExpr for which we
1728 // don't have a function body. In this case, we just invent a storage
1729 // location and value -- it's the best we can do.
1730 return createObjectInternal(D, Ty.getNonReferenceType(), nullptr);
1731 }
1732
1733 StorageLocation &Loc =
1735
1736 if (Ty->isRecordType()) {
1737 auto &RecordLoc = cast<RecordStorageLocation>(Loc);
1738 if (!InitExpr)
1739 initializeFieldsWithValues(RecordLoc);
1740 } else {
1741 Value *Val = nullptr;
1742 if (InitExpr)
1743 // In the (few) cases where an expression is intentionally
1744 // "uninterpreted", `InitExpr` is not associated with a value. There are
1745 // two ways to handle this situation: propagate the status, so that
1746 // uninterpreted initializers result in uninterpreted variables, or
1747 // provide a default value. We choose the latter so that later refinements
1748 // of the variable can be used for reasoning about the surrounding code.
1749 // For this reason, we let this case be handled by the `createValue()`
1750 // call below.
1751 //
1752 // FIXME. If and when we interpret all language cases, change this to
1753 // assert that `InitExpr` is interpreted, rather than supplying a
1754 // default value (assuming we don't update the environment API to return
1755 // references).
1756 Val = getValue(*InitExpr);
1757 if (!Val)
1758 Val = createValue(Ty);
1759 if (Val)
1760 setValue(Loc, *Val);
1761 }
1762
1763 return Loc;
1764}
1765
1766void Environment::assume(const Formula &F) { BoolState->assume(F); }
1767
1768bool Environment::proves(const Formula &F) const {
1769 return BoolState->proves(F);
1770}
1771
1772bool Environment::allows(const Formula &F) const {
1773 return BoolState->allows(F);
1774}
1775
1776void Environment::dump(raw_ostream &OS) const {
1777 llvm::DenseMap<const StorageLocation *, std::string> LocToName;
1778 if (LocForRecordReturnVal != nullptr)
1779 LocToName[LocForRecordReturnVal] = "(returned record)";
1780 if (ThisPointeeLoc != nullptr)
1781 LocToName[ThisPointeeLoc] = "this";
1782
1783 OS << "DeclToLoc:\n";
1784 for (auto [D, L] : DeclToLoc) {
1785 auto Iter = LocToName.insert({L, D->getNameAsString()}).first;
1786 OS << " [" << Iter->second << ", " << L << "]\n";
1787 }
1788 OS << "ExprToLoc:\n";
1789 for (auto [E, L] : ExprToLoc)
1790 OS << " [" << E << ", " << L << "]\n";
1791
1792 OS << "ExprToVal:\n";
1793 for (auto [E, V] : ExprToVal)
1794 OS << " [" << E << ", " << V << ": " << *V << "]\n";
1795
1796 OS << "LocToVal:\n";
1797 for (auto [L, V] : LocToVal) {
1798 OS << " [" << L;
1799 if (auto Iter = LocToName.find(L); Iter != LocToName.end())
1800 OS << " (" << Iter->second << ")";
1801 OS << ", " << V << ": " << *V << "]\n";
1802 }
1803
1804 if (const FunctionDecl *Func = getCurrentFunc()) {
1805 if (Func->getReturnType()->isReferenceType()) {
1806 OS << "ReturnLoc: " << ReturnLoc;
1807 if (auto Iter = LocToName.find(ReturnLoc); Iter != LocToName.end())
1808 OS << " (" << Iter->second << ")";
1809 OS << "\n";
1810 } else if (Func->getReturnType()->isRecordType() ||
1812 OS << "LocForRecordReturnVal: " << LocForRecordReturnVal << "\n";
1813 } else if (!Func->getReturnType()->isVoidType()) {
1814 if (ReturnVal == nullptr)
1815 OS << "ReturnVal: nullptr\n";
1816 else
1817 OS << "ReturnVal: " << *ReturnVal << "\n";
1818 }
1819
1820 if (isa<CXXMethodDecl>(Func)) {
1821 OS << "ThisPointeeLoc: " << ThisPointeeLoc << "\n";
1822 }
1823 }
1824
1825 OS << "\n";
1826 BoolState->dump(OS);
1827}
1828
1829void Environment::dump() const { dump(llvm::dbgs()); }
1830
1831Environment::PrValueToResultObject Environment::buildResultObjectMap(
1832 DataflowAnalysisContext *DACtx, const FunctionDecl *FuncDecl,
1833 RecordStorageLocation *ThisPointeeLoc,
1834 RecordStorageLocation *LocForRecordReturnVal) {
1835 assert(FuncDecl->doesThisDeclarationHaveABody());
1836
1837 PrValueToResultObject Map = buildResultObjectMap(
1838 DACtx, FuncDecl->getBody(), ThisPointeeLoc, LocForRecordReturnVal);
1839
1840 ResultObjectVisitor Visitor(Map, LocForRecordReturnVal, *DACtx);
1841 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FuncDecl))
1842 Visitor.traverseConstructorInits(Ctor, ThisPointeeLoc);
1843
1844 return Map;
1845}
1846
1847Environment::PrValueToResultObject Environment::buildResultObjectMap(
1848 DataflowAnalysisContext *DACtx, Stmt *S,
1849 RecordStorageLocation *ThisPointeeLoc,
1850 RecordStorageLocation *LocForRecordReturnVal) {
1851 PrValueToResultObject Map;
1852 ResultObjectVisitor Visitor(Map, LocForRecordReturnVal, *DACtx);
1853 Visitor.TraverseStmt(S);
1854 return Map;
1855}
1856
1857Environment::ThisExprOverridesMap Environment::buildThisExprOverridesMap(
1858 const FunctionDecl *FuncDecl, RecordStorageLocation *ThisPointeeLoc,
1859 const PrValueToResultObject &ResultObjectMap) {
1860 assert(FuncDecl->doesThisDeclarationHaveABody());
1861
1862 ThisExprOverridesMap Map = buildThisExprOverridesMap(
1863 FuncDecl->getBody(), ThisPointeeLoc, ResultObjectMap);
1864
1865 ThisExprOverridesVisitor Visitor(ThisPointeeLoc, ResultObjectMap, Map);
1866 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FuncDecl)) {
1867 Visitor.traverseConstructorInits(Ctor);
1868 }
1869 return Map;
1870}
1871
1872Environment::ThisExprOverridesMap Environment::buildThisExprOverridesMap(
1873 Stmt *S, RecordStorageLocation *ThisPointeeLoc,
1874 const PrValueToResultObject &ResultObjectMap) {
1875 ThisExprOverridesMap Map;
1876 ThisExprOverridesVisitor Visitor(ThisPointeeLoc, ResultObjectMap, Map);
1877 Visitor.TraverseStmt(S);
1878 return Map;
1879}
1880
1882 const Environment &Env) {
1883 Expr *ImplicitObject = MCE.getImplicitObjectArgument();
1884 if (ImplicitObject == nullptr)
1885 return nullptr;
1886 if (ImplicitObject->getType()->isPointerType()) {
1887 if (auto *Val = Env.get<PointerValue>(*ImplicitObject))
1888 return &cast<RecordStorageLocation>(Val->getPointeeLoc());
1889 return nullptr;
1890 }
1891 return cast_or_null<RecordStorageLocation>(
1892 Env.getStorageLocation(*ImplicitObject));
1893}
1894
1896 const Environment &Env) {
1897 Expr *Base = ME.getBase();
1898 if (Base == nullptr)
1899 return nullptr;
1900 if (ME.isArrow()) {
1901 if (auto *Val = Env.get<PointerValue>(*Base))
1902 return &cast<RecordStorageLocation>(Val->getPointeeLoc());
1903 return nullptr;
1904 }
1905 return Env.get<RecordStorageLocation>(*Base);
1906}
1907
1908} // namespace dataflow
1909} // namespace clang
#define V(N, I)
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static void initField(std::byte *Ptr, bool IsConst, bool IsMutable, bool IsVolatile, bool IsActive, bool IsUnionField, bool InUnion, const Descriptor *D, unsigned FieldOffset)
Defines the clang::Expr interface and subclasses for C++ expressions.
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
static PRESERVE_NONE bool RetValue(InterpState &S)
Definition Interp.cpp:64
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
C Language Family Type Representation.
Represents a member of a struct/union/class.
Definition Decl.h:3341
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
CanQualType getCanonicalTagType(const TagDecl *TD) const
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:754
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
This represents one expression.
Definition Expr.h:114
bool isGLValue() const
Definition Expr.h:289
bool isPRValue() const
Definition Expr.h:287
QualType getType() const
Definition Expr.h:146
Represents a function declaration or definition.
Definition Decl.h:2082
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3284
param_iterator param_end()
Definition Decl.h:2960
param_iterator param_begin()
Definition Decl.h:2959
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2482
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2438
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
Expr * getBase() const
Definition Expr.h:3510
bool isArrow() const
Definition Expr.h:3617
A (possibly-)qualified type.
Definition TypeBase.h:938
Represents a struct/union/class.
Definition Decl.h:4506
Stmt - This represents one statement.
Definition Stmt.h:85
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBooleanType() const
Definition TypeBase.h:9341
bool isPointerType() const
Definition TypeBase.h:8815
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
bool isReferenceType() const
Definition TypeBase.h:8839
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9169
bool isRecordType() const
Definition TypeBase.h:8942
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
Specialization of RecursiveASTVisitor that visits those nodes that are relevant to the dataflow analy...
Definition ASTOps.h:91
const Formula & makeNot(const Formula &Val)
Returns a formula for the negation of Val.
Definition Arena.cpp:67
std::enable_if_t< std::is_base_of< StorageLocation, T >::value, T & > create(Args &&...args)
Creates a T (some subclass of StorageLocation), forwarding args to the constructor,...
Definition Arena.h:36
Owns objects that encompass the state of a program and stores context that is used during dataflow an...
Supplements Environment with non-standard comparison and join operations.
Holds the state of the program (store and heap) at a given program point.
bool allows(const Formula &) const
Returns true if the formula may be true when this point is reached.
LatticeEffect widen(const Environment &PrevEnv, Environment::ValueModel &Model)
Widens the environment point-wise, using PrevEnv as needed to inform the approximation.
PointerValue & getOrCreateNullPointerValue(QualType PointeeType)
Returns a pointer value that represents a null pointer.
RecordStorageLocation * getThisPointeeStorageLocation() const
Returns the storage location assigned to the this pointee in the environment or null if the this poin...
Environment pushCall(const CallExpr *Call) const
Creates and returns an environment to use for an inline analysis of the callee.
StorageLocation * getStorageLocation(const ValueDecl &D) const
Returns the storage location assigned to D in the environment, or null if D isn't assigned a storage ...
LLVM_DUMP_METHOD void dump() const
BoolValue & makeTopBoolValue() const
Returns a unique instance of boolean Top.
void initializeFieldsWithValues(RecordStorageLocation &Loc, QualType Type)
Initializes the fields (including synthetic fields) of Loc with values, unless values of the field ty...
StorageLocation & createStorageLocation(QualType Type)
Creates a storage location appropriate for Type.
Environment fork() const
Returns a new environment that is a copy of this one.
void popCall(const CallExpr *Call, const Environment &CalleeEnv)
Moves gathered information back into this from a CalleeEnv created via pushCall.
bool equivalentTo(const Environment &Other, Environment::ValueModel &Model) const
Returns true if and only if the environment is equivalent to Other, i.e the two environments:
BoolValue & makeAtomicBoolValue() const
Returns an atomic boolean value.
bool proves(const Formula &) const
Returns true if the formula is always true when this point is reached.
Value * getValue(const StorageLocation &Loc) const
Returns the value assigned to Loc in the environment or null if Loc isn't assigned a value in the env...
const FunctionDecl * getCurrentFunc() const
Returns the function currently being analyzed, or null if the code being analyzed isn't part of a fun...
BoolValue & getBoolLiteralValue(bool Value) const
Returns a symbolic boolean value that models a boolean literal equal to Value
StorageLocation & createObject(QualType Ty, const Expr *InitExpr=nullptr)
Creates an object (i.e.
void assume(const Formula &)
Record a fact that must be true if this point in the program is reached.
BoolValue & joinBoolValues(BoolValue &Val1, const Environment &Env1, BoolValue &Val2, const Environment &Env2)
Joins two distinct boolean values Val1 (from Env1) and Val2 (from Env2) into this environment.
Environment(DataflowAnalysisContext &DACtx, Atom FlowConditionToken)
Creates an environment that uses DACtx to store objects that encompass the state of a program.
static Value * joinValues(QualType Ty, Value *Val1, const Environment &Env1, Value *Val2, const Environment &Env2, Environment &JoinedEnv, Environment::ValueModel &Model)
Returns a value that approximates both Val1 and Val2, or null if no such value can be produced.
void setStorageLocation(const ValueDecl &D, StorageLocation &Loc)
Assigns Loc as the storage location of D in the environment.
void removeDecl(const ValueDecl &D)
Removes the location assigned to D in the environment (if any).
RecordStorageLocation & getResultObjectLocation(const Expr &RecordPRValue) const
Returns the location of the result object for a record-type prvalue.
ExprJoinBehavior
How to treat expression state (ExprToLoc and ExprToVal) in a join.
static Environment join(const Environment &EnvA, const Environment &EnvB, Environment::ValueModel &Model, ExprJoinBehavior ExprBehavior)
Joins two environments by taking the intersection of storage locations and values that are stored in ...
Value * createValue(QualType Type)
Creates a value appropriate for Type, if Type is supported, otherwise returns null.
void setValue(const StorageLocation &Loc, Value &Val)
Assigns Val as the value of Loc in the environment.
void setThisPointeeStorageLocation(RecordStorageLocation &Loc)
Sets the storage location assigned to the this pointee in the environment.
bool canDescend(unsigned MaxDepth, const FunctionDecl *Callee) const
Returns whether this Environment can be extended to analyze the given Callee (i.e.
std::enable_if_t< std::is_base_of_v< StorageLocation, T >, T * > get(const ValueDecl &D) const
Returns the result of casting getStorageLocation(...) to a subclass of StorageLocation (using cast_or...
void initialize()
Assigns storage locations and values to all parameters, captures, global variables,...
@ Equal
True if LHS is false or RHS is true.
Definition Formula.h:64
@ Implies
True if either LHS or RHS is true.
Definition Formula.h:63
@ AtomRef
A reference to an atomic boolean variable.
Definition Formula.h:54
@ Literal
Constant true or false.
Definition Formula.h:56
@ Or
True if LHS and RHS are both true.
Definition Formula.h:62
@ And
True if its only operand is false.
Definition Formula.h:61
Models a symbolic pointer. Specifically, any value of type T*.
Definition Value.h:170
A storage location for a record (struct, class, or union).
Base class for elements of the local variable store and of the heap.
Base class for all values computed by abstract interpretation.
Definition Value.h:33
Kind getKind() const
Definition Value.h:55
@ Simple
Lightweight model that tracks known truth assignments for atoms (e.g., for each assume()) and unresol...
@ SAT
Full boolean formula tracking backed by a SAT solver.
static bool compareKeyToValueMaps(const llvm::MapVector< Key, Value * > &Map1, const llvm::MapVector< Key, Value * > &Map2, const Environment &Env1, const Environment &Env2, Environment::ValueModel &Model)
Atom
Identifies an atomic boolean variable such as "V1".
Definition Formula.h:34
static llvm::DenseMap< const ValueDecl *, StorageLocation * > intersectDeclToLoc(const llvm::DenseMap< const ValueDecl *, StorageLocation * > &DeclToLoc1, const llvm::DenseMap< const ValueDecl *, StorageLocation * > &DeclToLoc2)
Returns a map consisting of key-value entries that are present in both maps.
static bool equateUnknownValues(Value::Kind K)
bool areEquivalentValues(const Value &Val1, const Value &Val2)
An equivalence relation for values.
Definition Value.cpp:27
static llvm::MapVector< Key, Value * > widenKeyToValueMap(const llvm::MapVector< Key, Value * > &CurMap, const llvm::MapVector< Key, Value * > &PrevMap, Environment &CurEnv, const Environment &PrevEnv, Environment::ValueModel &Model, LatticeEffect &Effect)
static constexpr int MaxCompositeValueDepth
static constexpr int MaxCompositeValueSize
ReferencedDecls getReferencedDecls(const FunctionDecl &FD)
Returns declarations that are declared in or referenced from FD.
Definition ASTOps.cpp:276
RecordStorageLocation * getImplicitObjectLocation(const CXXMemberCallExpr &MCE, const Environment &Env)
Returns the storage location for the implicit object of a CXXMemberCallExpr, or null if none is defin...
static WidenResult widenDistinctValues(QualType Type, Value &Prev, const Environment &PrevEnv, Value &Current, Environment &CurrentEnv, Environment::ValueModel &Model)
const Expr & ignoreCFGOmittedNodes(const Expr &E)
Skip past nodes that the CFG does not emit.
Definition ASTOps.cpp:35
static llvm::MapVector< const StorageLocation *, Value * > joinLocToVal(const llvm::MapVector< const StorageLocation *, Value * > &LocToVal, const llvm::MapVector< const StorageLocation *, Value * > &LocToVal2, const Environment &Env1, const Environment &Env2, Environment &JoinedEnv, Environment::ValueModel &Model)
static MapT joinExprMaps(const MapT &Map1, const MapT &Map2)
static bool compareDistinctValues(QualType Type, Value &Val1, const Environment &Env1, Value &Val2, const Environment &Env2, Environment::ValueModel &Model)
RecordStorageLocation * getBaseObjectLocation(const MemberExpr &ME, const Environment &Env)
Returns the storage location for the base object of a MemberExpr, or null if none is defined in the e...
static Value * joinDistinctValues(QualType Type, Value &Val1, const Environment &Env1, Value &Val2, const Environment &Env2, Environment &JoinedEnv, Environment::ValueModel &Model)
Attempts to join distinct values Val1 and Val2 in Env1 and Env2, respectively, of the same type Type.
LatticeEffect
Effect indicating whether a lattice operation resulted in a new value.
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3178
bool DefaultInit(InterpState &S, CodePtr OpPC, const CXXConstructorDecl *Ctor)
Definition Interp.cpp:2783
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
static bool classof(const OMPClause *T)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Other
Other implicit parameter.
Definition Decl.h:1787
#define true
Definition stdbool.h:25
A collection of several types of declarations, all referenced from the same function.
Definition ASTOps.h:142
llvm::SetVector< const VarDecl * > Globals
All variables with static storage duration, notably including static member variables and static vari...
Definition ASTOps.h:147
FieldSet Fields
Non-static member variables.
Definition ASTOps.h:144
llvm::SetVector< const FunctionDecl * > Functions
Free functions and member functions which are referenced (but not necessarily called).
Definition ASTOps.h:153
The result of a widen operation.