xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision 3fed312d2bca7d44734ace75d18890675da0f89b)
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 
15 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/Stmt.h"
21 #include "clang/AST/Type.h"
22 #include "clang/Analysis/FlowSensitive/ASTOps.h"
23 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
24 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
25 #include "clang/Analysis/FlowSensitive/Value.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/MapVector.h"
29 #include "llvm/ADT/PointerUnion.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/ScopeExit.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include <algorithm>
34 #include <cassert>
35 #include <memory>
36 #include <utility>
37 
38 #define DEBUG_TYPE "dataflow"
39 
40 namespace clang {
41 namespace dataflow {
42 
43 // FIXME: convert these to parameters of the analysis or environment. Current
44 // settings have been experimentaly validated, but only for a particular
45 // analysis.
46 static constexpr int MaxCompositeValueDepth = 3;
47 static constexpr int MaxCompositeValueSize = 1000;
48 
49 /// Returns a map consisting of key-value entries that are present in both maps.
50 static llvm::DenseMap<const ValueDecl *, StorageLocation *> intersectDeclToLoc(
51     const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc1,
52     const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc2) {
53   llvm::DenseMap<const ValueDecl *, StorageLocation *> Result;
54   for (auto &Entry : DeclToLoc1) {
55     auto It = DeclToLoc2.find(Entry.first);
56     if (It != DeclToLoc2.end() && Entry.second == It->second)
57       Result.insert({Entry.first, Entry.second});
58   }
59   return Result;
60 }
61 
62 // Performs a join on either `ExprToLoc` or `ExprToVal`.
63 // The maps must be consistent in the sense that any entries for the same
64 // expression must map to the same location / value. This is the case if we are
65 // performing a join for control flow within a full-expression (which is the
66 // only case when this function should be used).
67 template <typename MapT> MapT joinExprMaps(const MapT &Map1, const MapT &Map2) {
68   MapT Result = Map1;
69 
70   for (const auto &Entry : Map2) {
71     [[maybe_unused]] auto [It, Inserted] = Result.insert(Entry);
72     // If there was an existing entry, its value should be the same as for the
73     // entry we were trying to insert.
74     assert(It->second == Entry.second);
75   }
76 
77   return Result;
78 }
79 
80 // Whether to consider equivalent two values with an unknown relation.
81 //
82 // FIXME: this function is a hack enabling unsoundness to support
83 // convergence. Once we have widening support for the reference/pointer and
84 // struct built-in models, this should be unconditionally `false` (and inlined
85 // as such at its call sites).
86 static bool equateUnknownValues(Value::Kind K) {
87   switch (K) {
88   case Value::Kind::Integer:
89   case Value::Kind::Pointer:
90     return true;
91   default:
92     return false;
93   }
94 }
95 
96 static bool compareDistinctValues(QualType Type, Value &Val1,
97                                   const Environment &Env1, Value &Val2,
98                                   const Environment &Env2,
99                                   Environment::ValueModel &Model) {
100   // Note: Potentially costly, but, for booleans, we could check whether both
101   // can be proven equivalent in their respective environments.
102 
103   // FIXME: move the reference/pointers logic from `areEquivalentValues` to here
104   // and implement separate, join/widen specific handling for
105   // reference/pointers.
106   switch (Model.compare(Type, Val1, Env1, Val2, Env2)) {
107   case ComparisonResult::Same:
108     return true;
109   case ComparisonResult::Different:
110     return false;
111   case ComparisonResult::Unknown:
112     return equateUnknownValues(Val1.getKind());
113   }
114   llvm_unreachable("All cases covered in switch");
115 }
116 
117 /// Attempts to join distinct values `Val1` and `Val2` in `Env1` and `Env2`,
118 /// respectively, of the same type `Type`. Joining generally produces a single
119 /// value that (soundly) approximates the two inputs, although the actual
120 /// meaning depends on `Model`.
121 static Value *joinDistinctValues(QualType Type, Value &Val1,
122                                  const Environment &Env1, Value &Val2,
123                                  const Environment &Env2,
124                                  Environment &JoinedEnv,
125                                  Environment::ValueModel &Model) {
126   // Join distinct boolean values preserving information about the constraints
127   // in the respective path conditions.
128   if (isa<BoolValue>(&Val1) && isa<BoolValue>(&Val2)) {
129     // FIXME: Checking both values should be unnecessary, since they should have
130     // a consistent shape.  However, right now we can end up with BoolValue's in
131     // integer-typed variables due to our incorrect handling of
132     // boolean-to-integer casts (we just propagate the BoolValue to the result
133     // of the cast). So, a join can encounter an integer in one branch but a
134     // bool in the other.
135     // For example:
136     // ```
137     // std::optional<bool> o;
138     // int x;
139     // if (o.has_value())
140     //   x = o.value();
141     // ```
142     auto &Expr1 = cast<BoolValue>(Val1).formula();
143     auto &Expr2 = cast<BoolValue>(Val2).formula();
144     auto &A = JoinedEnv.arena();
145     auto &JoinedVal = A.makeAtomRef(A.makeAtom());
146     JoinedEnv.assume(
147         A.makeOr(A.makeAnd(A.makeAtomRef(Env1.getFlowConditionToken()),
148                            A.makeEquals(JoinedVal, Expr1)),
149                  A.makeAnd(A.makeAtomRef(Env2.getFlowConditionToken()),
150                            A.makeEquals(JoinedVal, Expr2))));
151     return &A.makeBoolValue(JoinedVal);
152   }
153 
154   Value *JoinedVal = JoinedEnv.createValue(Type);
155   if (JoinedVal)
156     Model.join(Type, Val1, Env1, Val2, Env2, *JoinedVal, JoinedEnv);
157 
158   return JoinedVal;
159 }
160 
161 static WidenResult widenDistinctValues(QualType Type, Value &Prev,
162                                        const Environment &PrevEnv,
163                                        Value &Current, Environment &CurrentEnv,
164                                        Environment::ValueModel &Model) {
165   // Boolean-model widening.
166   if (isa<BoolValue>(Prev) && isa<BoolValue>(Current)) {
167     // FIXME: Checking both values should be unnecessary, but we can currently
168     // end up with `BoolValue`s in integer-typed variables. See comment in
169     // `joinDistinctValues()` for details.
170     auto &PrevBool = cast<BoolValue>(Prev);
171     auto &CurBool = cast<BoolValue>(Current);
172 
173     if (isa<TopBoolValue>(Prev))
174       // Safe to return `Prev` here, because Top is never dependent on the
175       // environment.
176       return {&Prev, LatticeEffect::Unchanged};
177 
178     // We may need to widen to Top, but before we do so, check whether both
179     // values are implied to be either true or false in the current environment.
180     // In that case, we can simply return a literal instead.
181     bool TruePrev = PrevEnv.proves(PrevBool.formula());
182     bool TrueCur = CurrentEnv.proves(CurBool.formula());
183     if (TruePrev && TrueCur)
184       return {&CurrentEnv.getBoolLiteralValue(true), LatticeEffect::Unchanged};
185     if (!TruePrev && !TrueCur &&
186         PrevEnv.proves(PrevEnv.arena().makeNot(PrevBool.formula())) &&
187         CurrentEnv.proves(CurrentEnv.arena().makeNot(CurBool.formula())))
188       return {&CurrentEnv.getBoolLiteralValue(false), LatticeEffect::Unchanged};
189 
190     return {&CurrentEnv.makeTopBoolValue(), LatticeEffect::Changed};
191   }
192 
193   // FIXME: Add other built-in model widening.
194 
195   // Custom-model widening.
196   if (auto Result = Model.widen(Type, Prev, PrevEnv, Current, CurrentEnv))
197     return *Result;
198 
199   return {&Current, equateUnknownValues(Prev.getKind())
200                         ? LatticeEffect::Unchanged
201                         : LatticeEffect::Changed};
202 }
203 
204 // Returns whether the values in `Map1` and `Map2` compare equal for those
205 // keys that `Map1` and `Map2` have in common.
206 template <typename Key>
207 bool compareKeyToValueMaps(const llvm::MapVector<Key, Value *> &Map1,
208                            const llvm::MapVector<Key, Value *> &Map2,
209                            const Environment &Env1, const Environment &Env2,
210                            Environment::ValueModel &Model) {
211   for (auto &Entry : Map1) {
212     Key K = Entry.first;
213     assert(K != nullptr);
214 
215     Value *Val = Entry.second;
216     assert(Val != nullptr);
217 
218     auto It = Map2.find(K);
219     if (It == Map2.end())
220       continue;
221     assert(It->second != nullptr);
222 
223     if (!areEquivalentValues(*Val, *It->second) &&
224         !compareDistinctValues(K->getType(), *Val, Env1, *It->second, Env2,
225                                Model))
226       return false;
227   }
228 
229   return true;
230 }
231 
232 // Perform a join on two `LocToVal` maps.
233 static llvm::MapVector<const StorageLocation *, Value *>
234 joinLocToVal(const llvm::MapVector<const StorageLocation *, Value *> &LocToVal,
235              const llvm::MapVector<const StorageLocation *, Value *> &LocToVal2,
236              const Environment &Env1, const Environment &Env2,
237              Environment &JoinedEnv, Environment::ValueModel &Model) {
238   llvm::MapVector<const StorageLocation *, Value *> Result;
239   for (auto &Entry : LocToVal) {
240     const StorageLocation *Loc = Entry.first;
241     assert(Loc != nullptr);
242 
243     Value *Val = Entry.second;
244     assert(Val != nullptr);
245 
246     auto It = LocToVal2.find(Loc);
247     if (It == LocToVal2.end())
248       continue;
249     assert(It->second != nullptr);
250 
251     if (Value *JoinedVal = Environment::joinValues(
252             Loc->getType(), Val, Env1, It->second, Env2, JoinedEnv, Model)) {
253       Result.insert({Loc, JoinedVal});
254     }
255   }
256 
257   return Result;
258 }
259 
260 // Perform widening on either `LocToVal` or `ExprToVal`. `Key` must be either
261 // `const StorageLocation *` or `const Expr *`.
262 template <typename Key>
263 llvm::MapVector<Key, Value *>
264 widenKeyToValueMap(const llvm::MapVector<Key, Value *> &CurMap,
265                    const llvm::MapVector<Key, Value *> &PrevMap,
266                    Environment &CurEnv, const Environment &PrevEnv,
267                    Environment::ValueModel &Model, LatticeEffect &Effect) {
268   llvm::MapVector<Key, Value *> WidenedMap;
269   for (auto &Entry : CurMap) {
270     Key K = Entry.first;
271     assert(K != nullptr);
272 
273     Value *Val = Entry.second;
274     assert(Val != nullptr);
275 
276     auto PrevIt = PrevMap.find(K);
277     if (PrevIt == PrevMap.end())
278       continue;
279     assert(PrevIt->second != nullptr);
280 
281     if (areEquivalentValues(*Val, *PrevIt->second)) {
282       WidenedMap.insert({K, Val});
283       continue;
284     }
285 
286     auto [WidenedVal, ValEffect] = widenDistinctValues(
287         K->getType(), *PrevIt->second, PrevEnv, *Val, CurEnv, Model);
288     WidenedMap.insert({K, WidenedVal});
289     if (ValEffect == LatticeEffect::Changed)
290       Effect = LatticeEffect::Changed;
291   }
292 
293   return WidenedMap;
294 }
295 
296 namespace {
297 
298 // Visitor that builds a map from record prvalues to result objects.
299 // For each result object that it encounters, it propagates the storage location
300 // of the result object to all record prvalues that can initialize it.
301 class ResultObjectVisitor : public AnalysisASTVisitor<ResultObjectVisitor> {
302 public:
303   // `ResultObjectMap` will be filled with a map from record prvalues to result
304   // object. If this visitor will traverse a function that returns a record by
305   // value, `LocForRecordReturnVal` is the location to which this record should
306   // be written; otherwise, it is null.
307   explicit ResultObjectVisitor(
308       llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap,
309       RecordStorageLocation *LocForRecordReturnVal,
310       DataflowAnalysisContext &DACtx)
311       : ResultObjectMap(ResultObjectMap),
312         LocForRecordReturnVal(LocForRecordReturnVal), DACtx(DACtx) {}
313 
314   // Traverse all member and base initializers of `Ctor`. This function is not
315   // called by `RecursiveASTVisitor`; it should be called manually if we are
316   // analyzing a constructor. `ThisPointeeLoc` is the storage location that
317   // `this` points to.
318   void TraverseConstructorInits(const CXXConstructorDecl *Ctor,
319                                 RecordStorageLocation *ThisPointeeLoc) {
320     assert(ThisPointeeLoc != nullptr);
321     for (const CXXCtorInitializer *Init : Ctor->inits()) {
322       Expr *InitExpr = Init->getInit();
323       if (FieldDecl *Field = Init->getMember();
324           Field != nullptr && Field->getType()->isRecordType()) {
325         PropagateResultObject(InitExpr, cast<RecordStorageLocation>(
326                                             ThisPointeeLoc->getChild(*Field)));
327       } else if (Init->getBaseClass()) {
328         PropagateResultObject(InitExpr, ThisPointeeLoc);
329       }
330 
331       // Ensure that any result objects within `InitExpr` (e.g. temporaries)
332       // are also propagated to the prvalues that initialize them.
333       TraverseStmt(InitExpr);
334 
335       // If this is a `CXXDefaultInitExpr`, also propagate any result objects
336       // within the default expression.
337       if (auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(InitExpr))
338         TraverseStmt(DefaultInit->getExpr());
339     }
340   }
341 
342   bool VisitVarDecl(VarDecl *VD) {
343     if (VD->getType()->isRecordType() && VD->hasInit())
344       PropagateResultObject(
345           VD->getInit(),
346           &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*VD)));
347     return true;
348   }
349 
350   bool VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE) {
351     if (MTE->getType()->isRecordType())
352       PropagateResultObject(
353           MTE->getSubExpr(),
354           &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*MTE)));
355     return true;
356   }
357 
358   bool VisitReturnStmt(ReturnStmt *Return) {
359     Expr *RetValue = Return->getRetValue();
360     if (RetValue != nullptr && RetValue->getType()->isRecordType() &&
361         RetValue->isPRValue())
362       PropagateResultObject(RetValue, LocForRecordReturnVal);
363     return true;
364   }
365 
366   bool VisitExpr(Expr *E) {
367     // Clang's AST can have record-type prvalues without a result object -- for
368     // example as full-expressions contained in a compound statement or as
369     // arguments of call expressions. We notice this if we get here and a
370     // storage location has not yet been associated with `E`. In this case,
371     // treat this as if it was a `MaterializeTemporaryExpr`.
372     if (E->isPRValue() && E->getType()->isRecordType() &&
373         !ResultObjectMap.contains(E))
374       PropagateResultObject(
375           E, &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*E)));
376     return true;
377   }
378 
379   void
380   PropagateResultObjectToRecordInitList(const RecordInitListHelper &InitList,
381                                         RecordStorageLocation *Loc) {
382     for (auto [Base, Init] : InitList.base_inits()) {
383       assert(Base->getType().getCanonicalType() ==
384              Init->getType().getCanonicalType());
385 
386       // Storage location for the base class is the same as that of the
387       // derived class because we "flatten" the object hierarchy and put all
388       // fields in `RecordStorageLocation` of the derived class.
389       PropagateResultObject(Init, Loc);
390     }
391 
392     for (auto [Field, Init] : InitList.field_inits()) {
393       // Fields of non-record type are handled in
394       // `TransferVisitor::VisitInitListExpr()`.
395       if (Field->getType()->isRecordType())
396         PropagateResultObject(
397             Init, cast<RecordStorageLocation>(Loc->getChild(*Field)));
398     }
399   }
400 
401   // Assigns `Loc` as the result object location of `E`, then propagates the
402   // location to all lower-level prvalues that initialize the same object as
403   // `E` (or one of its base classes or member variables).
404   void PropagateResultObject(Expr *E, RecordStorageLocation *Loc) {
405     if (!E->isPRValue() || !E->getType()->isRecordType()) {
406       assert(false);
407       // Ensure we don't propagate the result object if we hit this in a
408       // release build.
409       return;
410     }
411 
412     ResultObjectMap[E] = Loc;
413 
414     // The following AST node kinds are "original initializers": They are the
415     // lowest-level AST node that initializes a given object, and nothing
416     // below them can initialize the same object (or part of it).
417     if (isa<CXXConstructExpr>(E) || isa<CallExpr>(E) || isa<LambdaExpr>(E) ||
418         isa<CXXDefaultArgExpr>(E) || isa<CXXStdInitializerListExpr>(E) ||
419         isa<AtomicExpr>(E) ||
420         // We treat `BuiltinBitCastExpr` as an "original initializer" too as
421         // it may not even be casting from a record type -- and even if it is,
422         // the two objects are in general of unrelated type.
423         isa<BuiltinBitCastExpr>(E)) {
424       return;
425     }
426     if (auto *Op = dyn_cast<BinaryOperator>(E);
427         Op && Op->getOpcode() == BO_Cmp) {
428       // Builtin `<=>` returns a `std::strong_ordering` object.
429       return;
430     }
431 
432     if (auto *InitList = dyn_cast<InitListExpr>(E)) {
433       if (!InitList->isSemanticForm())
434         return;
435       if (InitList->isTransparent()) {
436         PropagateResultObject(InitList->getInit(0), Loc);
437         return;
438       }
439 
440       PropagateResultObjectToRecordInitList(RecordInitListHelper(InitList),
441                                             Loc);
442       return;
443     }
444 
445     if (auto *ParenInitList = dyn_cast<CXXParenListInitExpr>(E)) {
446       PropagateResultObjectToRecordInitList(RecordInitListHelper(ParenInitList),
447                                             Loc);
448       return;
449     }
450 
451     if (auto *Op = dyn_cast<BinaryOperator>(E); Op && Op->isCommaOp()) {
452       PropagateResultObject(Op->getRHS(), Loc);
453       return;
454     }
455 
456     if (auto *Cond = dyn_cast<AbstractConditionalOperator>(E)) {
457       PropagateResultObject(Cond->getTrueExpr(), Loc);
458       PropagateResultObject(Cond->getFalseExpr(), Loc);
459       return;
460     }
461 
462     if (auto *SE = dyn_cast<StmtExpr>(E)) {
463       PropagateResultObject(cast<Expr>(SE->getSubStmt()->body_back()), Loc);
464       return;
465     }
466 
467     if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(E)) {
468       PropagateResultObject(DIE->getExpr(), Loc);
469       return;
470     }
471 
472     // All other expression nodes that propagate a record prvalue should have
473     // exactly one child.
474     SmallVector<Stmt *, 1> Children(E->child_begin(), E->child_end());
475     LLVM_DEBUG({
476       if (Children.size() != 1)
477         E->dump();
478     });
479     assert(Children.size() == 1);
480     for (Stmt *S : Children)
481       PropagateResultObject(cast<Expr>(S), Loc);
482   }
483 
484 private:
485   llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap;
486   RecordStorageLocation *LocForRecordReturnVal;
487   DataflowAnalysisContext &DACtx;
488 };
489 
490 } // namespace
491 
492 void Environment::initialize() {
493   if (InitialTargetStmt == nullptr)
494     return;
495 
496   if (InitialTargetFunc == nullptr) {
497     initFieldsGlobalsAndFuncs(getReferencedDecls(*InitialTargetStmt));
498     ResultObjectMap =
499         std::make_shared<PrValueToResultObject>(buildResultObjectMap(
500             DACtx, InitialTargetStmt, getThisPointeeStorageLocation(),
501             /*LocForRecordReturnValue=*/nullptr));
502     return;
503   }
504 
505   initFieldsGlobalsAndFuncs(getReferencedDecls(*InitialTargetFunc));
506 
507   for (const auto *ParamDecl : InitialTargetFunc->parameters()) {
508     assert(ParamDecl != nullptr);
509     setStorageLocation(*ParamDecl, createObject(*ParamDecl, nullptr));
510   }
511 
512   if (InitialTargetFunc->getReturnType()->isRecordType())
513     LocForRecordReturnVal = &cast<RecordStorageLocation>(
514         createStorageLocation(InitialTargetFunc->getReturnType()));
515 
516   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(InitialTargetFunc)) {
517     auto *Parent = MethodDecl->getParent();
518     assert(Parent != nullptr);
519 
520     if (Parent->isLambda()) {
521       for (const auto &Capture : Parent->captures()) {
522         if (Capture.capturesVariable()) {
523           const auto *VarDecl = Capture.getCapturedVar();
524           assert(VarDecl != nullptr);
525           setStorageLocation(*VarDecl, createObject(*VarDecl, nullptr));
526         } else if (Capture.capturesThis()) {
527           const auto *SurroundingMethodDecl =
528               cast<CXXMethodDecl>(InitialTargetFunc->getNonClosureAncestor());
529           QualType ThisPointeeType =
530               SurroundingMethodDecl->getFunctionObjectParameterType();
531           setThisPointeeStorageLocation(
532               cast<RecordStorageLocation>(createObject(ThisPointeeType)));
533         }
534       }
535     } else if (MethodDecl->isImplicitObjectMemberFunction()) {
536       QualType ThisPointeeType = MethodDecl->getFunctionObjectParameterType();
537       auto &ThisLoc =
538           cast<RecordStorageLocation>(createStorageLocation(ThisPointeeType));
539       setThisPointeeStorageLocation(ThisLoc);
540       // Initialize fields of `*this` with values, but only if we're not
541       // analyzing a constructor; after all, it's the constructor's job to do
542       // this (and we want to be able to test that).
543       if (!isa<CXXConstructorDecl>(MethodDecl))
544         initializeFieldsWithValues(ThisLoc);
545     }
546   }
547 
548   // We do this below the handling of `CXXMethodDecl` above so that we can
549   // be sure that the storage location for `this` has been set.
550   ResultObjectMap =
551       std::make_shared<PrValueToResultObject>(buildResultObjectMap(
552           DACtx, InitialTargetFunc, getThisPointeeStorageLocation(),
553           LocForRecordReturnVal));
554 }
555 
556 // FIXME: Add support for resetting globals after function calls to enable the
557 // implementation of sound analyses.
558 
559 void Environment::initFieldsGlobalsAndFuncs(const ReferencedDecls &Referenced) {
560   // These have to be added before the lines that follow to ensure that
561   // `create*` work correctly for structs.
562   DACtx->addModeledFields(Referenced.Fields);
563 
564   for (const VarDecl *D : Referenced.Globals) {
565     if (getStorageLocation(*D) != nullptr)
566       continue;
567 
568     // We don't run transfer functions on the initializers of global variables,
569     // so they won't be associated with a value or storage location. We
570     // therefore intentionally don't pass an initializer to `createObject()`; in
571     // particular, this ensures that `createObject()` will initialize the fields
572     // of record-type variables with values.
573     setStorageLocation(*D, createObject(*D, nullptr));
574   }
575 
576   for (const FunctionDecl *FD : Referenced.Functions) {
577     if (getStorageLocation(*FD) != nullptr)
578       continue;
579     auto &Loc = createStorageLocation(*FD);
580     setStorageLocation(*FD, Loc);
581   }
582 }
583 
584 Environment Environment::fork() const {
585   Environment Copy(*this);
586   Copy.FlowConditionToken = DACtx->forkFlowCondition(FlowConditionToken);
587   return Copy;
588 }
589 
590 bool Environment::canDescend(unsigned MaxDepth,
591                              const FunctionDecl *Callee) const {
592   return CallStack.size() < MaxDepth && !llvm::is_contained(CallStack, Callee);
593 }
594 
595 Environment Environment::pushCall(const CallExpr *Call) const {
596   Environment Env(*this);
597 
598   if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
599     if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
600       if (!isa<CXXThisExpr>(Arg))
601         Env.ThisPointeeLoc =
602             cast<RecordStorageLocation>(getStorageLocation(*Arg));
603       // Otherwise (when the argument is `this`), retain the current
604       // environment's `ThisPointeeLoc`.
605     }
606   }
607 
608   if (Call->getType()->isRecordType() && Call->isPRValue())
609     Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call);
610 
611   Env.pushCallInternal(Call->getDirectCallee(),
612                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
613 
614   return Env;
615 }
616 
617 Environment Environment::pushCall(const CXXConstructExpr *Call) const {
618   Environment Env(*this);
619 
620   Env.ThisPointeeLoc = &Env.getResultObjectLocation(*Call);
621   Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call);
622 
623   Env.pushCallInternal(Call->getConstructor(),
624                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
625 
626   return Env;
627 }
628 
629 void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
630                                    ArrayRef<const Expr *> Args) {
631   // Canonicalize to the definition of the function. This ensures that we're
632   // putting arguments into the same `ParamVarDecl`s` that the callee will later
633   // be retrieving them from.
634   assert(FuncDecl->getDefinition() != nullptr);
635   FuncDecl = FuncDecl->getDefinition();
636 
637   CallStack.push_back(FuncDecl);
638 
639   initFieldsGlobalsAndFuncs(getReferencedDecls(*FuncDecl));
640 
641   const auto *ParamIt = FuncDecl->param_begin();
642 
643   // FIXME: Parameters don't always map to arguments 1:1; examples include
644   // overloaded operators implemented as member functions, and parameter packs.
645   for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
646     assert(ParamIt != FuncDecl->param_end());
647     const VarDecl *Param = *ParamIt;
648     setStorageLocation(*Param, createObject(*Param, Args[ArgIndex]));
649   }
650 
651   ResultObjectMap = std::make_shared<PrValueToResultObject>(
652       buildResultObjectMap(DACtx, FuncDecl, getThisPointeeStorageLocation(),
653                            LocForRecordReturnVal));
654 }
655 
656 void Environment::popCall(const CallExpr *Call, const Environment &CalleeEnv) {
657   // We ignore some entries of `CalleeEnv`:
658   // - `DACtx` because is already the same in both
659   // - We don't want the callee's `DeclCtx`, `ReturnVal`, `ReturnLoc` or
660   //   `ThisPointeeLoc` because they don't apply to us.
661   // - `DeclToLoc`, `ExprToLoc`, and `ExprToVal` capture information from the
662   //   callee's local scope, so when popping that scope, we do not propagate
663   //   the maps.
664   this->LocToVal = std::move(CalleeEnv.LocToVal);
665   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
666 
667   if (Call->isGLValue()) {
668     if (CalleeEnv.ReturnLoc != nullptr)
669       setStorageLocation(*Call, *CalleeEnv.ReturnLoc);
670   } else if (!Call->getType()->isVoidType()) {
671     if (CalleeEnv.ReturnVal != nullptr)
672       setValue(*Call, *CalleeEnv.ReturnVal);
673   }
674 }
675 
676 void Environment::popCall(const CXXConstructExpr *Call,
677                           const Environment &CalleeEnv) {
678   // See also comment in `popCall(const CallExpr *, const Environment &)` above.
679   this->LocToVal = std::move(CalleeEnv.LocToVal);
680   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
681 }
682 
683 bool Environment::equivalentTo(const Environment &Other,
684                                Environment::ValueModel &Model) const {
685   assert(DACtx == Other.DACtx);
686 
687   if (ReturnVal != Other.ReturnVal)
688     return false;
689 
690   if (ReturnLoc != Other.ReturnLoc)
691     return false;
692 
693   if (LocForRecordReturnVal != Other.LocForRecordReturnVal)
694     return false;
695 
696   if (ThisPointeeLoc != Other.ThisPointeeLoc)
697     return false;
698 
699   if (DeclToLoc != Other.DeclToLoc)
700     return false;
701 
702   if (ExprToLoc != Other.ExprToLoc)
703     return false;
704 
705   if (!compareKeyToValueMaps(ExprToVal, Other.ExprToVal, *this, Other, Model))
706     return false;
707 
708   if (!compareKeyToValueMaps(LocToVal, Other.LocToVal, *this, Other, Model))
709     return false;
710 
711   return true;
712 }
713 
714 LatticeEffect Environment::widen(const Environment &PrevEnv,
715                                  Environment::ValueModel &Model) {
716   assert(DACtx == PrevEnv.DACtx);
717   assert(ReturnVal == PrevEnv.ReturnVal);
718   assert(ReturnLoc == PrevEnv.ReturnLoc);
719   assert(LocForRecordReturnVal == PrevEnv.LocForRecordReturnVal);
720   assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc);
721   assert(CallStack == PrevEnv.CallStack);
722   assert(ResultObjectMap == PrevEnv.ResultObjectMap);
723   assert(InitialTargetFunc == PrevEnv.InitialTargetFunc);
724   assert(InitialTargetStmt == PrevEnv.InitialTargetStmt);
725 
726   auto Effect = LatticeEffect::Unchanged;
727 
728   // By the API, `PrevEnv` is a previous version of the environment for the same
729   // block, so we have some guarantees about its shape. In particular, it will
730   // be the result of a join or widen operation on previous values for this
731   // block. For `DeclToLoc`, `ExprToVal`, and `ExprToLoc`, join guarantees that
732   // these maps are subsets of the maps in `PrevEnv`. So, as long as we maintain
733   // this property here, we don't need change their current values to widen.
734   assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
735   assert(ExprToVal.size() <= PrevEnv.ExprToVal.size());
736   assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
737 
738   ExprToVal = widenKeyToValueMap(ExprToVal, PrevEnv.ExprToVal, *this, PrevEnv,
739                                  Model, Effect);
740 
741   LocToVal = widenKeyToValueMap(LocToVal, PrevEnv.LocToVal, *this, PrevEnv,
742                                 Model, Effect);
743   if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
744       ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
745       ExprToVal.size() != PrevEnv.ExprToVal.size() ||
746       LocToVal.size() != PrevEnv.LocToVal.size())
747     Effect = LatticeEffect::Changed;
748 
749   return Effect;
750 }
751 
752 Environment Environment::join(const Environment &EnvA, const Environment &EnvB,
753                               Environment::ValueModel &Model,
754                               ExprJoinBehavior ExprBehavior) {
755   assert(EnvA.DACtx == EnvB.DACtx);
756   assert(EnvA.LocForRecordReturnVal == EnvB.LocForRecordReturnVal);
757   assert(EnvA.ThisPointeeLoc == EnvB.ThisPointeeLoc);
758   assert(EnvA.CallStack == EnvB.CallStack);
759   assert(EnvA.ResultObjectMap == EnvB.ResultObjectMap);
760   assert(EnvA.InitialTargetFunc == EnvB.InitialTargetFunc);
761   assert(EnvA.InitialTargetStmt == EnvB.InitialTargetStmt);
762 
763   Environment JoinedEnv(*EnvA.DACtx);
764 
765   JoinedEnv.CallStack = EnvA.CallStack;
766   JoinedEnv.ResultObjectMap = EnvA.ResultObjectMap;
767   JoinedEnv.LocForRecordReturnVal = EnvA.LocForRecordReturnVal;
768   JoinedEnv.ThisPointeeLoc = EnvA.ThisPointeeLoc;
769   JoinedEnv.InitialTargetFunc = EnvA.InitialTargetFunc;
770   JoinedEnv.InitialTargetStmt = EnvA.InitialTargetStmt;
771 
772   const FunctionDecl *Func = EnvA.getCurrentFunc();
773   if (!Func) {
774     JoinedEnv.ReturnVal = nullptr;
775   } else {
776     JoinedEnv.ReturnVal =
777         joinValues(Func->getReturnType(), EnvA.ReturnVal, EnvA, EnvB.ReturnVal,
778                    EnvB, JoinedEnv, Model);
779   }
780 
781   if (EnvA.ReturnLoc == EnvB.ReturnLoc)
782     JoinedEnv.ReturnLoc = EnvA.ReturnLoc;
783   else
784     JoinedEnv.ReturnLoc = nullptr;
785 
786   JoinedEnv.DeclToLoc = intersectDeclToLoc(EnvA.DeclToLoc, EnvB.DeclToLoc);
787 
788   // FIXME: update join to detect backedges and simplify the flow condition
789   // accordingly.
790   JoinedEnv.FlowConditionToken = EnvA.DACtx->joinFlowConditions(
791       EnvA.FlowConditionToken, EnvB.FlowConditionToken);
792 
793   JoinedEnv.LocToVal =
794       joinLocToVal(EnvA.LocToVal, EnvB.LocToVal, EnvA, EnvB, JoinedEnv, Model);
795 
796   if (ExprBehavior == KeepExprState) {
797     JoinedEnv.ExprToVal = joinExprMaps(EnvA.ExprToVal, EnvB.ExprToVal);
798     JoinedEnv.ExprToLoc = joinExprMaps(EnvA.ExprToLoc, EnvB.ExprToLoc);
799   }
800 
801   return JoinedEnv;
802 }
803 
804 Value *Environment::joinValues(QualType Ty, Value *Val1,
805                                const Environment &Env1, Value *Val2,
806                                const Environment &Env2, Environment &JoinedEnv,
807                                Environment::ValueModel &Model) {
808   if (Val1 == nullptr || Val2 == nullptr)
809     // We can't say anything about the joined value -- even if one of the values
810     // is non-null, we don't want to simply propagate it, because it would be
811     // too specific: Because the other value is null, that means we have no
812     // information at all about the value (i.e. the value is unconstrained).
813     return nullptr;
814 
815   if (areEquivalentValues(*Val1, *Val2))
816     // Arbitrarily return one of the two values.
817     return Val1;
818 
819   return joinDistinctValues(Ty, *Val1, Env1, *Val2, Env2, JoinedEnv, Model);
820 }
821 
822 StorageLocation &Environment::createStorageLocation(QualType Type) {
823   return DACtx->createStorageLocation(Type);
824 }
825 
826 StorageLocation &Environment::createStorageLocation(const ValueDecl &D) {
827   // Evaluated declarations are always assigned the same storage locations to
828   // ensure that the environment stabilizes across loop iterations. Storage
829   // locations for evaluated declarations are stored in the analysis context.
830   return DACtx->getStableStorageLocation(D);
831 }
832 
833 StorageLocation &Environment::createStorageLocation(const Expr &E) {
834   // Evaluated expressions are always assigned the same storage locations to
835   // ensure that the environment stabilizes across loop iterations. Storage
836   // locations for evaluated expressions are stored in the analysis context.
837   return DACtx->getStableStorageLocation(E);
838 }
839 
840 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
841   assert(!DeclToLoc.contains(&D));
842   // The only kinds of declarations that may have a "variable" storage location
843   // are declarations of reference type and `BindingDecl`. For all other
844   // declaration, the storage location should be the stable storage location
845   // returned by `createStorageLocation()`.
846   assert(D.getType()->isReferenceType() || isa<BindingDecl>(D) ||
847          &Loc == &createStorageLocation(D));
848   DeclToLoc[&D] = &Loc;
849 }
850 
851 StorageLocation *Environment::getStorageLocation(const ValueDecl &D) const {
852   auto It = DeclToLoc.find(&D);
853   if (It == DeclToLoc.end())
854     return nullptr;
855 
856   StorageLocation *Loc = It->second;
857 
858   return Loc;
859 }
860 
861 void Environment::removeDecl(const ValueDecl &D) { DeclToLoc.erase(&D); }
862 
863 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
864   // `DeclRefExpr`s to builtin function types aren't glvalues, for some reason,
865   // but we still want to be able to associate a `StorageLocation` with them,
866   // so allow these as an exception.
867   assert(E.isGLValue() ||
868          E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
869   const Expr &CanonE = ignoreCFGOmittedNodes(E);
870   assert(!ExprToLoc.contains(&CanonE));
871   ExprToLoc[&CanonE] = &Loc;
872 }
873 
874 StorageLocation *Environment::getStorageLocation(const Expr &E) const {
875   // See comment in `setStorageLocation()`.
876   assert(E.isGLValue() ||
877          E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
878   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
879   return It == ExprToLoc.end() ? nullptr : &*It->second;
880 }
881 
882 RecordStorageLocation &
883 Environment::getResultObjectLocation(const Expr &RecordPRValue) const {
884   assert(RecordPRValue.getType()->isRecordType());
885   assert(RecordPRValue.isPRValue());
886 
887   assert(ResultObjectMap != nullptr);
888   RecordStorageLocation *Loc = ResultObjectMap->lookup(&RecordPRValue);
889   assert(Loc != nullptr);
890   // In release builds, use the "stable" storage location if the map lookup
891   // failed.
892   if (Loc == nullptr)
893     return cast<RecordStorageLocation>(
894         DACtx->getStableStorageLocation(RecordPRValue));
895   return *Loc;
896 }
897 
898 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
899   return DACtx->getOrCreateNullPointerValue(PointeeType);
900 }
901 
902 void Environment::initializeFieldsWithValues(RecordStorageLocation &Loc,
903                                              QualType Type) {
904   llvm::DenseSet<QualType> Visited;
905   int CreatedValuesCount = 0;
906   initializeFieldsWithValues(Loc, Type, Visited, 0, CreatedValuesCount);
907   if (CreatedValuesCount > MaxCompositeValueSize) {
908     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
909                  << '\n';
910   }
911 }
912 
913 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
914   // Records should not be associated with values.
915   assert(!isa<RecordStorageLocation>(Loc));
916   LocToVal[&Loc] = &Val;
917 }
918 
919 void Environment::setValue(const Expr &E, Value &Val) {
920   const Expr &CanonE = ignoreCFGOmittedNodes(E);
921 
922   assert(CanonE.isPRValue());
923   // Records should not be associated with values.
924   assert(!CanonE.getType()->isRecordType());
925   ExprToVal[&CanonE] = &Val;
926 }
927 
928 Value *Environment::getValue(const StorageLocation &Loc) const {
929   // Records should not be associated with values.
930   assert(!isa<RecordStorageLocation>(Loc));
931   return LocToVal.lookup(&Loc);
932 }
933 
934 Value *Environment::getValue(const ValueDecl &D) const {
935   auto *Loc = getStorageLocation(D);
936   if (Loc == nullptr)
937     return nullptr;
938   return getValue(*Loc);
939 }
940 
941 Value *Environment::getValue(const Expr &E) const {
942   // Records should not be associated with values.
943   assert(!E.getType()->isRecordType());
944 
945   if (E.isPRValue()) {
946     auto It = ExprToVal.find(&ignoreCFGOmittedNodes(E));
947     return It == ExprToVal.end() ? nullptr : It->second;
948   }
949 
950   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
951   if (It == ExprToLoc.end())
952     return nullptr;
953   return getValue(*It->second);
954 }
955 
956 Value *Environment::createValue(QualType Type) {
957   llvm::DenseSet<QualType> Visited;
958   int CreatedValuesCount = 0;
959   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
960                                                 CreatedValuesCount);
961   if (CreatedValuesCount > MaxCompositeValueSize) {
962     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
963                  << '\n';
964   }
965   return Val;
966 }
967 
968 Value *Environment::createValueUnlessSelfReferential(
969     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
970     int &CreatedValuesCount) {
971   assert(!Type.isNull());
972   assert(!Type->isReferenceType());
973   assert(!Type->isRecordType());
974 
975   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
976   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
977       Depth > MaxCompositeValueDepth)
978     return nullptr;
979 
980   if (Type->isBooleanType()) {
981     CreatedValuesCount++;
982     return &makeAtomicBoolValue();
983   }
984 
985   if (Type->isIntegerType()) {
986     // FIXME: consider instead `return nullptr`, given that we do nothing useful
987     // with integers, and so distinguishing them serves no purpose, but could
988     // prevent convergence.
989     CreatedValuesCount++;
990     return &arena().create<IntegerValue>();
991   }
992 
993   if (Type->isPointerType()) {
994     CreatedValuesCount++;
995     QualType PointeeType = Type->getPointeeType();
996     StorageLocation &PointeeLoc =
997         createLocAndMaybeValue(PointeeType, Visited, Depth, CreatedValuesCount);
998 
999     return &arena().create<PointerValue>(PointeeLoc);
1000   }
1001 
1002   return nullptr;
1003 }
1004 
1005 StorageLocation &
1006 Environment::createLocAndMaybeValue(QualType Ty,
1007                                     llvm::DenseSet<QualType> &Visited,
1008                                     int Depth, int &CreatedValuesCount) {
1009   if (!Visited.insert(Ty.getCanonicalType()).second)
1010     return createStorageLocation(Ty.getNonReferenceType());
1011   auto EraseVisited = llvm::make_scope_exit(
1012       [&Visited, Ty] { Visited.erase(Ty.getCanonicalType()); });
1013 
1014   Ty = Ty.getNonReferenceType();
1015 
1016   if (Ty->isRecordType()) {
1017     auto &Loc = cast<RecordStorageLocation>(createStorageLocation(Ty));
1018     initializeFieldsWithValues(Loc, Ty, Visited, Depth, CreatedValuesCount);
1019     return Loc;
1020   }
1021 
1022   StorageLocation &Loc = createStorageLocation(Ty);
1023 
1024   if (Value *Val = createValueUnlessSelfReferential(Ty, Visited, Depth,
1025                                                     CreatedValuesCount))
1026     setValue(Loc, *Val);
1027 
1028   return Loc;
1029 }
1030 
1031 void Environment::initializeFieldsWithValues(RecordStorageLocation &Loc,
1032                                              QualType Type,
1033                                              llvm::DenseSet<QualType> &Visited,
1034                                              int Depth,
1035                                              int &CreatedValuesCount) {
1036   auto initField = [&](QualType FieldType, StorageLocation &FieldLoc) {
1037     if (FieldType->isRecordType()) {
1038       auto &FieldRecordLoc = cast<RecordStorageLocation>(FieldLoc);
1039       initializeFieldsWithValues(FieldRecordLoc, FieldRecordLoc.getType(),
1040                                  Visited, Depth + 1, CreatedValuesCount);
1041     } else {
1042       if (getValue(FieldLoc) != nullptr)
1043         return;
1044       if (!Visited.insert(FieldType.getCanonicalType()).second)
1045         return;
1046       if (Value *Val = createValueUnlessSelfReferential(
1047               FieldType, Visited, Depth + 1, CreatedValuesCount))
1048         setValue(FieldLoc, *Val);
1049       Visited.erase(FieldType.getCanonicalType());
1050     }
1051   };
1052 
1053   for (const FieldDecl *Field : DACtx->getModeledFields(Type)) {
1054     assert(Field != nullptr);
1055     QualType FieldType = Field->getType();
1056 
1057     if (FieldType->isReferenceType()) {
1058       Loc.setChild(*Field,
1059                    &createLocAndMaybeValue(FieldType, Visited, Depth + 1,
1060                                            CreatedValuesCount));
1061     } else {
1062       StorageLocation *FieldLoc = Loc.getChild(*Field);
1063       assert(FieldLoc != nullptr);
1064       initField(FieldType, *FieldLoc);
1065     }
1066   }
1067   for (const auto &[FieldName, FieldType] : DACtx->getSyntheticFields(Type)) {
1068     // Synthetic fields cannot have reference type, so we don't need to deal
1069     // with this case.
1070     assert(!FieldType->isReferenceType());
1071     initField(FieldType, Loc.getSyntheticField(FieldName));
1072   }
1073 }
1074 
1075 StorageLocation &Environment::createObjectInternal(const ValueDecl *D,
1076                                                    QualType Ty,
1077                                                    const Expr *InitExpr) {
1078   if (Ty->isReferenceType()) {
1079     // Although variables of reference type always need to be initialized, it
1080     // can happen that we can't see the initializer, so `InitExpr` may still
1081     // be null.
1082     if (InitExpr) {
1083       if (auto *InitExprLoc = getStorageLocation(*InitExpr))
1084         return *InitExprLoc;
1085     }
1086 
1087     // Even though we have an initializer, we might not get an
1088     // InitExprLoc, for example if the InitExpr is a CallExpr for which we
1089     // don't have a function body. In this case, we just invent a storage
1090     // location and value -- it's the best we can do.
1091     return createObjectInternal(D, Ty.getNonReferenceType(), nullptr);
1092   }
1093 
1094   StorageLocation &Loc =
1095       D ? createStorageLocation(*D) : createStorageLocation(Ty);
1096 
1097   if (Ty->isRecordType()) {
1098     auto &RecordLoc = cast<RecordStorageLocation>(Loc);
1099     if (!InitExpr)
1100       initializeFieldsWithValues(RecordLoc);
1101   } else {
1102     Value *Val = nullptr;
1103     if (InitExpr)
1104       // In the (few) cases where an expression is intentionally
1105       // "uninterpreted", `InitExpr` is not associated with a value.  There are
1106       // two ways to handle this situation: propagate the status, so that
1107       // uninterpreted initializers result in uninterpreted variables, or
1108       // provide a default value. We choose the latter so that later refinements
1109       // of the variable can be used for reasoning about the surrounding code.
1110       // For this reason, we let this case be handled by the `createValue()`
1111       // call below.
1112       //
1113       // FIXME. If and when we interpret all language cases, change this to
1114       // assert that `InitExpr` is interpreted, rather than supplying a
1115       // default value (assuming we don't update the environment API to return
1116       // references).
1117       Val = getValue(*InitExpr);
1118     if (!Val)
1119       Val = createValue(Ty);
1120     if (Val)
1121       setValue(Loc, *Val);
1122   }
1123 
1124   return Loc;
1125 }
1126 
1127 void Environment::assume(const Formula &F) {
1128   DACtx->addFlowConditionConstraint(FlowConditionToken, F);
1129 }
1130 
1131 bool Environment::proves(const Formula &F) const {
1132   return DACtx->flowConditionImplies(FlowConditionToken, F);
1133 }
1134 
1135 bool Environment::allows(const Formula &F) const {
1136   return DACtx->flowConditionAllows(FlowConditionToken, F);
1137 }
1138 
1139 void Environment::dump(raw_ostream &OS) const {
1140   llvm::DenseMap<const StorageLocation *, std::string> LocToName;
1141   if (LocForRecordReturnVal != nullptr)
1142     LocToName[LocForRecordReturnVal] = "(returned record)";
1143   if (ThisPointeeLoc != nullptr)
1144     LocToName[ThisPointeeLoc] = "this";
1145 
1146   OS << "DeclToLoc:\n";
1147   for (auto [D, L] : DeclToLoc) {
1148     auto Iter = LocToName.insert({L, D->getNameAsString()}).first;
1149     OS << "  [" << Iter->second << ", " << L << "]\n";
1150   }
1151   OS << "ExprToLoc:\n";
1152   for (auto [E, L] : ExprToLoc)
1153     OS << "  [" << E << ", " << L << "]\n";
1154 
1155   OS << "ExprToVal:\n";
1156   for (auto [E, V] : ExprToVal)
1157     OS << "  [" << E << ", " << V << ": " << *V << "]\n";
1158 
1159   OS << "LocToVal:\n";
1160   for (auto [L, V] : LocToVal) {
1161     OS << "  [" << L;
1162     if (auto Iter = LocToName.find(L); Iter != LocToName.end())
1163       OS << " (" << Iter->second << ")";
1164     OS << ", " << V << ": " << *V << "]\n";
1165   }
1166 
1167   if (const FunctionDecl *Func = getCurrentFunc()) {
1168     if (Func->getReturnType()->isReferenceType()) {
1169       OS << "ReturnLoc: " << ReturnLoc;
1170       if (auto Iter = LocToName.find(ReturnLoc); Iter != LocToName.end())
1171         OS << " (" << Iter->second << ")";
1172       OS << "\n";
1173     } else if (Func->getReturnType()->isRecordType() ||
1174                isa<CXXConstructorDecl>(Func)) {
1175       OS << "LocForRecordReturnVal: " << LocForRecordReturnVal << "\n";
1176     } else if (!Func->getReturnType()->isVoidType()) {
1177       if (ReturnVal == nullptr)
1178         OS << "ReturnVal: nullptr\n";
1179       else
1180         OS << "ReturnVal: " << *ReturnVal << "\n";
1181     }
1182 
1183     if (isa<CXXMethodDecl>(Func)) {
1184       OS << "ThisPointeeLoc: " << ThisPointeeLoc << "\n";
1185     }
1186   }
1187 
1188   OS << "\n";
1189   DACtx->dumpFlowCondition(FlowConditionToken, OS);
1190 }
1191 
1192 void Environment::dump() const { dump(llvm::dbgs()); }
1193 
1194 Environment::PrValueToResultObject Environment::buildResultObjectMap(
1195     DataflowAnalysisContext *DACtx, const FunctionDecl *FuncDecl,
1196     RecordStorageLocation *ThisPointeeLoc,
1197     RecordStorageLocation *LocForRecordReturnVal) {
1198   assert(FuncDecl->doesThisDeclarationHaveABody());
1199 
1200   PrValueToResultObject Map = buildResultObjectMap(
1201       DACtx, FuncDecl->getBody(), ThisPointeeLoc, LocForRecordReturnVal);
1202 
1203   ResultObjectVisitor Visitor(Map, LocForRecordReturnVal, *DACtx);
1204   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FuncDecl))
1205     Visitor.TraverseConstructorInits(Ctor, ThisPointeeLoc);
1206 
1207   return Map;
1208 }
1209 
1210 Environment::PrValueToResultObject Environment::buildResultObjectMap(
1211     DataflowAnalysisContext *DACtx, Stmt *S,
1212     RecordStorageLocation *ThisPointeeLoc,
1213     RecordStorageLocation *LocForRecordReturnVal) {
1214   PrValueToResultObject Map;
1215   ResultObjectVisitor Visitor(Map, LocForRecordReturnVal, *DACtx);
1216   Visitor.TraverseStmt(S);
1217   return Map;
1218 }
1219 
1220 RecordStorageLocation *getImplicitObjectLocation(const CXXMemberCallExpr &MCE,
1221                                                  const Environment &Env) {
1222   Expr *ImplicitObject = MCE.getImplicitObjectArgument();
1223   if (ImplicitObject == nullptr)
1224     return nullptr;
1225   if (ImplicitObject->getType()->isPointerType()) {
1226     if (auto *Val = Env.get<PointerValue>(*ImplicitObject))
1227       return &cast<RecordStorageLocation>(Val->getPointeeLoc());
1228     return nullptr;
1229   }
1230   return cast_or_null<RecordStorageLocation>(
1231       Env.getStorageLocation(*ImplicitObject));
1232 }
1233 
1234 RecordStorageLocation *getBaseObjectLocation(const MemberExpr &ME,
1235                                              const Environment &Env) {
1236   Expr *Base = ME.getBase();
1237   if (Base == nullptr)
1238     return nullptr;
1239   if (ME.isArrow()) {
1240     if (auto *Val = Env.get<PointerValue>(*Base))
1241       return &cast<RecordStorageLocation>(Val->getPointeeLoc());
1242     return nullptr;
1243   }
1244   return Env.get<RecordStorageLocation>(*Base);
1245 }
1246 
1247 } // namespace dataflow
1248 } // namespace clang
1249