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