xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision 74d8455ba6a19d9eeaa561fd0eccc8cbf5351a47)
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/Type.h"
19 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
20 #include "clang/Analysis/FlowSensitive/Value.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include <cassert>
27 #include <memory>
28 #include <utility>
29 
30 namespace clang {
31 namespace dataflow {
32 
33 // FIXME: convert these to parameters of the analysis or environment. Current
34 // settings have been experimentaly validated, but only for a particular
35 // analysis.
36 static constexpr int MaxCompositeValueDepth = 3;
37 static constexpr int MaxCompositeValueSize = 1000;
38 
39 /// Returns a map consisting of key-value entries that are present in both maps.
40 template <typename K, typename V>
41 llvm::DenseMap<K, V> intersectDenseMaps(const llvm::DenseMap<K, V> &Map1,
42                                         const llvm::DenseMap<K, V> &Map2) {
43   llvm::DenseMap<K, V> Result;
44   for (auto &Entry : Map1) {
45     auto It = Map2.find(Entry.first);
46     if (It != Map2.end() && Entry.second == It->second)
47       Result.insert({Entry.first, Entry.second});
48   }
49   return Result;
50 }
51 
52 static bool compareDistinctValues(QualType Type, Value &Val1,
53                                   const Environment &Env1, Value &Val2,
54                                   const Environment &Env2,
55                                   Environment::ValueModel &Model) {
56   // Note: Potentially costly, but, for booleans, we could check whether both
57   // can be proven equivalent in their respective environments.
58 
59   // FIXME: move the reference/pointers logic from `areEquivalentValues` to here
60   // and implement separate, join/widen specific handling for
61   // reference/pointers.
62   switch (Model.compare(Type, Val1, Env1, Val2, Env2)) {
63   case ComparisonResult::Same:
64     return true;
65   case ComparisonResult::Different:
66     return false;
67   case ComparisonResult::Unknown:
68     switch (Val1.getKind()) {
69     case Value::Kind::Integer:
70     case Value::Kind::Reference:
71     case Value::Kind::Pointer:
72     case Value::Kind::Struct:
73       // FIXME: this choice intentionally introduces unsoundness to allow
74       // for convergence. Once we have widening support for the
75       // reference/pointer and struct built-in models, this should be
76       // `false`.
77       return true;
78     default:
79       return false;
80     }
81   }
82   llvm_unreachable("All cases covered in switch");
83 }
84 
85 /// Attempts to merge distinct values `Val1` and `Val2` in `Env1` and `Env2`,
86 /// respectively, of the same type `Type`. Merging generally produces a single
87 /// value that (soundly) approximates the two inputs, although the actual
88 /// meaning depends on `Model`.
89 static Value *mergeDistinctValues(QualType Type, Value &Val1,
90                                   const Environment &Env1, Value &Val2,
91                                   const Environment &Env2,
92                                   Environment &MergedEnv,
93                                   Environment::ValueModel &Model) {
94   // Join distinct boolean values preserving information about the constraints
95   // in the respective path conditions.
96   if (isa<BoolValue>(&Val1) && isa<BoolValue>(&Val2)) {
97     // FIXME: Checking both values should be unnecessary, since they should have
98     // a consistent shape.  However, right now we can end up with BoolValue's in
99     // integer-typed variables due to our incorrect handling of
100     // boolean-to-integer casts (we just propagate the BoolValue to the result
101     // of the cast). So, a join can encounter an integer in one branch but a
102     // bool in the other.
103     // For example:
104     // ```
105     // std::optional<bool> o;
106     // int x;
107     // if (o.has_value())
108     //   x = o.value();
109     // ```
110     auto *Expr1 = cast<BoolValue>(&Val1);
111     auto *Expr2 = cast<BoolValue>(&Val2);
112     auto &MergedVal = MergedEnv.makeAtomicBoolValue();
113     MergedEnv.addToFlowCondition(MergedEnv.makeOr(
114         MergedEnv.makeAnd(Env1.getFlowConditionToken(),
115                           MergedEnv.makeIff(MergedVal, *Expr1)),
116         MergedEnv.makeAnd(Env2.getFlowConditionToken(),
117                           MergedEnv.makeIff(MergedVal, *Expr2))));
118     return &MergedVal;
119   }
120 
121   // FIXME: Consider destroying `MergedValue` immediately if `ValueModel::merge`
122   // returns false to avoid storing unneeded values in `DACtx`.
123   // FIXME: Creating the value based on the type alone creates misshapen values
124   // for lvalues, since the type does not reflect the need for `ReferenceValue`.
125   if (Value *MergedVal = MergedEnv.createValue(Type))
126     if (Model.merge(Type, Val1, Env1, Val2, Env2, *MergedVal, MergedEnv))
127       return MergedVal;
128 
129   return nullptr;
130 }
131 
132 // When widening does not change `Current`, return value will equal `&Prev`.
133 static Value &widenDistinctValues(QualType Type, Value &Prev,
134                                   const Environment &PrevEnv, Value &Current,
135                                   Environment &CurrentEnv,
136                                   Environment::ValueModel &Model) {
137   // Boolean-model widening.
138   if (isa<BoolValue>(&Prev)) {
139     assert(isa<BoolValue>(Current));
140     // Widen to Top, because we know they are different values. If previous was
141     // already Top, re-use that to (implicitly) indicate that no change occured.
142     if (isa<TopBoolValue>(Prev))
143       return Prev;
144     return CurrentEnv.makeTopBoolValue();
145   }
146 
147   // FIXME: Add other built-in model widening.
148 
149   // Custom-model widening.
150   if (auto *W = Model.widen(Type, Prev, PrevEnv, Current, CurrentEnv))
151     return *W;
152 
153   // Default of widening is a no-op: leave the current value unchanged.
154   return Current;
155 }
156 
157 /// Initializes a global storage value.
158 static void insertIfGlobal(const Decl &D,
159                            llvm::DenseSet<const VarDecl *> &Vars) {
160   if (auto *V = dyn_cast<VarDecl>(&D))
161     if (V->hasGlobalStorage())
162       Vars.insert(V);
163 }
164 
165 static void insertIfFunction(const Decl &D,
166                              llvm::DenseSet<const FunctionDecl *> &Funcs) {
167   if (auto *FD = dyn_cast<FunctionDecl>(&D))
168     Funcs.insert(FD);
169 }
170 
171 static void
172 getFieldsGlobalsAndFuncs(const Decl &D,
173                          llvm::DenseSet<const FieldDecl *> &Fields,
174                          llvm::DenseSet<const VarDecl *> &Vars,
175                          llvm::DenseSet<const FunctionDecl *> &Funcs) {
176   insertIfGlobal(D, Vars);
177   insertIfFunction(D, Funcs);
178   if (const auto *Decomp = dyn_cast<DecompositionDecl>(&D))
179     for (const auto *B : Decomp->bindings())
180       if (auto *ME = dyn_cast_or_null<MemberExpr>(B->getBinding()))
181         // FIXME: should we be using `E->getFoundDecl()`?
182         if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
183           Fields.insert(FD);
184 }
185 
186 /// Traverses `S` and inserts into `Fields`, `Vars` and `Funcs` any fields,
187 /// global variables and functions that are declared in or referenced from
188 /// sub-statements.
189 static void
190 getFieldsGlobalsAndFuncs(const Stmt &S,
191                          llvm::DenseSet<const FieldDecl *> &Fields,
192                          llvm::DenseSet<const VarDecl *> &Vars,
193                          llvm::DenseSet<const FunctionDecl *> &Funcs) {
194   for (auto *Child : S.children())
195     if (Child != nullptr)
196       getFieldsGlobalsAndFuncs(*Child, Fields, Vars, Funcs);
197 
198   if (auto *DS = dyn_cast<DeclStmt>(&S)) {
199     if (DS->isSingleDecl())
200       getFieldsGlobalsAndFuncs(*DS->getSingleDecl(), Fields, Vars, Funcs);
201     else
202       for (auto *D : DS->getDeclGroup())
203         getFieldsGlobalsAndFuncs(*D, Fields, Vars, Funcs);
204   } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) {
205     insertIfGlobal(*E->getDecl(), Vars);
206     insertIfFunction(*E->getDecl(), Funcs);
207   } else if (auto *E = dyn_cast<MemberExpr>(&S)) {
208     // FIXME: should we be using `E->getFoundDecl()`?
209     const ValueDecl *VD = E->getMemberDecl();
210     insertIfGlobal(*VD, Vars);
211     insertIfFunction(*VD, Funcs);
212     if (const auto *FD = dyn_cast<FieldDecl>(VD))
213       Fields.insert(FD);
214   }
215 }
216 
217 // FIXME: Add support for resetting globals after function calls to enable
218 // the implementation of sound analyses.
219 void Environment::initFieldsGlobalsAndFuncs(const FunctionDecl *FuncDecl) {
220   assert(FuncDecl->getBody() != nullptr);
221 
222   llvm::DenseSet<const FieldDecl *> Fields;
223   llvm::DenseSet<const VarDecl *> Vars;
224   llvm::DenseSet<const FunctionDecl *> Funcs;
225 
226   // Look for global variable and field references in the
227   // constructor-initializers.
228   if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(FuncDecl)) {
229     for (const auto *Init : CtorDecl->inits()) {
230       if (Init->isMemberInitializer()) {
231         Fields.insert(Init->getMember());
232       } else if (Init->isIndirectMemberInitializer()) {
233         for (const auto *I : Init->getIndirectMember()->chain())
234           Fields.insert(cast<FieldDecl>(I));
235       }
236       const Expr *E = Init->getInit();
237       assert(E != nullptr);
238       getFieldsGlobalsAndFuncs(*E, Fields, Vars, Funcs);
239     }
240     // Add all fields mentioned in default member initializers.
241     for (const FieldDecl *F : CtorDecl->getParent()->fields())
242       if (const auto *I = F->getInClassInitializer())
243           getFieldsGlobalsAndFuncs(*I, Fields, Vars, Funcs);
244   }
245   getFieldsGlobalsAndFuncs(*FuncDecl->getBody(), Fields, Vars, Funcs);
246 
247   // These have to be added before the lines that follow to ensure that
248   // `create*` work correctly for structs.
249   DACtx->addModeledFields(Fields);
250 
251   for (const VarDecl *D : Vars) {
252     if (getStorageLocation(*D) != nullptr)
253       continue;
254     auto &Loc = createStorageLocation(D->getType().getNonReferenceType());
255     setStorageLocation(*D, Loc);
256     if (auto *Val = createValue(D->getType().getNonReferenceType()))
257       setValue(Loc, *Val);
258   }
259 
260   for (const FunctionDecl *FD : Funcs) {
261     if (getStorageLocation(*FD) != nullptr)
262       continue;
263     auto &Loc = createStorageLocation(FD->getType());
264     setStorageLocation(*FD, Loc);
265   }
266 }
267 
268 Environment::Environment(DataflowAnalysisContext &DACtx)
269     : DACtx(&DACtx),
270       FlowConditionToken(&DACtx.arena().makeFlowConditionToken()) {}
271 
272 Environment Environment::fork() const {
273   Environment Copy(*this);
274   Copy.FlowConditionToken = &DACtx->forkFlowCondition(*FlowConditionToken);
275   return Copy;
276 }
277 
278 Environment::Environment(DataflowAnalysisContext &DACtx,
279                          const DeclContext &DeclCtx)
280     : Environment(DACtx) {
281   CallStack.push_back(&DeclCtx);
282 
283   if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) {
284     assert(FuncDecl->getBody() != nullptr);
285 
286     initFieldsGlobalsAndFuncs(FuncDecl);
287 
288     for (const auto *ParamDecl : FuncDecl->parameters()) {
289       assert(ParamDecl != nullptr);
290       // References aren't objects, so the reference itself doesn't have a
291       // storage location. Instead, the storage location for a reference refers
292       // directly to an object of the referenced type -- so strip off any
293       // reference from the type.
294       auto &ParamLoc =
295           createStorageLocation(ParamDecl->getType().getNonReferenceType());
296       setStorageLocation(*ParamDecl, ParamLoc);
297       if (Value *ParamVal =
298               createValue(ParamDecl->getType().getNonReferenceType()))
299           setValue(ParamLoc, *ParamVal);
300     }
301   }
302 
303   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) {
304     auto *Parent = MethodDecl->getParent();
305     assert(Parent != nullptr);
306     if (Parent->isLambda())
307       MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext());
308 
309     // FIXME: Initialize the ThisPointeeLoc of lambdas too.
310     if (MethodDecl && !MethodDecl->isStatic()) {
311       QualType ThisPointeeType = MethodDecl->getThisObjectType();
312       ThisPointeeLoc = &cast<AggregateStorageLocation>(
313           createStorageLocation(ThisPointeeType));
314       if (Value *ThisPointeeVal = createValue(ThisPointeeType))
315         setValue(*ThisPointeeLoc, *ThisPointeeVal);
316     }
317   }
318 }
319 
320 bool Environment::canDescend(unsigned MaxDepth,
321                              const DeclContext *Callee) const {
322   return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee);
323 }
324 
325 Environment Environment::pushCall(const CallExpr *Call) const {
326   Environment Env(*this);
327 
328   if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
329     if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
330       if (!isa<CXXThisExpr>(Arg))
331         Env.ThisPointeeLoc = cast<AggregateStorageLocation>(
332             getStorageLocation(*Arg, SkipPast::Reference));
333       // Otherwise (when the argument is `this`), retain the current
334       // environment's `ThisPointeeLoc`.
335     }
336   }
337 
338   Env.pushCallInternal(Call->getDirectCallee(),
339                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
340 
341   return Env;
342 }
343 
344 Environment Environment::pushCall(const CXXConstructExpr *Call) const {
345   Environment Env(*this);
346 
347   Env.ThisPointeeLoc = &cast<AggregateStorageLocation>(
348       Env.createStorageLocation(Call->getType()));
349   if (Value *Val = Env.createValue(Call->getType()))
350     Env.setValue(*Env.ThisPointeeLoc, *Val);
351 
352   Env.pushCallInternal(Call->getConstructor(),
353                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
354 
355   return Env;
356 }
357 
358 void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
359                                    ArrayRef<const Expr *> Args) {
360   // Canonicalize to the definition of the function. This ensures that we're
361   // putting arguments into the same `ParamVarDecl`s` that the callee will later
362   // be retrieving them from.
363   assert(FuncDecl->getDefinition() != nullptr);
364   FuncDecl = FuncDecl->getDefinition();
365 
366   CallStack.push_back(FuncDecl);
367 
368   initFieldsGlobalsAndFuncs(FuncDecl);
369 
370   const auto *ParamIt = FuncDecl->param_begin();
371 
372   // FIXME: Parameters don't always map to arguments 1:1; examples include
373   // overloaded operators implemented as member functions, and parameter packs.
374   for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
375     assert(ParamIt != FuncDecl->param_end());
376 
377     const Expr *Arg = Args[ArgIndex];
378     auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
379     if (ArgLoc == nullptr)
380       continue;
381 
382     const VarDecl *Param = *ParamIt;
383 
384     QualType ParamType = Param->getType();
385     if (ParamType->isReferenceType()) {
386       setStorageLocation(*Param, *ArgLoc);
387     } else {
388       auto &Loc = createStorageLocation(*Param);
389       setStorageLocation(*Param, Loc);
390 
391       if (auto *ArgVal = getValue(*ArgLoc)) {
392         setValue(Loc, *ArgVal);
393       } else if (Value *Val = createValue(ParamType)) {
394         setValue(Loc, *Val);
395       }
396     }
397   }
398 }
399 
400 void Environment::popCall(const CallExpr *Call, const Environment &CalleeEnv) {
401   // We ignore `DACtx` because it's already the same in both. We don't want the
402   // callee's `DeclCtx`, `ReturnVal`, `ReturnLoc` or `ThisPointeeLoc`. We don't
403   // bring back `DeclToLoc` and `ExprToLoc` because we want to be able to later
404   // analyze the same callee in a different context, and `setStorageLocation`
405   // requires there to not already be a storage location assigned. Conceptually,
406   // these maps capture information from the local scope, so when popping that
407   // scope, we do not propagate the maps.
408   this->LocToVal = std::move(CalleeEnv.LocToVal);
409   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
410   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
411 
412   if (Call->isGLValue()) {
413     if (CalleeEnv.ReturnLoc != nullptr)
414       setStorageLocationStrict(*Call, *CalleeEnv.ReturnLoc);
415   } else if (!Call->getType()->isVoidType()) {
416     if (CalleeEnv.ReturnVal != nullptr)
417       setValueStrict(*Call, *CalleeEnv.ReturnVal);
418   }
419 }
420 
421 void Environment::popCall(const CXXConstructExpr *Call,
422                           const Environment &CalleeEnv) {
423   // See also comment in `popCall(const CallExpr *, const Environment &)` above.
424   this->LocToVal = std::move(CalleeEnv.LocToVal);
425   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
426   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
427 
428   if (Value *Val = CalleeEnv.getValue(*CalleeEnv.ThisPointeeLoc)) {
429     setValueStrict(*Call, *Val);
430   }
431 }
432 
433 bool Environment::equivalentTo(const Environment &Other,
434                                Environment::ValueModel &Model) const {
435   assert(DACtx == Other.DACtx);
436 
437   if (ReturnVal != Other.ReturnVal)
438     return false;
439 
440   if (ReturnLoc != Other.ReturnLoc)
441     return false;
442 
443   if (ThisPointeeLoc != Other.ThisPointeeLoc)
444     return false;
445 
446   if (DeclToLoc != Other.DeclToLoc)
447     return false;
448 
449   if (ExprToLoc != Other.ExprToLoc)
450     return false;
451 
452   // Compare the contents for the intersection of their domains.
453   for (auto &Entry : LocToVal) {
454     const StorageLocation *Loc = Entry.first;
455     assert(Loc != nullptr);
456 
457     Value *Val = Entry.second;
458     assert(Val != nullptr);
459 
460     auto It = Other.LocToVal.find(Loc);
461     if (It == Other.LocToVal.end())
462       continue;
463     assert(It->second != nullptr);
464 
465     if (!areEquivalentValues(*Val, *It->second) &&
466         !compareDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
467                                Model))
468       return false;
469   }
470 
471   return true;
472 }
473 
474 LatticeJoinEffect Environment::widen(const Environment &PrevEnv,
475                                      Environment::ValueModel &Model) {
476   assert(DACtx == PrevEnv.DACtx);
477   assert(ReturnVal == PrevEnv.ReturnVal);
478   assert(ReturnLoc == PrevEnv.ReturnLoc);
479   assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc);
480   assert(CallStack == PrevEnv.CallStack);
481 
482   auto Effect = LatticeJoinEffect::Unchanged;
483 
484   // By the API, `PrevEnv` is a previous version of the environment for the same
485   // block, so we have some guarantees about its shape. In particular, it will
486   // be the result of a join or widen operation on previous values for this
487   // block. For `DeclToLoc` and `ExprToLoc`, join guarantees that these maps are
488   // subsets of the maps in `PrevEnv`. So, as long as we maintain this property
489   // here, we don't need change their current values to widen.
490   //
491   // FIXME: `MemberLocToStruct` does not share the above property, because
492   // `join` can cause the map size to increase (when we add fresh data in places
493   // of conflict). Once this issue with join is resolved, re-enable the
494   // assertion below or replace with something that captures the desired
495   // invariant.
496   assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
497   assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
498   // assert(MemberLocToStruct.size() <= PrevEnv.MemberLocToStruct.size());
499 
500   llvm::DenseMap<const StorageLocation *, Value *> WidenedLocToVal;
501   for (auto &Entry : LocToVal) {
502     const StorageLocation *Loc = Entry.first;
503     assert(Loc != nullptr);
504 
505     Value *Val = Entry.second;
506     assert(Val != nullptr);
507 
508     auto PrevIt = PrevEnv.LocToVal.find(Loc);
509     if (PrevIt == PrevEnv.LocToVal.end())
510       continue;
511     assert(PrevIt->second != nullptr);
512 
513     if (areEquivalentValues(*Val, *PrevIt->second)) {
514       WidenedLocToVal.insert({Loc, Val});
515       continue;
516     }
517 
518     Value &WidenedVal = widenDistinctValues(Loc->getType(), *PrevIt->second,
519                                             PrevEnv, *Val, *this, Model);
520     WidenedLocToVal.insert({Loc, &WidenedVal});
521     if (&WidenedVal != PrevIt->second)
522       Effect = LatticeJoinEffect::Changed;
523   }
524   LocToVal = std::move(WidenedLocToVal);
525   // FIXME: update the equivalence calculation for `MemberLocToStruct`, once we
526   // have a systematic way of soundly comparing this map.
527   if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
528       ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
529       LocToVal.size() != PrevEnv.LocToVal.size() ||
530       MemberLocToStruct.size() != PrevEnv.MemberLocToStruct.size())
531     Effect = LatticeJoinEffect::Changed;
532 
533   return Effect;
534 }
535 
536 Environment Environment::join(const Environment &EnvA, const Environment &EnvB,
537                               Environment::ValueModel &Model) {
538   assert(EnvA.DACtx == EnvB.DACtx);
539   assert(EnvA.ThisPointeeLoc == EnvB.ThisPointeeLoc);
540   assert(EnvA.CallStack == EnvB.CallStack);
541 
542   Environment JoinedEnv(*EnvA.DACtx);
543 
544   JoinedEnv.CallStack = EnvA.CallStack;
545   JoinedEnv.ThisPointeeLoc = EnvA.ThisPointeeLoc;
546 
547   if (EnvA.ReturnVal == nullptr || EnvB.ReturnVal == nullptr) {
548     // `ReturnVal` might not always get set -- for example if we have a return
549     // statement of the form `return some_other_func()` and we decide not to
550     // analyze `some_other_func()`.
551     // In this case, we can't say anything about the joined return value -- we
552     // don't simply want to propagate the return value that we do have, because
553     // it might not be the correct one.
554     // This occurs for example in the test `ContextSensitiveMutualRecursion`.
555     JoinedEnv.ReturnVal = nullptr;
556   } else if (areEquivalentValues(*EnvA.ReturnVal, *EnvB.ReturnVal)) {
557     JoinedEnv.ReturnVal = EnvA.ReturnVal;
558   } else {
559     assert(!EnvA.CallStack.empty());
560     // FIXME: Make `CallStack` a vector of `FunctionDecl` so we don't need this
561     // cast.
562     auto *Func = dyn_cast<FunctionDecl>(EnvA.CallStack.back());
563     assert(Func != nullptr);
564     if (Value *MergedVal =
565             mergeDistinctValues(Func->getReturnType(), *EnvA.ReturnVal, EnvA,
566                                 *EnvB.ReturnVal, EnvB, JoinedEnv, Model))
567       JoinedEnv.ReturnVal = MergedVal;
568   }
569 
570   if (EnvA.ReturnLoc == EnvB.ReturnLoc)
571     JoinedEnv.ReturnLoc = EnvA.ReturnLoc;
572   else
573     JoinedEnv.ReturnLoc = nullptr;
574 
575   // FIXME: Once we're able to remove declarations from `DeclToLoc` when their
576   // lifetime ends, add an assertion that there aren't any entries in
577   // `DeclToLoc` and `Other.DeclToLoc` that map the same declaration to
578   // different storage locations.
579   JoinedEnv.DeclToLoc = intersectDenseMaps(EnvA.DeclToLoc, EnvB.DeclToLoc);
580 
581   JoinedEnv.ExprToLoc = intersectDenseMaps(EnvA.ExprToLoc, EnvB.ExprToLoc);
582 
583   JoinedEnv.MemberLocToStruct =
584       intersectDenseMaps(EnvA.MemberLocToStruct, EnvB.MemberLocToStruct);
585 
586   // FIXME: update join to detect backedges and simplify the flow condition
587   // accordingly.
588   JoinedEnv.FlowConditionToken = &EnvA.DACtx->joinFlowConditions(
589       *EnvA.FlowConditionToken, *EnvB.FlowConditionToken);
590 
591   for (auto &Entry : EnvA.LocToVal) {
592     const StorageLocation *Loc = Entry.first;
593     assert(Loc != nullptr);
594 
595     Value *Val = Entry.second;
596     assert(Val != nullptr);
597 
598     auto It = EnvB.LocToVal.find(Loc);
599     if (It == EnvB.LocToVal.end())
600       continue;
601     assert(It->second != nullptr);
602 
603     if (areEquivalentValues(*Val, *It->second)) {
604       JoinedEnv.LocToVal.insert({Loc, Val});
605       continue;
606     }
607 
608     if (Value *MergedVal = mergeDistinctValues(
609             Loc->getType(), *Val, EnvA, *It->second, EnvB, JoinedEnv, Model)) {
610       JoinedEnv.LocToVal.insert({Loc, MergedVal});
611     }
612   }
613 
614   return JoinedEnv;
615 }
616 
617 StorageLocation &Environment::createStorageLocation(QualType Type) {
618   return DACtx->createStorageLocation(Type);
619 }
620 
621 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
622   // Evaluated declarations are always assigned the same storage locations to
623   // ensure that the environment stabilizes across loop iterations. Storage
624   // locations for evaluated declarations are stored in the analysis context.
625   return DACtx->getStableStorageLocation(D);
626 }
627 
628 StorageLocation &Environment::createStorageLocation(const Expr &E) {
629   // Evaluated expressions are always assigned the same storage locations to
630   // ensure that the environment stabilizes across loop iterations. Storage
631   // locations for evaluated expressions are stored in the analysis context.
632   return DACtx->getStableStorageLocation(E);
633 }
634 
635 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
636   assert(!DeclToLoc.contains(&D));
637   assert(!isa_and_nonnull<ReferenceValue>(getValue(Loc)));
638   DeclToLoc[&D] = &Loc;
639 }
640 
641 StorageLocation *Environment::getStorageLocation(const ValueDecl &D) const {
642   auto It = DeclToLoc.find(&D);
643   if (It == DeclToLoc.end())
644     return nullptr;
645 
646   StorageLocation *Loc = It->second;
647 
648   assert(!isa_and_nonnull<ReferenceValue>(getValue(*Loc)));
649 
650   return Loc;
651 }
652 
653 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
654   const Expr &CanonE = ignoreCFGOmittedNodes(E);
655   assert(!ExprToLoc.contains(&CanonE));
656   ExprToLoc[&CanonE] = &Loc;
657 }
658 
659 void Environment::setStorageLocationStrict(const Expr &E,
660                                            StorageLocation &Loc) {
661   // `DeclRefExpr`s to builtin function types aren't glvalues, for some reason,
662   // but we still want to be able to associate a `StorageLocation` with them,
663   // so allow these as an exception.
664   assert(E.isGLValue() ||
665          E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
666   setStorageLocation(E, Loc);
667 }
668 
669 StorageLocation *Environment::getStorageLocation(const Expr &E,
670                                                  SkipPast SP) const {
671   // FIXME: Add a test with parens.
672   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
673   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
674 }
675 
676 StorageLocation *Environment::getStorageLocationStrict(const Expr &E) const {
677   // See comment in `setStorageLocationStrict()`.
678   assert(E.isGLValue() ||
679          E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
680   StorageLocation *Loc = getStorageLocation(E, SkipPast::None);
681 
682   if (Loc == nullptr)
683     return nullptr;
684 
685   if (auto *RefVal = dyn_cast_or_null<ReferenceValue>(getValue(*Loc)))
686     return &RefVal->getReferentLoc();
687 
688   return Loc;
689 }
690 
691 AggregateStorageLocation *Environment::getThisPointeeStorageLocation() const {
692   return ThisPointeeLoc;
693 }
694 
695 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
696   return DACtx->getOrCreateNullPointerValue(PointeeType);
697 }
698 
699 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
700   LocToVal[&Loc] = &Val;
701 
702   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
703     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
704 
705     const QualType Type = AggregateLoc.getType();
706     assert(Type->isRecordType());
707 
708     for (const FieldDecl *Field : DACtx->getReferencedFields(Type)) {
709       assert(Field != nullptr);
710       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
711       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
712       if (auto *FieldVal = StructVal->getChild(*Field))
713         setValue(FieldLoc, *FieldVal);
714     }
715   }
716 
717   auto It = MemberLocToStruct.find(&Loc);
718   if (It != MemberLocToStruct.end()) {
719     // `Loc` is the location of a struct member so we need to also update the
720     // value of the member in the corresponding `StructValue`.
721 
722     assert(It->second.first != nullptr);
723     StructValue &StructVal = *It->second.first;
724 
725     assert(It->second.second != nullptr);
726     const ValueDecl &Member = *It->second.second;
727 
728     StructVal.setChild(Member, Val);
729   }
730 }
731 
732 void Environment::clearValue(const StorageLocation &Loc) {
733   LocToVal.erase(&Loc);
734 
735   if (auto It = MemberLocToStruct.find(&Loc); It != MemberLocToStruct.end()) {
736     // `Loc` is the location of a struct member so we need to also clear the
737     // member in the corresponding `StructValue`.
738 
739     assert(It->second.first != nullptr);
740     StructValue &StructVal = *It->second.first;
741 
742     assert(It->second.second != nullptr);
743     const ValueDecl &Member = *It->second.second;
744 
745     StructVal.clearChild(Member);
746   }
747 }
748 
749 void Environment::setValueStrict(const Expr &E, Value &Val) {
750   assert(E.isPRValue());
751   assert(!isa<ReferenceValue>(Val));
752 
753   StorageLocation *Loc = getStorageLocation(E, SkipPast::None);
754   if (Loc == nullptr) {
755     Loc = &createStorageLocation(E);
756     setStorageLocation(E, *Loc);
757   }
758   setValue(*Loc, Val);
759 }
760 
761 Value *Environment::getValue(const StorageLocation &Loc) const {
762   return LocToVal.lookup(&Loc);
763 }
764 
765 Value *Environment::getValue(const ValueDecl &D) const {
766   auto *Loc = getStorageLocation(D);
767   if (Loc == nullptr)
768     return nullptr;
769   return getValue(*Loc);
770 }
771 
772 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
773   auto *Loc = getStorageLocation(E, SP);
774   if (Loc == nullptr)
775     return nullptr;
776   return getValue(*Loc);
777 }
778 
779 Value *Environment::getValueStrict(const Expr &E) const {
780   assert(E.isPRValue());
781   Value *Val = getValue(E, SkipPast::None);
782 
783   assert(Val == nullptr || !isa<ReferenceValue>(Val));
784 
785   return Val;
786 }
787 
788 Value *Environment::createValue(QualType Type) {
789   llvm::DenseSet<QualType> Visited;
790   int CreatedValuesCount = 0;
791   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
792                                                 CreatedValuesCount);
793   if (CreatedValuesCount > MaxCompositeValueSize) {
794     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
795                  << '\n';
796   }
797   return Val;
798 }
799 
800 Value *Environment::createValueUnlessSelfReferential(
801     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
802     int &CreatedValuesCount) {
803   assert(!Type.isNull());
804 
805   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
806   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
807       Depth > MaxCompositeValueDepth)
808     return nullptr;
809 
810   if (Type->isBooleanType()) {
811     CreatedValuesCount++;
812     return &makeAtomicBoolValue();
813   }
814 
815   if (Type->isIntegerType()) {
816     // FIXME: consider instead `return nullptr`, given that we do nothing useful
817     // with integers, and so distinguishing them serves no purpose, but could
818     // prevent convergence.
819     CreatedValuesCount++;
820     return &DACtx->arena().create<IntegerValue>();
821   }
822 
823   if (Type->isReferenceType() || Type->isPointerType()) {
824     CreatedValuesCount++;
825     QualType PointeeType = Type->getPointeeType();
826     auto &PointeeLoc = createStorageLocation(PointeeType);
827 
828     if (Visited.insert(PointeeType.getCanonicalType()).second) {
829       Value *PointeeVal = createValueUnlessSelfReferential(
830           PointeeType, Visited, Depth, CreatedValuesCount);
831       Visited.erase(PointeeType.getCanonicalType());
832 
833       if (PointeeVal != nullptr)
834         setValue(PointeeLoc, *PointeeVal);
835     }
836 
837     if (Type->isReferenceType())
838       return &DACtx->arena().create<ReferenceValue>(PointeeLoc);
839     else
840       return &DACtx->arena().create<PointerValue>(PointeeLoc);
841   }
842 
843   if (Type->isRecordType()) {
844     CreatedValuesCount++;
845     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
846     for (const FieldDecl *Field : DACtx->getReferencedFields(Type)) {
847       assert(Field != nullptr);
848 
849       QualType FieldType = Field->getType();
850       if (Visited.contains(FieldType.getCanonicalType()))
851         continue;
852 
853       Visited.insert(FieldType.getCanonicalType());
854       if (auto *FieldValue = createValueUnlessSelfReferential(
855               FieldType, Visited, Depth + 1, CreatedValuesCount))
856         FieldValues.insert({Field, FieldValue});
857       Visited.erase(FieldType.getCanonicalType());
858     }
859 
860     return &DACtx->arena().create<StructValue>(std::move(FieldValues));
861   }
862 
863   return nullptr;
864 }
865 
866 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
867   switch (SP) {
868   case SkipPast::None:
869     return Loc;
870   case SkipPast::Reference:
871     // References cannot be chained so we only need to skip past one level of
872     // indirection.
873     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
874       return Val->getReferentLoc();
875     return Loc;
876   }
877   llvm_unreachable("bad SkipPast kind");
878 }
879 
880 const StorageLocation &Environment::skip(const StorageLocation &Loc,
881                                          SkipPast SP) const {
882   return skip(*const_cast<StorageLocation *>(&Loc), SP);
883 }
884 
885 void Environment::addToFlowCondition(BoolValue &Val) {
886   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
887 }
888 
889 bool Environment::flowConditionImplies(BoolValue &Val) const {
890   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
891 }
892 
893 void Environment::dump(raw_ostream &OS) const {
894   // FIXME: add printing for remaining fields and allow caller to decide what
895   // fields are printed.
896   OS << "DeclToLoc:\n";
897   for (auto [D, L] : DeclToLoc)
898     OS << "  [" << D->getNameAsString() << ", " << L << "]\n";
899 
900   OS << "ExprToLoc:\n";
901   for (auto [E, L] : ExprToLoc)
902     OS << "  [" << E << ", " << L << "]\n";
903 
904   OS << "LocToVal:\n";
905   for (auto [L, V] : LocToVal) {
906     OS << "  [" << L << ", " << V << ": " << *V << "]\n";
907   }
908 
909   OS << "FlowConditionToken:\n";
910   DACtx->dumpFlowCondition(*FlowConditionToken, OS);
911 }
912 
913 void Environment::dump() const {
914   dump(llvm::dbgs());
915 }
916 
917 AggregateStorageLocation *
918 getImplicitObjectLocation(const CXXMemberCallExpr &MCE,
919                           const Environment &Env) {
920   Expr *ImplicitObject = MCE.getImplicitObjectArgument();
921   if (ImplicitObject == nullptr)
922     return nullptr;
923   StorageLocation *Loc =
924       Env.getStorageLocation(*ImplicitObject, SkipPast::Reference);
925   if (Loc == nullptr)
926     return nullptr;
927   if (ImplicitObject->getType()->isPointerType()) {
928     if (auto *Val = cast_or_null<PointerValue>(Env.getValue(*Loc)))
929       return &cast<AggregateStorageLocation>(Val->getPointeeLoc());
930     return nullptr;
931   }
932   return cast<AggregateStorageLocation>(Loc);
933 }
934 
935 AggregateStorageLocation *getBaseObjectLocation(const MemberExpr &ME,
936                                                 const Environment &Env) {
937   Expr *Base = ME.getBase();
938   if (Base == nullptr)
939     return nullptr;
940   StorageLocation *Loc = Env.getStorageLocation(*Base, SkipPast::Reference);
941   if (Loc == nullptr)
942     return nullptr;
943   if (ME.isArrow()) {
944     if (auto *Val = cast_or_null<PointerValue>(Env.getValue(*Loc)))
945       return &cast<AggregateStorageLocation>(Val->getPointeeLoc());
946     return nullptr;
947   }
948   return cast<AggregateStorageLocation>(Loc);
949 }
950 
951 } // namespace dataflow
952 } // namespace clang
953