xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision d09d4bd66c864d58b29d74918a4a164f3ad905de)
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/Support/Casting.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include <cassert>
26 #include <memory>
27 #include <utility>
28 
29 namespace clang {
30 namespace dataflow {
31 
32 // FIXME: convert these to parameters of the analysis or environment. Current
33 // settings have been experimentaly validated, but only for a particular
34 // analysis.
35 static constexpr int MaxCompositeValueDepth = 3;
36 static constexpr int MaxCompositeValueSize = 1000;
37 
38 /// Returns a map consisting of key-value entries that are present in both maps.
39 template <typename K, typename V>
40 llvm::DenseMap<K, V> intersectDenseMaps(const llvm::DenseMap<K, V> &Map1,
41                                         const llvm::DenseMap<K, V> &Map2) {
42   llvm::DenseMap<K, V> Result;
43   for (auto &Entry : Map1) {
44     auto It = Map2.find(Entry.first);
45     if (It != Map2.end() && Entry.second == It->second)
46       Result.insert({Entry.first, Entry.second});
47   }
48   return Result;
49 }
50 
51 static bool areEquivalentIndirectionValues(Value *Val1, Value *Val2) {
52   if (auto *IndVal1 = dyn_cast<ReferenceValue>(Val1)) {
53     auto *IndVal2 = cast<ReferenceValue>(Val2);
54     return &IndVal1->getReferentLoc() == &IndVal2->getReferentLoc();
55   }
56   if (auto *IndVal1 = dyn_cast<PointerValue>(Val1)) {
57     auto *IndVal2 = cast<PointerValue>(Val2);
58     return &IndVal1->getPointeeLoc() == &IndVal2->getPointeeLoc();
59   }
60   return false;
61 }
62 
63 /// Returns true if and only if `Val1` is equivalent to `Val2`.
64 static bool equivalentValues(QualType Type, Value *Val1,
65                              const Environment &Env1, Value *Val2,
66                              const Environment &Env2,
67                              Environment::ValueModel &Model) {
68   return Val1 == Val2 || areEquivalentIndirectionValues(Val1, Val2) ||
69          Model.compareEquivalent(Type, *Val1, Env1, *Val2, Env2);
70 }
71 
72 /// Attempts to merge distinct values `Val1` and `Val2` in `Env1` and `Env2`,
73 /// respectively, of the same type `Type`. Merging generally produces a single
74 /// value that (soundly) approximates the two inputs, although the actual
75 /// meaning depends on `Model`.
76 static Value *mergeDistinctValues(QualType Type, Value *Val1,
77                                   const Environment &Env1, Value *Val2,
78                                   const Environment &Env2,
79                                   Environment &MergedEnv,
80                                   Environment::ValueModel &Model) {
81   // Join distinct boolean values preserving information about the constraints
82   // in the respective path conditions.
83   //
84   // FIXME: Does not work for backedges, since the two (or more) paths will not
85   // have mutually exclusive conditions.
86   if (auto *Expr1 = dyn_cast<BoolValue>(Val1)) {
87     auto *Expr2 = cast<BoolValue>(Val2);
88     auto &MergedVal = MergedEnv.makeAtomicBoolValue();
89     MergedEnv.addToFlowCondition(MergedEnv.makeOr(
90         MergedEnv.makeAnd(Env1.getFlowConditionToken(),
91                           MergedEnv.makeIff(MergedVal, *Expr1)),
92         MergedEnv.makeAnd(Env2.getFlowConditionToken(),
93                           MergedEnv.makeIff(MergedVal, *Expr2))));
94     return &MergedVal;
95   }
96 
97   // FIXME: add unit tests that cover this statement.
98   if (areEquivalentIndirectionValues(Val1, Val2)) {
99     return Val1;
100   }
101 
102   // FIXME: Consider destroying `MergedValue` immediately if `ValueModel::merge`
103   // returns false to avoid storing unneeded values in `DACtx`.
104   if (Value *MergedVal = MergedEnv.createValue(Type))
105     if (Model.merge(Type, *Val1, Env1, *Val2, Env2, *MergedVal, MergedEnv))
106       return MergedVal;
107 
108   return nullptr;
109 }
110 
111 /// Initializes a global storage value.
112 static void initGlobalVar(const VarDecl &D, Environment &Env) {
113   if (!D.hasGlobalStorage() ||
114       Env.getStorageLocation(D, SkipPast::None) != nullptr)
115     return;
116 
117   auto &Loc = Env.createStorageLocation(D);
118   Env.setStorageLocation(D, Loc);
119   if (auto *Val = Env.createValue(D.getType()))
120     Env.setValue(Loc, *Val);
121 }
122 
123 /// Initializes a global storage value.
124 static void initGlobalVar(const Decl &D, Environment &Env) {
125   if (auto *V = dyn_cast<VarDecl>(&D))
126     initGlobalVar(*V, Env);
127 }
128 
129 /// Initializes global storage values that are declared or referenced from
130 /// sub-statements of `S`.
131 // FIXME: Add support for resetting globals after function calls to enable
132 // the implementation of sound analyses.
133 static void initGlobalVars(const Stmt &S, Environment &Env) {
134   for (auto *Child : S.children()) {
135     if (Child != nullptr)
136       initGlobalVars(*Child, Env);
137   }
138 
139   if (auto *DS = dyn_cast<DeclStmt>(&S)) {
140     if (DS->isSingleDecl()) {
141       initGlobalVar(*DS->getSingleDecl(), Env);
142     } else {
143       for (auto *D : DS->getDeclGroup())
144         initGlobalVar(*D, Env);
145     }
146   } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) {
147     initGlobalVar(*E->getDecl(), Env);
148   } else if (auto *E = dyn_cast<MemberExpr>(&S)) {
149     initGlobalVar(*E->getMemberDecl(), Env);
150   }
151 }
152 
153 Environment::Environment(DataflowAnalysisContext &DACtx)
154     : DACtx(&DACtx), FlowConditionToken(&DACtx.makeFlowConditionToken()) {}
155 
156 Environment::Environment(const Environment &Other)
157     : DACtx(Other.DACtx), DeclCtx(Other.DeclCtx), ReturnLoc(Other.ReturnLoc),
158       ThisPointeeLoc(Other.ThisPointeeLoc), DeclToLoc(Other.DeclToLoc),
159       ExprToLoc(Other.ExprToLoc), LocToVal(Other.LocToVal),
160       MemberLocToStruct(Other.MemberLocToStruct),
161       FlowConditionToken(&DACtx->forkFlowCondition(*Other.FlowConditionToken)) {
162 }
163 
164 Environment &Environment::operator=(const Environment &Other) {
165   Environment Copy(Other);
166   *this = std::move(Copy);
167   return *this;
168 }
169 
170 Environment::Environment(DataflowAnalysisContext &DACtx,
171                          const DeclContext &DeclCtxArg)
172     : Environment(DACtx) {
173   setDeclCtx(&DeclCtxArg);
174 
175   if (const auto *FuncDecl = dyn_cast<FunctionDecl>(DeclCtx)) {
176     assert(FuncDecl->getBody() != nullptr);
177     initGlobalVars(*FuncDecl->getBody(), *this);
178     for (const auto *ParamDecl : FuncDecl->parameters()) {
179       assert(ParamDecl != nullptr);
180       auto &ParamLoc = createStorageLocation(*ParamDecl);
181       setStorageLocation(*ParamDecl, ParamLoc);
182       if (Value *ParamVal = createValue(ParamDecl->getType()))
183         setValue(ParamLoc, *ParamVal);
184     }
185 
186     QualType ReturnType = FuncDecl->getReturnType();
187     ReturnLoc = &createStorageLocation(ReturnType);
188   }
189 
190   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclCtx)) {
191     auto *Parent = MethodDecl->getParent();
192     assert(Parent != nullptr);
193     if (Parent->isLambda())
194       MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext());
195 
196     if (MethodDecl && !MethodDecl->isStatic()) {
197       QualType ThisPointeeType = MethodDecl->getThisObjectType();
198       // FIXME: Add support for union types.
199       if (!ThisPointeeType->isUnionType()) {
200         ThisPointeeLoc = &createStorageLocation(ThisPointeeType);
201         if (Value *ThisPointeeVal = createValue(ThisPointeeType))
202           setValue(*ThisPointeeLoc, *ThisPointeeVal);
203       }
204     }
205   }
206 }
207 
208 Environment Environment::pushCall(const CallExpr *Call) const {
209   Environment Env(*this);
210 
211   // FIXME: Support references here.
212   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
213 
214   if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
215     if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
216       Env.ThisPointeeLoc = getStorageLocation(*Arg, SkipPast::Reference);
217     }
218   }
219 
220   Env.pushCallInternal(Call->getDirectCallee(),
221                        llvm::makeArrayRef(Call->getArgs(), Call->getNumArgs()));
222 
223   return Env;
224 }
225 
226 Environment Environment::pushCall(const CXXConstructExpr *Call) const {
227   Environment Env(*this);
228 
229   // FIXME: Support references here.
230   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
231 
232   Env.ThisPointeeLoc = Env.ReturnLoc;
233 
234   Env.pushCallInternal(Call->getConstructor(),
235                        llvm::makeArrayRef(Call->getArgs(), Call->getNumArgs()));
236 
237   return Env;
238 }
239 
240 void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
241                                    ArrayRef<const Expr *> Args) {
242   setDeclCtx(FuncDecl);
243 
244   // FIXME: In order to allow the callee to reference globals, we probably need
245   // to call `initGlobalVars` here in some way.
246 
247   auto ParamIt = FuncDecl->param_begin();
248 
249   // FIXME: Parameters don't always map to arguments 1:1; examples include
250   // overloaded operators implemented as member functions, and parameter packs.
251   for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
252     assert(ParamIt != FuncDecl->param_end());
253 
254     const Expr *Arg = Args[ArgIndex];
255     auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
256     if (ArgLoc == nullptr)
257       continue;
258 
259     const VarDecl *Param = *ParamIt;
260     auto &Loc = createStorageLocation(*Param);
261     setStorageLocation(*Param, Loc);
262 
263     QualType ParamType = Param->getType();
264     if (ParamType->isReferenceType()) {
265       auto &Val = takeOwnership(std::make_unique<ReferenceValue>(*ArgLoc));
266       setValue(Loc, Val);
267     } else if (auto *ArgVal = getValue(*ArgLoc)) {
268       setValue(Loc, *ArgVal);
269     } else if (Value *Val = createValue(ParamType)) {
270       setValue(Loc, *Val);
271     }
272   }
273 }
274 
275 void Environment::popCall(const Environment &CalleeEnv) {
276   // We ignore `DACtx` because it's already the same in both. We don't want the
277   // callee's `DeclCtx`, `ReturnLoc` or `ThisPointeeLoc`. We don't bring back
278   // `DeclToLoc` and `ExprToLoc` because we want to be able to later analyze the
279   // same callee in a different context, and `setStorageLocation` requires there
280   // to not already be a storage location assigned. Conceptually, these maps
281   // capture information from the local scope, so when popping that scope, we do
282   // not propagate the maps.
283   this->LocToVal = std::move(CalleeEnv.LocToVal);
284   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
285   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
286 }
287 
288 bool Environment::equivalentTo(const Environment &Other,
289                                Environment::ValueModel &Model) const {
290   assert(DACtx == Other.DACtx);
291 
292   if (ReturnLoc != Other.ReturnLoc)
293     return false;
294 
295   if (ThisPointeeLoc != Other.ThisPointeeLoc)
296     return false;
297 
298   if (DeclToLoc != Other.DeclToLoc)
299     return false;
300 
301   if (ExprToLoc != Other.ExprToLoc)
302     return false;
303 
304   // Compare the contents for the intersection of their domains.
305   for (auto &Entry : LocToVal) {
306     const StorageLocation *Loc = Entry.first;
307     assert(Loc != nullptr);
308 
309     Value *Val = Entry.second;
310     assert(Val != nullptr);
311 
312     auto It = Other.LocToVal.find(Loc);
313     if (It == Other.LocToVal.end())
314       continue;
315     assert(It->second != nullptr);
316 
317     if (!equivalentValues(Loc->getType(), Val, *this, It->second, Other, Model))
318       return false;
319   }
320 
321   return true;
322 }
323 
324 LatticeJoinEffect Environment::join(const Environment &Other,
325                                     Environment::ValueModel &Model) {
326   assert(DACtx == Other.DACtx);
327   assert(ReturnLoc == Other.ReturnLoc);
328   assert(ThisPointeeLoc == Other.ThisPointeeLoc);
329   assert(DeclCtx == Other.DeclCtx);
330 
331   auto Effect = LatticeJoinEffect::Unchanged;
332 
333   Environment JoinedEnv(*DACtx);
334 
335   JoinedEnv.setDeclCtx(DeclCtx);
336   JoinedEnv.ReturnLoc = ReturnLoc;
337   JoinedEnv.ThisPointeeLoc = ThisPointeeLoc;
338 
339   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
340   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
341     Effect = LatticeJoinEffect::Changed;
342 
343   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
344   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
345     Effect = LatticeJoinEffect::Changed;
346 
347   JoinedEnv.MemberLocToStruct =
348       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
349   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
350     Effect = LatticeJoinEffect::Changed;
351 
352   // FIXME: set `Effect` as needed.
353   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
354       *FlowConditionToken, *Other.FlowConditionToken);
355 
356   for (auto &Entry : LocToVal) {
357     const StorageLocation *Loc = Entry.first;
358     assert(Loc != nullptr);
359 
360     Value *Val = Entry.second;
361     assert(Val != nullptr);
362 
363     auto It = Other.LocToVal.find(Loc);
364     if (It == Other.LocToVal.end())
365       continue;
366     assert(It->second != nullptr);
367 
368     if (Val == It->second) {
369       JoinedEnv.LocToVal.insert({Loc, Val});
370       continue;
371     }
372 
373     if (Value *MergedVal = mergeDistinctValues(
374             Loc->getType(), Val, *this, It->second, Other, JoinedEnv, Model))
375       JoinedEnv.LocToVal.insert({Loc, MergedVal});
376   }
377   if (LocToVal.size() != JoinedEnv.LocToVal.size())
378     Effect = LatticeJoinEffect::Changed;
379 
380   *this = std::move(JoinedEnv);
381 
382   return Effect;
383 }
384 
385 StorageLocation &Environment::createStorageLocation(QualType Type) {
386   return DACtx->createStorageLocation(Type);
387 }
388 
389 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
390   // Evaluated declarations are always assigned the same storage locations to
391   // ensure that the environment stabilizes across loop iterations. Storage
392   // locations for evaluated declarations are stored in the analysis context.
393   return DACtx->getStableStorageLocation(D);
394 }
395 
396 StorageLocation &Environment::createStorageLocation(const Expr &E) {
397   // Evaluated expressions are always assigned the same storage locations to
398   // ensure that the environment stabilizes across loop iterations. Storage
399   // locations for evaluated expressions are stored in the analysis context.
400   return DACtx->getStableStorageLocation(E);
401 }
402 
403 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
404   assert(DeclToLoc.find(&D) == DeclToLoc.end());
405   DeclToLoc[&D] = &Loc;
406 }
407 
408 StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
409                                                  SkipPast SP) const {
410   auto It = DeclToLoc.find(&D);
411   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
412 }
413 
414 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
415   const Expr &CanonE = ignoreCFGOmittedNodes(E);
416   assert(ExprToLoc.find(&CanonE) == ExprToLoc.end());
417   ExprToLoc[&CanonE] = &Loc;
418 }
419 
420 StorageLocation *Environment::getStorageLocation(const Expr &E,
421                                                  SkipPast SP) const {
422   // FIXME: Add a test with parens.
423   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
424   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
425 }
426 
427 StorageLocation *Environment::getThisPointeeStorageLocation() const {
428   return ThisPointeeLoc;
429 }
430 
431 StorageLocation *Environment::getReturnStorageLocation() const {
432   return ReturnLoc;
433 }
434 
435 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
436   return DACtx->getOrCreateNullPointerValue(PointeeType);
437 }
438 
439 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
440   LocToVal[&Loc] = &Val;
441 
442   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
443     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
444 
445     const QualType Type = AggregateLoc.getType();
446     assert(Type->isStructureOrClassType());
447 
448     for (const FieldDecl *Field : getObjectFields(Type)) {
449       assert(Field != nullptr);
450       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
451       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
452       if (auto *FieldVal = StructVal->getChild(*Field))
453         setValue(FieldLoc, *FieldVal);
454     }
455   }
456 
457   auto It = MemberLocToStruct.find(&Loc);
458   if (It != MemberLocToStruct.end()) {
459     // `Loc` is the location of a struct member so we need to also update the
460     // value of the member in the corresponding `StructValue`.
461 
462     assert(It->second.first != nullptr);
463     StructValue &StructVal = *It->second.first;
464 
465     assert(It->second.second != nullptr);
466     const ValueDecl &Member = *It->second.second;
467 
468     StructVal.setChild(Member, Val);
469   }
470 }
471 
472 Value *Environment::getValue(const StorageLocation &Loc) const {
473   auto It = LocToVal.find(&Loc);
474   return It == LocToVal.end() ? nullptr : It->second;
475 }
476 
477 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
478   auto *Loc = getStorageLocation(D, SP);
479   if (Loc == nullptr)
480     return nullptr;
481   return getValue(*Loc);
482 }
483 
484 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
485   auto *Loc = getStorageLocation(E, SP);
486   if (Loc == nullptr)
487     return nullptr;
488   return getValue(*Loc);
489 }
490 
491 Value *Environment::createValue(QualType Type) {
492   llvm::DenseSet<QualType> Visited;
493   int CreatedValuesCount = 0;
494   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
495                                                 CreatedValuesCount);
496   if (CreatedValuesCount > MaxCompositeValueSize) {
497     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
498                  << '\n';
499   }
500   return Val;
501 }
502 
503 Value *Environment::createValueUnlessSelfReferential(
504     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
505     int &CreatedValuesCount) {
506   assert(!Type.isNull());
507 
508   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
509   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
510       Depth > MaxCompositeValueDepth)
511     return nullptr;
512 
513   if (Type->isBooleanType()) {
514     CreatedValuesCount++;
515     return &makeAtomicBoolValue();
516   }
517 
518   if (Type->isIntegerType()) {
519     CreatedValuesCount++;
520     return &takeOwnership(std::make_unique<IntegerValue>());
521   }
522 
523   if (Type->isReferenceType()) {
524     CreatedValuesCount++;
525     QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType();
526     auto &PointeeLoc = createStorageLocation(PointeeType);
527 
528     if (Visited.insert(PointeeType.getCanonicalType()).second) {
529       Value *PointeeVal = createValueUnlessSelfReferential(
530           PointeeType, Visited, Depth, CreatedValuesCount);
531       Visited.erase(PointeeType.getCanonicalType());
532 
533       if (PointeeVal != nullptr)
534         setValue(PointeeLoc, *PointeeVal);
535     }
536 
537     return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc));
538   }
539 
540   if (Type->isPointerType()) {
541     CreatedValuesCount++;
542     QualType PointeeType = Type->castAs<PointerType>()->getPointeeType();
543     auto &PointeeLoc = createStorageLocation(PointeeType);
544 
545     if (Visited.insert(PointeeType.getCanonicalType()).second) {
546       Value *PointeeVal = createValueUnlessSelfReferential(
547           PointeeType, Visited, Depth, CreatedValuesCount);
548       Visited.erase(PointeeType.getCanonicalType());
549 
550       if (PointeeVal != nullptr)
551         setValue(PointeeLoc, *PointeeVal);
552     }
553 
554     return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc));
555   }
556 
557   if (Type->isStructureOrClassType()) {
558     CreatedValuesCount++;
559     // FIXME: Initialize only fields that are accessed in the context that is
560     // being analyzed.
561     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
562     for (const FieldDecl *Field : getObjectFields(Type)) {
563       assert(Field != nullptr);
564 
565       QualType FieldType = Field->getType();
566       if (Visited.contains(FieldType.getCanonicalType()))
567         continue;
568 
569       Visited.insert(FieldType.getCanonicalType());
570       if (auto *FieldValue = createValueUnlessSelfReferential(
571               FieldType, Visited, Depth + 1, CreatedValuesCount))
572         FieldValues.insert({Field, FieldValue});
573       Visited.erase(FieldType.getCanonicalType());
574     }
575 
576     return &takeOwnership(
577         std::make_unique<StructValue>(std::move(FieldValues)));
578   }
579 
580   return nullptr;
581 }
582 
583 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
584   switch (SP) {
585   case SkipPast::None:
586     return Loc;
587   case SkipPast::Reference:
588     // References cannot be chained so we only need to skip past one level of
589     // indirection.
590     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
591       return Val->getReferentLoc();
592     return Loc;
593   case SkipPast::ReferenceThenPointer:
594     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
595     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
596       return Val->getPointeeLoc();
597     return LocPastRef;
598   }
599   llvm_unreachable("bad SkipPast kind");
600 }
601 
602 const StorageLocation &Environment::skip(const StorageLocation &Loc,
603                                          SkipPast SP) const {
604   return skip(*const_cast<StorageLocation *>(&Loc), SP);
605 }
606 
607 void Environment::addToFlowCondition(BoolValue &Val) {
608   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
609 }
610 
611 bool Environment::flowConditionImplies(BoolValue &Val) const {
612   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
613 }
614 
615 void Environment::dump() const {
616   DACtx->dumpFlowCondition(*FlowConditionToken);
617 }
618 
619 } // namespace dataflow
620 } // namespace clang
621