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