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