xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision 991c7e11728f6f6372e5dc865e3a4c0636a575ea)
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 getFieldsAndGlobalVars(const Decl &D,
166                                    llvm::DenseSet<const FieldDecl *> &Fields,
167                                    llvm::DenseSet<const VarDecl *> &Vars) {
168   insertIfGlobal(D, Vars);
169   if (const auto *Decomp = dyn_cast<DecompositionDecl>(&D))
170     for (const auto *B : Decomp->bindings())
171       if (auto *ME = dyn_cast_or_null<MemberExpr>(B->getBinding()))
172         // FIXME: should we be using `E->getFoundDecl()`?
173         if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
174           Fields.insert(FD);
175 }
176 
177 /// Traverses `S` and inserts into `Vars` any global storage values that are
178 /// declared in or referenced from sub-statements.
179 static void getFieldsAndGlobalVars(const Stmt &S,
180                                    llvm::DenseSet<const FieldDecl *> &Fields,
181                                    llvm::DenseSet<const VarDecl *> &Vars) {
182   for (auto *Child : S.children())
183     if (Child != nullptr)
184       getFieldsAndGlobalVars(*Child, Fields, Vars);
185 
186   if (auto *DS = dyn_cast<DeclStmt>(&S)) {
187     if (DS->isSingleDecl())
188       getFieldsAndGlobalVars(*DS->getSingleDecl(), Fields, Vars);
189     else
190       for (auto *D : DS->getDeclGroup())
191           getFieldsAndGlobalVars(*D, Fields, Vars);
192   } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) {
193     insertIfGlobal(*E->getDecl(), Vars);
194   } else if (auto *E = dyn_cast<MemberExpr>(&S)) {
195     // FIXME: should we be using `E->getFoundDecl()`?
196     const ValueDecl *VD = E->getMemberDecl();
197     insertIfGlobal(*VD, Vars);
198     if (const auto *FD = dyn_cast<FieldDecl>(VD))
199       Fields.insert(FD);
200   }
201 }
202 
203 // FIXME: Add support for resetting globals after function calls to enable
204 // the implementation of sound analyses.
205 void Environment::initFieldsAndGlobals(const FunctionDecl *FuncDecl) {
206   assert(FuncDecl->getBody() != nullptr);
207 
208   llvm::DenseSet<const FieldDecl *> Fields;
209   llvm::DenseSet<const VarDecl *> Vars;
210 
211   // Look for global variable and field references in the
212   // constructor-initializers.
213   if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(FuncDecl)) {
214     for (const auto *Init : CtorDecl->inits()) {
215       if (const auto *M = Init->getAnyMember())
216           Fields.insert(M);
217       const Expr *E = Init->getInit();
218       assert(E != nullptr);
219       getFieldsAndGlobalVars(*E, Fields, Vars);
220     }
221     // Add all fields mentioned in default member initializers.
222     for (const FieldDecl *F : CtorDecl->getParent()->fields())
223       if (const auto *I = F->getInClassInitializer())
224           getFieldsAndGlobalVars(*I, Fields, Vars);
225   }
226   getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
227 
228   // These have to be added before the lines that follow to ensure that
229   // `create*` work correctly for structs.
230   DACtx->addModeledFields(Fields);
231 
232   for (const VarDecl *D : Vars) {
233     if (getStorageLocation(*D, SkipPast::None) != nullptr)
234       continue;
235     auto &Loc = createStorageLocation(*D);
236     setStorageLocation(*D, Loc);
237     if (auto *Val = createValue(D->getType()))
238       setValue(Loc, *Val);
239   }
240 }
241 
242 Environment::Environment(DataflowAnalysisContext &DACtx)
243     : DACtx(&DACtx), FlowConditionToken(&DACtx.makeFlowConditionToken()) {}
244 
245 Environment::Environment(const Environment &Other)
246     : DACtx(Other.DACtx), CallStack(Other.CallStack),
247       ReturnLoc(Other.ReturnLoc), ThisPointeeLoc(Other.ThisPointeeLoc),
248       DeclToLoc(Other.DeclToLoc), ExprToLoc(Other.ExprToLoc),
249       LocToVal(Other.LocToVal), MemberLocToStruct(Other.MemberLocToStruct),
250       FlowConditionToken(&DACtx->forkFlowCondition(*Other.FlowConditionToken)) {
251 }
252 
253 Environment &Environment::operator=(const Environment &Other) {
254   Environment Copy(Other);
255   *this = std::move(Copy);
256   return *this;
257 }
258 
259 Environment::Environment(DataflowAnalysisContext &DACtx,
260                          const DeclContext &DeclCtx)
261     : Environment(DACtx) {
262   CallStack.push_back(&DeclCtx);
263 
264   if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) {
265     assert(FuncDecl->getBody() != nullptr);
266 
267     initFieldsAndGlobals(FuncDecl);
268 
269     for (const auto *ParamDecl : FuncDecl->parameters()) {
270       assert(ParamDecl != nullptr);
271       auto &ParamLoc = createStorageLocation(*ParamDecl);
272       setStorageLocation(*ParamDecl, ParamLoc);
273       if (Value *ParamVal = createValue(ParamDecl->getType()))
274         setValue(ParamLoc, *ParamVal);
275     }
276 
277     QualType ReturnType = FuncDecl->getReturnType();
278     ReturnLoc = &createStorageLocation(ReturnType);
279   }
280 
281   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) {
282     auto *Parent = MethodDecl->getParent();
283     assert(Parent != nullptr);
284     if (Parent->isLambda())
285       MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext());
286 
287     // FIXME: Initialize the ThisPointeeLoc of lambdas too.
288     if (MethodDecl && !MethodDecl->isStatic()) {
289       QualType ThisPointeeType = MethodDecl->getThisObjectType();
290       ThisPointeeLoc = &createStorageLocation(ThisPointeeType);
291       if (Value *ThisPointeeVal = createValue(ThisPointeeType))
292         setValue(*ThisPointeeLoc, *ThisPointeeVal);
293     }
294   }
295 }
296 
297 bool Environment::canDescend(unsigned MaxDepth,
298                              const DeclContext *Callee) const {
299   return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee);
300 }
301 
302 Environment Environment::pushCall(const CallExpr *Call) const {
303   Environment Env(*this);
304 
305   // FIXME: Support references here.
306   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
307 
308   if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
309     if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
310       if (!isa<CXXThisExpr>(Arg))
311         Env.ThisPointeeLoc = getStorageLocation(*Arg, SkipPast::Reference);
312       // Otherwise (when the argument is `this`), retain the current
313       // environment's `ThisPointeeLoc`.
314     }
315   }
316 
317   Env.pushCallInternal(Call->getDirectCallee(),
318                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
319 
320   return Env;
321 }
322 
323 Environment Environment::pushCall(const CXXConstructExpr *Call) const {
324   Environment Env(*this);
325 
326   // FIXME: Support references here.
327   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
328 
329   Env.ThisPointeeLoc = Env.ReturnLoc;
330 
331   Env.pushCallInternal(Call->getConstructor(),
332                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
333 
334   return Env;
335 }
336 
337 void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
338                                    ArrayRef<const Expr *> Args) {
339   CallStack.push_back(FuncDecl);
340 
341   initFieldsAndGlobals(FuncDecl);
342 
343   const auto *ParamIt = FuncDecl->param_begin();
344 
345   // FIXME: Parameters don't always map to arguments 1:1; examples include
346   // overloaded operators implemented as member functions, and parameter packs.
347   for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
348     assert(ParamIt != FuncDecl->param_end());
349 
350     const Expr *Arg = Args[ArgIndex];
351     auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
352     if (ArgLoc == nullptr)
353       continue;
354 
355     const VarDecl *Param = *ParamIt;
356     auto &Loc = createStorageLocation(*Param);
357     setStorageLocation(*Param, Loc);
358 
359     QualType ParamType = Param->getType();
360     if (ParamType->isReferenceType()) {
361       auto &Val = create<ReferenceValue>(*ArgLoc);
362       setValue(Loc, Val);
363     } else if (auto *ArgVal = getValue(*ArgLoc)) {
364       setValue(Loc, *ArgVal);
365     } else if (Value *Val = createValue(ParamType)) {
366       setValue(Loc, *Val);
367     }
368   }
369 }
370 
371 void Environment::popCall(const Environment &CalleeEnv) {
372   // We ignore `DACtx` because it's already the same in both. We don't want the
373   // callee's `DeclCtx`, `ReturnLoc` or `ThisPointeeLoc`. We don't bring back
374   // `DeclToLoc` and `ExprToLoc` because we want to be able to later analyze the
375   // same callee in a different context, and `setStorageLocation` requires there
376   // to not already be a storage location assigned. Conceptually, these maps
377   // capture information from the local scope, so when popping that scope, we do
378   // not propagate the maps.
379   this->LocToVal = std::move(CalleeEnv.LocToVal);
380   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
381   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
382 }
383 
384 bool Environment::equivalentTo(const Environment &Other,
385                                Environment::ValueModel &Model) const {
386   assert(DACtx == Other.DACtx);
387 
388   if (ReturnLoc != Other.ReturnLoc)
389     return false;
390 
391   if (ThisPointeeLoc != Other.ThisPointeeLoc)
392     return false;
393 
394   if (DeclToLoc != Other.DeclToLoc)
395     return false;
396 
397   if (ExprToLoc != Other.ExprToLoc)
398     return false;
399 
400   // Compare the contents for the intersection of their domains.
401   for (auto &Entry : LocToVal) {
402     const StorageLocation *Loc = Entry.first;
403     assert(Loc != nullptr);
404 
405     Value *Val = Entry.second;
406     assert(Val != nullptr);
407 
408     auto It = Other.LocToVal.find(Loc);
409     if (It == Other.LocToVal.end())
410       continue;
411     assert(It->second != nullptr);
412 
413     if (!areEquivalentValues(*Val, *It->second) &&
414         !compareDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
415                                Model))
416       return false;
417   }
418 
419   return true;
420 }
421 
422 LatticeJoinEffect Environment::widen(const Environment &PrevEnv,
423                                      Environment::ValueModel &Model) {
424   assert(DACtx == PrevEnv.DACtx);
425   assert(ReturnLoc == PrevEnv.ReturnLoc);
426   assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc);
427   assert(CallStack == PrevEnv.CallStack);
428 
429   auto Effect = LatticeJoinEffect::Unchanged;
430 
431   // By the API, `PrevEnv` is a previous version of the environment for the same
432   // block, so we have some guarantees about its shape. In particular, it will
433   // be the result of a join or widen operation on previous values for this
434   // block. For `DeclToLoc` and `ExprToLoc`, join guarantees that these maps are
435   // subsets of the maps in `PrevEnv`. So, as long as we maintain this property
436   // here, we don't need change their current values to widen.
437   //
438   // FIXME: `MemberLocToStruct` does not share the above property, because
439   // `join` can cause the map size to increase (when we add fresh data in places
440   // of conflict). Once this issue with join is resolved, re-enable the
441   // assertion below or replace with something that captures the desired
442   // invariant.
443   assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
444   assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
445   // assert(MemberLocToStruct.size() <= PrevEnv.MemberLocToStruct.size());
446 
447   llvm::DenseMap<const StorageLocation *, Value *> WidenedLocToVal;
448   for (auto &Entry : LocToVal) {
449     const StorageLocation *Loc = Entry.first;
450     assert(Loc != nullptr);
451 
452     Value *Val = Entry.second;
453     assert(Val != nullptr);
454 
455     auto PrevIt = PrevEnv.LocToVal.find(Loc);
456     if (PrevIt == PrevEnv.LocToVal.end())
457       continue;
458     assert(PrevIt->second != nullptr);
459 
460     if (areEquivalentValues(*Val, *PrevIt->second)) {
461       WidenedLocToVal.insert({Loc, Val});
462       continue;
463     }
464 
465     Value &WidenedVal = widenDistinctValues(Loc->getType(), *PrevIt->second,
466                                             PrevEnv, *Val, *this, Model);
467     WidenedLocToVal.insert({Loc, &WidenedVal});
468     if (&WidenedVal != PrevIt->second)
469       Effect = LatticeJoinEffect::Changed;
470   }
471   LocToVal = std::move(WidenedLocToVal);
472   // FIXME: update the equivalence calculation for `MemberLocToStruct`, once we
473   // have a systematic way of soundly comparing this map.
474   if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
475       ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
476       LocToVal.size() != PrevEnv.LocToVal.size() ||
477       MemberLocToStruct.size() != PrevEnv.MemberLocToStruct.size())
478     Effect = LatticeJoinEffect::Changed;
479 
480   return Effect;
481 }
482 
483 LatticeJoinEffect Environment::join(const Environment &Other,
484                                     Environment::ValueModel &Model) {
485   assert(DACtx == Other.DACtx);
486   assert(ReturnLoc == Other.ReturnLoc);
487   assert(ThisPointeeLoc == Other.ThisPointeeLoc);
488   assert(CallStack == Other.CallStack);
489 
490   auto Effect = LatticeJoinEffect::Unchanged;
491 
492   Environment JoinedEnv(*DACtx);
493 
494   JoinedEnv.CallStack = CallStack;
495   JoinedEnv.ReturnLoc = ReturnLoc;
496   JoinedEnv.ThisPointeeLoc = ThisPointeeLoc;
497 
498   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
499   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
500     Effect = LatticeJoinEffect::Changed;
501 
502   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
503   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
504     Effect = LatticeJoinEffect::Changed;
505 
506   JoinedEnv.MemberLocToStruct =
507       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
508   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
509     Effect = LatticeJoinEffect::Changed;
510 
511   // FIXME: set `Effect` as needed.
512   // FIXME: update join to detect backedges and simplify the flow condition
513   // accordingly.
514   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
515       *FlowConditionToken, *Other.FlowConditionToken);
516 
517   for (auto &Entry : LocToVal) {
518     const StorageLocation *Loc = Entry.first;
519     assert(Loc != nullptr);
520 
521     Value *Val = Entry.second;
522     assert(Val != nullptr);
523 
524     auto It = Other.LocToVal.find(Loc);
525     if (It == Other.LocToVal.end())
526       continue;
527     assert(It->second != nullptr);
528 
529     if (areEquivalentValues(*Val, *It->second)) {
530       JoinedEnv.LocToVal.insert({Loc, Val});
531       continue;
532     }
533 
534     if (Value *MergedVal =
535             mergeDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
536                                 JoinedEnv, Model)) {
537       JoinedEnv.LocToVal.insert({Loc, MergedVal});
538       Effect = LatticeJoinEffect::Changed;
539     }
540   }
541   if (LocToVal.size() != JoinedEnv.LocToVal.size())
542     Effect = LatticeJoinEffect::Changed;
543 
544   *this = std::move(JoinedEnv);
545 
546   return Effect;
547 }
548 
549 StorageLocation &Environment::createStorageLocation(QualType Type) {
550   return DACtx->createStorageLocation(Type);
551 }
552 
553 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
554   // Evaluated declarations are always assigned the same storage locations to
555   // ensure that the environment stabilizes across loop iterations. Storage
556   // locations for evaluated declarations are stored in the analysis context.
557   return DACtx->getStableStorageLocation(D);
558 }
559 
560 StorageLocation &Environment::createStorageLocation(const Expr &E) {
561   // Evaluated expressions are always assigned the same storage locations to
562   // ensure that the environment stabilizes across loop iterations. Storage
563   // locations for evaluated expressions are stored in the analysis context.
564   return DACtx->getStableStorageLocation(E);
565 }
566 
567 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
568   assert(!DeclToLoc.contains(&D));
569   DeclToLoc[&D] = &Loc;
570 }
571 
572 StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
573                                                  SkipPast SP) const {
574   auto It = DeclToLoc.find(&D);
575   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
576 }
577 
578 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
579   const Expr &CanonE = ignoreCFGOmittedNodes(E);
580   assert(!ExprToLoc.contains(&CanonE));
581   ExprToLoc[&CanonE] = &Loc;
582 }
583 
584 StorageLocation *Environment::getStorageLocation(const Expr &E,
585                                                  SkipPast SP) const {
586   // FIXME: Add a test with parens.
587   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
588   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
589 }
590 
591 StorageLocation *Environment::getThisPointeeStorageLocation() const {
592   return ThisPointeeLoc;
593 }
594 
595 StorageLocation *Environment::getReturnStorageLocation() const {
596   return ReturnLoc;
597 }
598 
599 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
600   return DACtx->getOrCreateNullPointerValue(PointeeType);
601 }
602 
603 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
604   LocToVal[&Loc] = &Val;
605 
606   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
607     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
608 
609     const QualType Type = AggregateLoc.getType();
610     assert(Type->isRecordType());
611 
612     for (const FieldDecl *Field : DACtx->getReferencedFields(Type)) {
613       assert(Field != nullptr);
614       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
615       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
616       if (auto *FieldVal = StructVal->getChild(*Field))
617         setValue(FieldLoc, *FieldVal);
618     }
619   }
620 
621   auto It = MemberLocToStruct.find(&Loc);
622   if (It != MemberLocToStruct.end()) {
623     // `Loc` is the location of a struct member so we need to also update the
624     // value of the member in the corresponding `StructValue`.
625 
626     assert(It->second.first != nullptr);
627     StructValue &StructVal = *It->second.first;
628 
629     assert(It->second.second != nullptr);
630     const ValueDecl &Member = *It->second.second;
631 
632     StructVal.setChild(Member, Val);
633   }
634 }
635 
636 Value *Environment::getValue(const StorageLocation &Loc) const {
637   auto It = LocToVal.find(&Loc);
638   return It == LocToVal.end() ? nullptr : It->second;
639 }
640 
641 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
642   auto *Loc = getStorageLocation(D, SP);
643   if (Loc == nullptr)
644     return nullptr;
645   return getValue(*Loc);
646 }
647 
648 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
649   auto *Loc = getStorageLocation(E, SP);
650   if (Loc == nullptr)
651     return nullptr;
652   return getValue(*Loc);
653 }
654 
655 Value *Environment::createValue(QualType Type) {
656   llvm::DenseSet<QualType> Visited;
657   int CreatedValuesCount = 0;
658   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
659                                                 CreatedValuesCount);
660   if (CreatedValuesCount > MaxCompositeValueSize) {
661     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
662                  << '\n';
663   }
664   return Val;
665 }
666 
667 Value *Environment::createValueUnlessSelfReferential(
668     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
669     int &CreatedValuesCount) {
670   assert(!Type.isNull());
671 
672   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
673   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
674       Depth > MaxCompositeValueDepth)
675     return nullptr;
676 
677   if (Type->isBooleanType()) {
678     CreatedValuesCount++;
679     return &makeAtomicBoolValue();
680   }
681 
682   if (Type->isIntegerType()) {
683     // FIXME: consider instead `return nullptr`, given that we do nothing useful
684     // with integers, and so distinguishing them serves no purpose, but could
685     // prevent convergence.
686     CreatedValuesCount++;
687     return &create<IntegerValue>();
688   }
689 
690   if (Type->isReferenceType() || Type->isPointerType()) {
691     CreatedValuesCount++;
692     QualType PointeeType = Type->getPointeeType();
693     auto &PointeeLoc = createStorageLocation(PointeeType);
694 
695     if (Visited.insert(PointeeType.getCanonicalType()).second) {
696       Value *PointeeVal = createValueUnlessSelfReferential(
697           PointeeType, Visited, Depth, CreatedValuesCount);
698       Visited.erase(PointeeType.getCanonicalType());
699 
700       if (PointeeVal != nullptr)
701         setValue(PointeeLoc, *PointeeVal);
702     }
703 
704     if (Type->isReferenceType())
705       return &create<ReferenceValue>(PointeeLoc);
706     else
707       return &create<PointerValue>(PointeeLoc);
708   }
709 
710   if (Type->isRecordType()) {
711     CreatedValuesCount++;
712     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
713     for (const FieldDecl *Field : DACtx->getReferencedFields(Type)) {
714       assert(Field != nullptr);
715 
716       QualType FieldType = Field->getType();
717       if (Visited.contains(FieldType.getCanonicalType()))
718         continue;
719 
720       Visited.insert(FieldType.getCanonicalType());
721       if (auto *FieldValue = createValueUnlessSelfReferential(
722               FieldType, Visited, Depth + 1, CreatedValuesCount))
723         FieldValues.insert({Field, FieldValue});
724       Visited.erase(FieldType.getCanonicalType());
725     }
726 
727     return &create<StructValue>(std::move(FieldValues));
728   }
729 
730   return nullptr;
731 }
732 
733 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
734   switch (SP) {
735   case SkipPast::None:
736     return Loc;
737   case SkipPast::Reference:
738     // References cannot be chained so we only need to skip past one level of
739     // indirection.
740     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
741       return Val->getReferentLoc();
742     return Loc;
743   case SkipPast::ReferenceThenPointer:
744     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
745     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
746       return Val->getPointeeLoc();
747     return LocPastRef;
748   }
749   llvm_unreachable("bad SkipPast kind");
750 }
751 
752 const StorageLocation &Environment::skip(const StorageLocation &Loc,
753                                          SkipPast SP) const {
754   return skip(*const_cast<StorageLocation *>(&Loc), SP);
755 }
756 
757 void Environment::addToFlowCondition(BoolValue &Val) {
758   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
759 }
760 
761 bool Environment::flowConditionImplies(BoolValue &Val) const {
762   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
763 }
764 
765 void Environment::dump(raw_ostream &OS) const {
766   // FIXME: add printing for remaining fields and allow caller to decide what
767   // fields are printed.
768   OS << "DeclToLoc:\n";
769   for (auto [D, L] : DeclToLoc)
770     OS << "  [" << D->getName() << ", " << L << "]\n";
771 
772   OS << "ExprToLoc:\n";
773   for (auto [E, L] : ExprToLoc)
774     OS << "  [" << E << ", " << L << "]\n";
775 
776   OS << "LocToVal:\n";
777   for (auto [L, V] : LocToVal) {
778     OS << "  [" << L << ", " << V << ": " << *V << "]\n";
779   }
780 
781   OS << "FlowConditionToken:\n";
782   DACtx->dumpFlowCondition(*FlowConditionToken, OS);
783 }
784 
785 void Environment::dump() const {
786   dump(llvm::dbgs());
787 }
788 
789 } // namespace dataflow
790 } // namespace clang
791