xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision fb13d027eae405a7be96fd7da0d72422e48a0719)
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 (const auto *M = Init->getAnyMember())
231           Fields.insert(M);
232       const Expr *E = Init->getInit();
233       assert(E != nullptr);
234       getFieldsGlobalsAndFuncs(*E, Fields, Vars, Funcs);
235     }
236     // Add all fields mentioned in default member initializers.
237     for (const FieldDecl *F : CtorDecl->getParent()->fields())
238       if (const auto *I = F->getInClassInitializer())
239           getFieldsGlobalsAndFuncs(*I, Fields, Vars, Funcs);
240   }
241   getFieldsGlobalsAndFuncs(*FuncDecl->getBody(), Fields, Vars, Funcs);
242 
243   // These have to be added before the lines that follow to ensure that
244   // `create*` work correctly for structs.
245   DACtx->addModeledFields(Fields);
246 
247   for (const VarDecl *D : Vars) {
248     if (getStorageLocation(*D) != nullptr)
249       continue;
250     auto &Loc = createStorageLocation(D->getType().getNonReferenceType());
251     setStorageLocation(*D, Loc);
252     if (auto *Val = createValue(D->getType().getNonReferenceType()))
253       setValue(Loc, *Val);
254   }
255 
256   for (const FunctionDecl *FD : Funcs) {
257     if (getStorageLocation(*FD) != nullptr)
258       continue;
259     auto &Loc = createStorageLocation(FD->getType());
260     setStorageLocation(*FD, Loc);
261   }
262 }
263 
264 Environment::Environment(DataflowAnalysisContext &DACtx)
265     : DACtx(&DACtx),
266       FlowConditionToken(&DACtx.arena().makeFlowConditionToken()) {}
267 
268 Environment Environment::fork() const {
269   Environment Copy(*this);
270   Copy.FlowConditionToken = &DACtx->forkFlowCondition(*FlowConditionToken);
271   return Copy;
272 }
273 
274 Environment::Environment(DataflowAnalysisContext &DACtx,
275                          const DeclContext &DeclCtx)
276     : Environment(DACtx) {
277   CallStack.push_back(&DeclCtx);
278 
279   if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) {
280     assert(FuncDecl->getBody() != nullptr);
281 
282     initFieldsGlobalsAndFuncs(FuncDecl);
283 
284     for (const auto *ParamDecl : FuncDecl->parameters()) {
285       assert(ParamDecl != nullptr);
286       // References aren't objects, so the reference itself doesn't have a
287       // storage location. Instead, the storage location for a reference refers
288       // directly to an object of the referenced type -- so strip off any
289       // reference from the type.
290       auto &ParamLoc =
291           createStorageLocation(ParamDecl->getType().getNonReferenceType());
292       setStorageLocation(*ParamDecl, ParamLoc);
293       if (Value *ParamVal =
294               createValue(ParamDecl->getType().getNonReferenceType()))
295           setValue(ParamLoc, *ParamVal);
296     }
297   }
298 
299   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) {
300     auto *Parent = MethodDecl->getParent();
301     assert(Parent != nullptr);
302     if (Parent->isLambda())
303       MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext());
304 
305     // FIXME: Initialize the ThisPointeeLoc of lambdas too.
306     if (MethodDecl && !MethodDecl->isStatic()) {
307       QualType ThisPointeeType = MethodDecl->getThisObjectType();
308       ThisPointeeLoc = &createStorageLocation(ThisPointeeType);
309       if (Value *ThisPointeeVal = createValue(ThisPointeeType))
310         setValue(*ThisPointeeLoc, *ThisPointeeVal);
311     }
312   }
313 }
314 
315 bool Environment::canDescend(unsigned MaxDepth,
316                              const DeclContext *Callee) const {
317   return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee);
318 }
319 
320 Environment Environment::pushCall(const CallExpr *Call) const {
321   Environment Env(*this);
322 
323   if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
324     if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
325       if (!isa<CXXThisExpr>(Arg))
326         Env.ThisPointeeLoc = getStorageLocation(*Arg, SkipPast::Reference);
327       // Otherwise (when the argument is `this`), retain the current
328       // environment's `ThisPointeeLoc`.
329     }
330   }
331 
332   Env.pushCallInternal(Call->getDirectCallee(),
333                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
334 
335   return Env;
336 }
337 
338 Environment Environment::pushCall(const CXXConstructExpr *Call) const {
339   Environment Env(*this);
340 
341   Env.ThisPointeeLoc = &Env.createStorageLocation(Call->getType());
342   if (Value *Val = Env.createValue(Call->getType()))
343     Env.setValue(*Env.ThisPointeeLoc, *Val);
344 
345   Env.pushCallInternal(Call->getConstructor(),
346                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
347 
348   return Env;
349 }
350 
351 void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
352                                    ArrayRef<const Expr *> Args) {
353   // Canonicalize to the definition of the function. This ensures that we're
354   // putting arguments into the same `ParamVarDecl`s` that the callee will later
355   // be retrieving them from.
356   assert(FuncDecl->getDefinition() != nullptr);
357   FuncDecl = FuncDecl->getDefinition();
358 
359   CallStack.push_back(FuncDecl);
360 
361   initFieldsGlobalsAndFuncs(FuncDecl);
362 
363   const auto *ParamIt = FuncDecl->param_begin();
364 
365   // FIXME: Parameters don't always map to arguments 1:1; examples include
366   // overloaded operators implemented as member functions, and parameter packs.
367   for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
368     assert(ParamIt != FuncDecl->param_end());
369 
370     const Expr *Arg = Args[ArgIndex];
371     auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
372     if (ArgLoc == nullptr)
373       continue;
374 
375     const VarDecl *Param = *ParamIt;
376 
377     QualType ParamType = Param->getType();
378     if (ParamType->isReferenceType()) {
379       setStorageLocation(*Param, *ArgLoc);
380     } else {
381       auto &Loc = createStorageLocation(*Param);
382       setStorageLocation(*Param, Loc);
383 
384       if (auto *ArgVal = getValue(*ArgLoc)) {
385         setValue(Loc, *ArgVal);
386       } else if (Value *Val = createValue(ParamType)) {
387         setValue(Loc, *Val);
388       }
389     }
390   }
391 }
392 
393 void Environment::popCall(const CallExpr *Call, const Environment &CalleeEnv) {
394   // We ignore `DACtx` because it's already the same in both. We don't want the
395   // callee's `DeclCtx`, `ReturnVal`, `ReturnLoc` or `ThisPointeeLoc`. We don't
396   // bring back `DeclToLoc` and `ExprToLoc` because we want to be able to later
397   // analyze the same callee in a different context, and `setStorageLocation`
398   // requires there to not already be a storage location assigned. Conceptually,
399   // these maps capture information from the local scope, so when popping that
400   // scope, we do not propagate the maps.
401   this->LocToVal = std::move(CalleeEnv.LocToVal);
402   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
403   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
404 
405   if (Call->isGLValue()) {
406     if (CalleeEnv.ReturnLoc != nullptr)
407       setStorageLocationStrict(*Call, *CalleeEnv.ReturnLoc);
408   } else if (!Call->getType()->isVoidType()) {
409     if (CalleeEnv.ReturnVal != nullptr)
410       setValueStrict(*Call, *CalleeEnv.ReturnVal);
411   }
412 }
413 
414 void Environment::popCall(const CXXConstructExpr *Call,
415                           const Environment &CalleeEnv) {
416   // See also comment in `popCall(const CallExpr *, const Environment &)` above.
417   this->LocToVal = std::move(CalleeEnv.LocToVal);
418   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
419   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
420 
421   if (Value *Val = CalleeEnv.getValue(*CalleeEnv.ThisPointeeLoc)) {
422     setValueStrict(*Call, *Val);
423   }
424 }
425 
426 bool Environment::equivalentTo(const Environment &Other,
427                                Environment::ValueModel &Model) const {
428   assert(DACtx == Other.DACtx);
429 
430   if (ReturnVal != Other.ReturnVal)
431     return false;
432 
433   if (ReturnLoc != Other.ReturnLoc)
434     return false;
435 
436   if (ThisPointeeLoc != Other.ThisPointeeLoc)
437     return false;
438 
439   if (DeclToLoc != Other.DeclToLoc)
440     return false;
441 
442   if (ExprToLoc != Other.ExprToLoc)
443     return false;
444 
445   // Compare the contents for the intersection of their domains.
446   for (auto &Entry : LocToVal) {
447     const StorageLocation *Loc = Entry.first;
448     assert(Loc != nullptr);
449 
450     Value *Val = Entry.second;
451     assert(Val != nullptr);
452 
453     auto It = Other.LocToVal.find(Loc);
454     if (It == Other.LocToVal.end())
455       continue;
456     assert(It->second != nullptr);
457 
458     if (!areEquivalentValues(*Val, *It->second) &&
459         !compareDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
460                                Model))
461       return false;
462   }
463 
464   return true;
465 }
466 
467 LatticeJoinEffect Environment::widen(const Environment &PrevEnv,
468                                      Environment::ValueModel &Model) {
469   assert(DACtx == PrevEnv.DACtx);
470   assert(ReturnVal == PrevEnv.ReturnVal);
471   assert(ReturnLoc == PrevEnv.ReturnLoc);
472   assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc);
473   assert(CallStack == PrevEnv.CallStack);
474 
475   auto Effect = LatticeJoinEffect::Unchanged;
476 
477   // By the API, `PrevEnv` is a previous version of the environment for the same
478   // block, so we have some guarantees about its shape. In particular, it will
479   // be the result of a join or widen operation on previous values for this
480   // block. For `DeclToLoc` and `ExprToLoc`, join guarantees that these maps are
481   // subsets of the maps in `PrevEnv`. So, as long as we maintain this property
482   // here, we don't need change their current values to widen.
483   //
484   // FIXME: `MemberLocToStruct` does not share the above property, because
485   // `join` can cause the map size to increase (when we add fresh data in places
486   // of conflict). Once this issue with join is resolved, re-enable the
487   // assertion below or replace with something that captures the desired
488   // invariant.
489   assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
490   assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
491   // assert(MemberLocToStruct.size() <= PrevEnv.MemberLocToStruct.size());
492 
493   llvm::DenseMap<const StorageLocation *, Value *> WidenedLocToVal;
494   for (auto &Entry : LocToVal) {
495     const StorageLocation *Loc = Entry.first;
496     assert(Loc != nullptr);
497 
498     Value *Val = Entry.second;
499     assert(Val != nullptr);
500 
501     auto PrevIt = PrevEnv.LocToVal.find(Loc);
502     if (PrevIt == PrevEnv.LocToVal.end())
503       continue;
504     assert(PrevIt->second != nullptr);
505 
506     if (areEquivalentValues(*Val, *PrevIt->second)) {
507       WidenedLocToVal.insert({Loc, Val});
508       continue;
509     }
510 
511     Value &WidenedVal = widenDistinctValues(Loc->getType(), *PrevIt->second,
512                                             PrevEnv, *Val, *this, Model);
513     WidenedLocToVal.insert({Loc, &WidenedVal});
514     if (&WidenedVal != PrevIt->second)
515       Effect = LatticeJoinEffect::Changed;
516   }
517   LocToVal = std::move(WidenedLocToVal);
518   // FIXME: update the equivalence calculation for `MemberLocToStruct`, once we
519   // have a systematic way of soundly comparing this map.
520   if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
521       ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
522       LocToVal.size() != PrevEnv.LocToVal.size() ||
523       MemberLocToStruct.size() != PrevEnv.MemberLocToStruct.size())
524     Effect = LatticeJoinEffect::Changed;
525 
526   return Effect;
527 }
528 
529 LatticeJoinEffect Environment::join(const Environment &Other,
530                                     Environment::ValueModel &Model) {
531   assert(DACtx == Other.DACtx);
532   assert(ThisPointeeLoc == Other.ThisPointeeLoc);
533   assert(CallStack == Other.CallStack);
534 
535   auto Effect = LatticeJoinEffect::Unchanged;
536 
537   Environment JoinedEnv(*DACtx);
538 
539   JoinedEnv.CallStack = CallStack;
540   JoinedEnv.ThisPointeeLoc = ThisPointeeLoc;
541 
542   if (ReturnVal == nullptr || Other.ReturnVal == nullptr) {
543     // `ReturnVal` might not always get set -- for example if we have a return
544     // statement of the form `return some_other_func()` and we decide not to
545     // analyze `some_other_func()`.
546     // In this case, we can't say anything about the joined return value -- we
547     // don't simply want to propagate the return value that we do have, because
548     // it might not be the correct one.
549     // This occurs for example in the test `ContextSensitiveMutualRecursion`.
550     JoinedEnv.ReturnVal = nullptr;
551   } else if (areEquivalentValues(*ReturnVal, *Other.ReturnVal)) {
552     JoinedEnv.ReturnVal = ReturnVal;
553   } else {
554     assert(!CallStack.empty());
555     // FIXME: Make `CallStack` a vector of `FunctionDecl` so we don't need this
556     // cast.
557     auto *Func = dyn_cast<FunctionDecl>(CallStack.back());
558     assert(Func != nullptr);
559     if (Value *MergedVal =
560             mergeDistinctValues(Func->getReturnType(), *ReturnVal, *this,
561                                 *Other.ReturnVal, Other, JoinedEnv, Model)) {
562       JoinedEnv.ReturnVal = MergedVal;
563       Effect = LatticeJoinEffect::Changed;
564     }
565   }
566 
567   if (ReturnLoc == Other.ReturnLoc)
568     JoinedEnv.ReturnLoc = ReturnLoc;
569   else
570     JoinedEnv.ReturnLoc = nullptr;
571 
572   // FIXME: Once we're able to remove declarations from `DeclToLoc` when their
573   // lifetime ends, add an assertion that there aren't any entries in
574   // `DeclToLoc` and `Other.DeclToLoc` that map the same declaration to
575   // different storage locations.
576   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
577   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
578     Effect = LatticeJoinEffect::Changed;
579 
580   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
581   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
582     Effect = LatticeJoinEffect::Changed;
583 
584   JoinedEnv.MemberLocToStruct =
585       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
586   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
587     Effect = LatticeJoinEffect::Changed;
588 
589   // FIXME: set `Effect` as needed.
590   // FIXME: update join to detect backedges and simplify the flow condition
591   // accordingly.
592   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
593       *FlowConditionToken, *Other.FlowConditionToken);
594 
595   for (auto &Entry : LocToVal) {
596     const StorageLocation *Loc = Entry.first;
597     assert(Loc != nullptr);
598 
599     Value *Val = Entry.second;
600     assert(Val != nullptr);
601 
602     auto It = Other.LocToVal.find(Loc);
603     if (It == Other.LocToVal.end())
604       continue;
605     assert(It->second != nullptr);
606 
607     if (areEquivalentValues(*Val, *It->second)) {
608       JoinedEnv.LocToVal.insert({Loc, Val});
609       continue;
610     }
611 
612     if (Value *MergedVal =
613             mergeDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
614                                 JoinedEnv, Model)) {
615       JoinedEnv.LocToVal.insert({Loc, MergedVal});
616       Effect = LatticeJoinEffect::Changed;
617     }
618   }
619   if (LocToVal.size() != JoinedEnv.LocToVal.size())
620     Effect = LatticeJoinEffect::Changed;
621 
622   *this = std::move(JoinedEnv);
623 
624   return Effect;
625 }
626 
627 StorageLocation &Environment::createStorageLocation(QualType Type) {
628   return DACtx->createStorageLocation(Type);
629 }
630 
631 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
632   // Evaluated declarations are always assigned the same storage locations to
633   // ensure that the environment stabilizes across loop iterations. Storage
634   // locations for evaluated declarations are stored in the analysis context.
635   return DACtx->getStableStorageLocation(D);
636 }
637 
638 StorageLocation &Environment::createStorageLocation(const Expr &E) {
639   // Evaluated expressions are always assigned the same storage locations to
640   // ensure that the environment stabilizes across loop iterations. Storage
641   // locations for evaluated expressions are stored in the analysis context.
642   return DACtx->getStableStorageLocation(E);
643 }
644 
645 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
646   assert(!DeclToLoc.contains(&D));
647   assert(!isa_and_nonnull<ReferenceValue>(getValue(Loc)));
648   DeclToLoc[&D] = &Loc;
649 }
650 
651 StorageLocation *Environment::getStorageLocation(const ValueDecl &D) const {
652   auto It = DeclToLoc.find(&D);
653   if (It == DeclToLoc.end())
654     return nullptr;
655 
656   StorageLocation *Loc = It->second;
657 
658   assert(!isa_and_nonnull<ReferenceValue>(getValue(*Loc)));
659 
660   return Loc;
661 }
662 
663 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
664   const Expr &CanonE = ignoreCFGOmittedNodes(E);
665   assert(!ExprToLoc.contains(&CanonE));
666   ExprToLoc[&CanonE] = &Loc;
667 }
668 
669 void Environment::setStorageLocationStrict(const Expr &E,
670                                            StorageLocation &Loc) {
671   // `DeclRefExpr`s to builtin function types aren't glvalues, for some reason,
672   // but we still want to be able to associate a `StorageLocation` with them,
673   // so allow these as an exception.
674   assert(E.isGLValue() ||
675          E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
676   setStorageLocation(E, Loc);
677 }
678 
679 StorageLocation *Environment::getStorageLocation(const Expr &E,
680                                                  SkipPast SP) const {
681   // FIXME: Add a test with parens.
682   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
683   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
684 }
685 
686 StorageLocation *Environment::getStorageLocationStrict(const Expr &E) const {
687   // See comment in `setStorageLocationStrict()`.
688   assert(E.isGLValue() ||
689          E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
690   StorageLocation *Loc = getStorageLocation(E, SkipPast::None);
691 
692   if (Loc == nullptr)
693     return nullptr;
694 
695   if (auto *RefVal = dyn_cast_or_null<ReferenceValue>(getValue(*Loc)))
696     return &RefVal->getReferentLoc();
697 
698   return Loc;
699 }
700 
701 StorageLocation *Environment::getThisPointeeStorageLocation() const {
702   return ThisPointeeLoc;
703 }
704 
705 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
706   return DACtx->getOrCreateNullPointerValue(PointeeType);
707 }
708 
709 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
710   LocToVal[&Loc] = &Val;
711 
712   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
713     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
714 
715     const QualType Type = AggregateLoc.getType();
716     assert(Type->isRecordType());
717 
718     for (const FieldDecl *Field : DACtx->getReferencedFields(Type)) {
719       assert(Field != nullptr);
720       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
721       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
722       if (auto *FieldVal = StructVal->getChild(*Field))
723         setValue(FieldLoc, *FieldVal);
724     }
725   }
726 
727   auto It = MemberLocToStruct.find(&Loc);
728   if (It != MemberLocToStruct.end()) {
729     // `Loc` is the location of a struct member so we need to also update the
730     // value of the member in the corresponding `StructValue`.
731 
732     assert(It->second.first != nullptr);
733     StructValue &StructVal = *It->second.first;
734 
735     assert(It->second.second != nullptr);
736     const ValueDecl &Member = *It->second.second;
737 
738     StructVal.setChild(Member, Val);
739   }
740 }
741 
742 void Environment::clearValue(const StorageLocation &Loc) {
743   LocToVal.erase(&Loc);
744 
745   if (auto It = MemberLocToStruct.find(&Loc); It != MemberLocToStruct.end()) {
746     // `Loc` is the location of a struct member so we need to also clear the
747     // member in the corresponding `StructValue`.
748 
749     assert(It->second.first != nullptr);
750     StructValue &StructVal = *It->second.first;
751 
752     assert(It->second.second != nullptr);
753     const ValueDecl &Member = *It->second.second;
754 
755     StructVal.clearChild(Member);
756   }
757 }
758 
759 void Environment::setValueStrict(const Expr &E, Value &Val) {
760   assert(E.isPRValue());
761   assert(!isa<ReferenceValue>(Val));
762 
763   StorageLocation *Loc = getStorageLocation(E, SkipPast::None);
764   if (Loc == nullptr) {
765     Loc = &createStorageLocation(E);
766     setStorageLocation(E, *Loc);
767   }
768   setValue(*Loc, Val);
769 }
770 
771 Value *Environment::getValue(const StorageLocation &Loc) const {
772   return LocToVal.lookup(&Loc);
773 }
774 
775 Value *Environment::getValue(const ValueDecl &D) const {
776   auto *Loc = getStorageLocation(D);
777   if (Loc == nullptr)
778     return nullptr;
779   return getValue(*Loc);
780 }
781 
782 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
783   auto *Loc = getStorageLocation(E, SP);
784   if (Loc == nullptr)
785     return nullptr;
786   return getValue(*Loc);
787 }
788 
789 Value *Environment::getValueStrict(const Expr &E) const {
790   assert(E.isPRValue());
791   Value *Val = getValue(E, SkipPast::None);
792 
793   assert(Val == nullptr || !isa<ReferenceValue>(Val));
794 
795   return Val;
796 }
797 
798 Value *Environment::createValue(QualType Type) {
799   llvm::DenseSet<QualType> Visited;
800   int CreatedValuesCount = 0;
801   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
802                                                 CreatedValuesCount);
803   if (CreatedValuesCount > MaxCompositeValueSize) {
804     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
805                  << '\n';
806   }
807   return Val;
808 }
809 
810 Value *Environment::createValueUnlessSelfReferential(
811     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
812     int &CreatedValuesCount) {
813   assert(!Type.isNull());
814 
815   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
816   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
817       Depth > MaxCompositeValueDepth)
818     return nullptr;
819 
820   if (Type->isBooleanType()) {
821     CreatedValuesCount++;
822     return &makeAtomicBoolValue();
823   }
824 
825   if (Type->isIntegerType()) {
826     // FIXME: consider instead `return nullptr`, given that we do nothing useful
827     // with integers, and so distinguishing them serves no purpose, but could
828     // prevent convergence.
829     CreatedValuesCount++;
830     return &DACtx->arena().create<IntegerValue>();
831   }
832 
833   if (Type->isReferenceType() || Type->isPointerType()) {
834     CreatedValuesCount++;
835     QualType PointeeType = Type->getPointeeType();
836     auto &PointeeLoc = createStorageLocation(PointeeType);
837 
838     if (Visited.insert(PointeeType.getCanonicalType()).second) {
839       Value *PointeeVal = createValueUnlessSelfReferential(
840           PointeeType, Visited, Depth, CreatedValuesCount);
841       Visited.erase(PointeeType.getCanonicalType());
842 
843       if (PointeeVal != nullptr)
844         setValue(PointeeLoc, *PointeeVal);
845     }
846 
847     if (Type->isReferenceType())
848       return &DACtx->arena().create<ReferenceValue>(PointeeLoc);
849     else
850       return &DACtx->arena().create<PointerValue>(PointeeLoc);
851   }
852 
853   if (Type->isRecordType()) {
854     CreatedValuesCount++;
855     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
856     for (const FieldDecl *Field : DACtx->getReferencedFields(Type)) {
857       assert(Field != nullptr);
858 
859       QualType FieldType = Field->getType();
860       if (Visited.contains(FieldType.getCanonicalType()))
861         continue;
862 
863       Visited.insert(FieldType.getCanonicalType());
864       if (auto *FieldValue = createValueUnlessSelfReferential(
865               FieldType, Visited, Depth + 1, CreatedValuesCount))
866         FieldValues.insert({Field, FieldValue});
867       Visited.erase(FieldType.getCanonicalType());
868     }
869 
870     return &DACtx->arena().create<StructValue>(std::move(FieldValues));
871   }
872 
873   return nullptr;
874 }
875 
876 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
877   switch (SP) {
878   case SkipPast::None:
879     return Loc;
880   case SkipPast::Reference:
881     // References cannot be chained so we only need to skip past one level of
882     // indirection.
883     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
884       return Val->getReferentLoc();
885     return Loc;
886   }
887   llvm_unreachable("bad SkipPast kind");
888 }
889 
890 const StorageLocation &Environment::skip(const StorageLocation &Loc,
891                                          SkipPast SP) const {
892   return skip(*const_cast<StorageLocation *>(&Loc), SP);
893 }
894 
895 void Environment::addToFlowCondition(BoolValue &Val) {
896   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
897 }
898 
899 bool Environment::flowConditionImplies(BoolValue &Val) const {
900   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
901 }
902 
903 void Environment::dump(raw_ostream &OS) const {
904   // FIXME: add printing for remaining fields and allow caller to decide what
905   // fields are printed.
906   OS << "DeclToLoc:\n";
907   for (auto [D, L] : DeclToLoc)
908     OS << "  [" << D->getNameAsString() << ", " << L << "]\n";
909 
910   OS << "ExprToLoc:\n";
911   for (auto [E, L] : ExprToLoc)
912     OS << "  [" << E << ", " << L << "]\n";
913 
914   OS << "LocToVal:\n";
915   for (auto [L, V] : LocToVal) {
916     OS << "  [" << L << ", " << V << ": " << *V << "]\n";
917   }
918 
919   OS << "FlowConditionToken:\n";
920   DACtx->dumpFlowCondition(*FlowConditionToken, OS);
921 }
922 
923 void Environment::dump() const {
924   dump(llvm::dbgs());
925 }
926 
927 AggregateStorageLocation *
928 getImplicitObjectLocation(const CXXMemberCallExpr &MCE,
929                           const Environment &Env) {
930   Expr *ImplicitObject = MCE.getImplicitObjectArgument();
931   if (ImplicitObject == nullptr)
932     return nullptr;
933   StorageLocation *Loc =
934       Env.getStorageLocation(*ImplicitObject, SkipPast::Reference);
935   if (Loc == nullptr)
936     return nullptr;
937   if (ImplicitObject->getType()->isPointerType()) {
938     if (auto *Val = cast_or_null<PointerValue>(Env.getValue(*Loc)))
939       return &cast<AggregateStorageLocation>(Val->getPointeeLoc());
940     return nullptr;
941   }
942   return cast<AggregateStorageLocation>(Loc);
943 }
944 
945 AggregateStorageLocation *getBaseObjectLocation(const MemberExpr &ME,
946                                                 const Environment &Env) {
947   Expr *Base = ME.getBase();
948   if (Base == nullptr)
949     return nullptr;
950   StorageLocation *Loc = Env.getStorageLocation(*Base, SkipPast::Reference);
951   if (Loc == nullptr)
952     return nullptr;
953   if (ME.isArrow()) {
954     if (auto *Val = cast_or_null<PointerValue>(Env.getValue(*Loc)))
955       return &cast<AggregateStorageLocation>(Val->getPointeeLoc());
956     return nullptr;
957   }
958   return cast<AggregateStorageLocation>(Loc);
959 }
960 
961 } // namespace dataflow
962 } // namespace clang
963