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