1af7bc39bSStanislav Gatev //===-- DataflowEnvironment.cpp ---------------------------------*- C++ -*-===//
2af7bc39bSStanislav Gatev //
3af7bc39bSStanislav Gatev // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4af7bc39bSStanislav Gatev // See https://llvm.org/LICENSE.txt for license information.
5af7bc39bSStanislav Gatev // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6af7bc39bSStanislav Gatev //
7af7bc39bSStanislav Gatev //===----------------------------------------------------------------------===//
8af7bc39bSStanislav Gatev //
9af7bc39bSStanislav Gatev //  This file defines an Environment class that is used by dataflow analyses
10af7bc39bSStanislav Gatev //  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
11af7bc39bSStanislav Gatev //  program at given program points.
12af7bc39bSStanislav Gatev //
13af7bc39bSStanislav Gatev //===----------------------------------------------------------------------===//
14af7bc39bSStanislav Gatev 
15af7bc39bSStanislav Gatev #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
16af7bc39bSStanislav Gatev #include "clang/AST/Decl.h"
1799f7d55eSStanislav Gatev #include "clang/AST/DeclCXX.h"
18af7bc39bSStanislav Gatev #include "clang/AST/Type.h"
19af7bc39bSStanislav Gatev #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
20af7bc39bSStanislav Gatev #include "clang/Analysis/FlowSensitive/Value.h"
21af7bc39bSStanislav Gatev #include "llvm/ADT/DenseMap.h"
22af7bc39bSStanislav Gatev #include "llvm/ADT/DenseSet.h"
236c81b572SYitzhak Mandelbaum #include "llvm/Support/Casting.h"
24e7481f6eSStanislav Gatev #include "llvm/Support/ErrorHandling.h"
2503dff121SStanislav Gatev #include <cassert>
26af7bc39bSStanislav Gatev #include <memory>
27af7bc39bSStanislav Gatev #include <utility>
28af7bc39bSStanislav Gatev 
29af7bc39bSStanislav Gatev namespace clang {
30af7bc39bSStanislav Gatev namespace dataflow {
31af7bc39bSStanislav Gatev 
32208c25fcSYitzhak Mandelbaum // FIXME: convert these to parameters of the analysis or environment. Current
33208c25fcSYitzhak Mandelbaum // settings have been experimentaly validated, but only for a particular
34208c25fcSYitzhak Mandelbaum // analysis.
35208c25fcSYitzhak Mandelbaum static constexpr int MaxCompositeValueDepth = 3;
36208c25fcSYitzhak Mandelbaum static constexpr int MaxCompositeValueSize = 1000;
37208c25fcSYitzhak Mandelbaum 
38af7bc39bSStanislav Gatev /// Returns a map consisting of key-value entries that are present in both maps.
39af7bc39bSStanislav Gatev template <typename K, typename V>
intersectDenseMaps(const llvm::DenseMap<K,V> & Map1,const llvm::DenseMap<K,V> & Map2)40af7bc39bSStanislav Gatev llvm::DenseMap<K, V> intersectDenseMaps(const llvm::DenseMap<K, V> &Map1,
41af7bc39bSStanislav Gatev                                         const llvm::DenseMap<K, V> &Map2) {
42af7bc39bSStanislav Gatev   llvm::DenseMap<K, V> Result;
43af7bc39bSStanislav Gatev   for (auto &Entry : Map1) {
44af7bc39bSStanislav Gatev     auto It = Map2.find(Entry.first);
45af7bc39bSStanislav Gatev     if (It != Map2.end() && Entry.second == It->second)
46af7bc39bSStanislav Gatev       Result.insert({Entry.first, Entry.second});
47af7bc39bSStanislav Gatev   }
48af7bc39bSStanislav Gatev   return Result;
49af7bc39bSStanislav Gatev }
50af7bc39bSStanislav Gatev 
areEquivalentIndirectionValues(Value * Val1,Value * Val2)51a1b2b7d9SWei Yi Tee static bool areEquivalentIndirectionValues(Value *Val1, Value *Val2) {
52a1b2b7d9SWei Yi Tee   if (auto *IndVal1 = dyn_cast<ReferenceValue>(Val1)) {
53a1b2b7d9SWei Yi Tee     auto *IndVal2 = cast<ReferenceValue>(Val2);
5497d69cdaSWei Yi Tee     return &IndVal1->getReferentLoc() == &IndVal2->getReferentLoc();
55a1b2b7d9SWei Yi Tee   }
56a1b2b7d9SWei Yi Tee   if (auto *IndVal1 = dyn_cast<PointerValue>(Val1)) {
57a1b2b7d9SWei Yi Tee     auto *IndVal2 = cast<PointerValue>(Val2);
58a1b2b7d9SWei Yi Tee     return &IndVal1->getPointeeLoc() == &IndVal2->getPointeeLoc();
59a1b2b7d9SWei Yi Tee   }
60a1b2b7d9SWei Yi Tee   return false;
61a1b2b7d9SWei Yi Tee }
62a1b2b7d9SWei Yi Tee 
636b8800dfSStanislav Gatev /// Returns true if and only if `Val1` is equivalent to `Val2`.
equivalentValues(QualType Type,Value * Val1,const Environment & Env1,Value * Val2,const Environment & Env2,Environment::ValueModel & Model)641e571585SStanislav Gatev static bool equivalentValues(QualType Type, Value *Val1,
651e571585SStanislav Gatev                              const Environment &Env1, Value *Val2,
661e571585SStanislav Gatev                              const Environment &Env2,
676b8800dfSStanislav Gatev                              Environment::ValueModel &Model) {
68a1b2b7d9SWei Yi Tee   return Val1 == Val2 || areEquivalentIndirectionValues(Val1, Val2) ||
69a1b2b7d9SWei Yi Tee          Model.compareEquivalent(Type, *Val1, Env1, *Val2, Env2);
706b8800dfSStanislav Gatev }
716b8800dfSStanislav Gatev 
7237b4782eSYitzhak Mandelbaum /// Attempts to merge distinct values `Val1` and `Val2` in `Env1` and `Env2`,
7301db1036SYitzhak Mandelbaum /// respectively, of the same type `Type`. Merging generally produces a single
7401db1036SYitzhak Mandelbaum /// value that (soundly) approximates the two inputs, although the actual
7501db1036SYitzhak Mandelbaum /// meaning depends on `Model`.
mergeDistinctValues(QualType Type,Value * Val1,const Environment & Env1,Value * Val2,const Environment & Env2,Environment & MergedEnv,Environment::ValueModel & Model)7637b4782eSYitzhak Mandelbaum static Value *mergeDistinctValues(QualType Type, Value *Val1,
7737b4782eSYitzhak Mandelbaum                                   const Environment &Env1, Value *Val2,
7837b4782eSYitzhak Mandelbaum                                   const Environment &Env2,
7937b4782eSYitzhak Mandelbaum                                   Environment &MergedEnv,
8001db1036SYitzhak Mandelbaum                                   Environment::ValueModel &Model) {
8101db1036SYitzhak Mandelbaum   // Join distinct boolean values preserving information about the constraints
82955a05a2SStanislav Gatev   // in the respective path conditions.
83bbcf11f5SYitzhak Mandelbaum   //
84bbcf11f5SYitzhak Mandelbaum   // FIXME: Does not work for backedges, since the two (or more) paths will not
85bbcf11f5SYitzhak Mandelbaum   // have mutually exclusive conditions.
8601db1036SYitzhak Mandelbaum   if (auto *Expr1 = dyn_cast<BoolValue>(Val1)) {
8701db1036SYitzhak Mandelbaum     auto *Expr2 = cast<BoolValue>(Val2);
88e363c596SStanislav Gatev     auto &MergedVal = MergedEnv.makeAtomicBoolValue();
89e363c596SStanislav Gatev     MergedEnv.addToFlowCondition(MergedEnv.makeOr(
90e363c596SStanislav Gatev         MergedEnv.makeAnd(Env1.getFlowConditionToken(),
91e363c596SStanislav Gatev                           MergedEnv.makeIff(MergedVal, *Expr1)),
92e363c596SStanislav Gatev         MergedEnv.makeAnd(Env2.getFlowConditionToken(),
93e363c596SStanislav Gatev                           MergedEnv.makeIff(MergedVal, *Expr2))));
94e363c596SStanislav Gatev     return &MergedVal;
9501db1036SYitzhak Mandelbaum   }
9601db1036SYitzhak Mandelbaum 
976c81b572SYitzhak Mandelbaum   // FIXME: add unit tests that cover this statement.
98a1b2b7d9SWei Yi Tee   if (areEquivalentIndirectionValues(Val1, Val2)) {
996c81b572SYitzhak Mandelbaum     return Val1;
1006c81b572SYitzhak Mandelbaum   }
1016c81b572SYitzhak Mandelbaum 
10201db1036SYitzhak Mandelbaum   // FIXME: Consider destroying `MergedValue` immediately if `ValueModel::merge`
10301db1036SYitzhak Mandelbaum   // returns false to avoid storing unneeded values in `DACtx`.
10437b4782eSYitzhak Mandelbaum   if (Value *MergedVal = MergedEnv.createValue(Type))
10537b4782eSYitzhak Mandelbaum     if (Model.merge(Type, *Val1, Env1, *Val2, Env2, *MergedVal, MergedEnv))
10601db1036SYitzhak Mandelbaum       return MergedVal;
10701db1036SYitzhak Mandelbaum 
10801db1036SYitzhak Mandelbaum   return nullptr;
10901db1036SYitzhak Mandelbaum }
11001db1036SYitzhak Mandelbaum 
11103dff121SStanislav Gatev /// Initializes a global storage value.
initGlobalVar(const VarDecl & D,Environment & Env)11203dff121SStanislav Gatev static void initGlobalVar(const VarDecl &D, Environment &Env) {
11303dff121SStanislav Gatev   if (!D.hasGlobalStorage() ||
11403dff121SStanislav Gatev       Env.getStorageLocation(D, SkipPast::None) != nullptr)
11503dff121SStanislav Gatev     return;
11603dff121SStanislav Gatev 
11703dff121SStanislav Gatev   auto &Loc = Env.createStorageLocation(D);
11803dff121SStanislav Gatev   Env.setStorageLocation(D, Loc);
11903dff121SStanislav Gatev   if (auto *Val = Env.createValue(D.getType()))
12003dff121SStanislav Gatev     Env.setValue(Loc, *Val);
12103dff121SStanislav Gatev }
12203dff121SStanislav Gatev 
12303dff121SStanislav Gatev /// Initializes a global storage value.
initGlobalVar(const Decl & D,Environment & Env)12403dff121SStanislav Gatev static void initGlobalVar(const Decl &D, Environment &Env) {
12503dff121SStanislav Gatev   if (auto *V = dyn_cast<VarDecl>(&D))
12603dff121SStanislav Gatev     initGlobalVar(*V, Env);
12703dff121SStanislav Gatev }
12803dff121SStanislav Gatev 
12903dff121SStanislav Gatev /// Initializes global storage values that are declared or referenced from
13003dff121SStanislav Gatev /// sub-statements of `S`.
13103dff121SStanislav Gatev // FIXME: Add support for resetting globals after function calls to enable
13203dff121SStanislav Gatev // the implementation of sound analyses.
initGlobalVars(const Stmt & S,Environment & Env)13303dff121SStanislav Gatev static void initGlobalVars(const Stmt &S, Environment &Env) {
13403dff121SStanislav Gatev   for (auto *Child : S.children()) {
13503dff121SStanislav Gatev     if (Child != nullptr)
13603dff121SStanislav Gatev       initGlobalVars(*Child, Env);
13703dff121SStanislav Gatev   }
13803dff121SStanislav Gatev 
13903dff121SStanislav Gatev   if (auto *DS = dyn_cast<DeclStmt>(&S)) {
14003dff121SStanislav Gatev     if (DS->isSingleDecl()) {
14103dff121SStanislav Gatev       initGlobalVar(*DS->getSingleDecl(), Env);
14203dff121SStanislav Gatev     } else {
14303dff121SStanislav Gatev       for (auto *D : DS->getDeclGroup())
14403dff121SStanislav Gatev         initGlobalVar(*D, Env);
14503dff121SStanislav Gatev     }
14603dff121SStanislav Gatev   } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) {
14703dff121SStanislav Gatev     initGlobalVar(*E->getDecl(), Env);
14803dff121SStanislav Gatev   } else if (auto *E = dyn_cast<MemberExpr>(&S)) {
14903dff121SStanislav Gatev     initGlobalVar(*E->getMemberDecl(), Env);
15003dff121SStanislav Gatev   }
15103dff121SStanislav Gatev }
15203dff121SStanislav Gatev 
Environment(DataflowAnalysisContext & DACtx)153955a05a2SStanislav Gatev Environment::Environment(DataflowAnalysisContext &DACtx)
154955a05a2SStanislav Gatev     : DACtx(&DACtx), FlowConditionToken(&DACtx.makeFlowConditionToken()) {}
155955a05a2SStanislav Gatev 
Environment(const Environment & Other)156955a05a2SStanislav Gatev Environment::Environment(const Environment &Other)
157955a05a2SStanislav Gatev     : DACtx(Other.DACtx), DeclToLoc(Other.DeclToLoc),
158955a05a2SStanislav Gatev       ExprToLoc(Other.ExprToLoc), LocToVal(Other.LocToVal),
159955a05a2SStanislav Gatev       MemberLocToStruct(Other.MemberLocToStruct),
160955a05a2SStanislav Gatev       FlowConditionToken(&DACtx->forkFlowCondition(*Other.FlowConditionToken)) {
161955a05a2SStanislav Gatev }
162955a05a2SStanislav Gatev 
operator =(const Environment & Other)163955a05a2SStanislav Gatev Environment &Environment::operator=(const Environment &Other) {
164955a05a2SStanislav Gatev   Environment Copy(Other);
165955a05a2SStanislav Gatev   *this = std::move(Copy);
166955a05a2SStanislav Gatev   return *this;
167955a05a2SStanislav Gatev }
168955a05a2SStanislav Gatev 
Environment(DataflowAnalysisContext & DACtx,const DeclContext & DeclCtx)16999f7d55eSStanislav Gatev Environment::Environment(DataflowAnalysisContext &DACtx,
17099f7d55eSStanislav Gatev                          const DeclContext &DeclCtx)
17199f7d55eSStanislav Gatev     : Environment(DACtx) {
17299f7d55eSStanislav Gatev   if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) {
17303dff121SStanislav Gatev     assert(FuncDecl->getBody() != nullptr);
17403dff121SStanislav Gatev     initGlobalVars(*FuncDecl->getBody(), *this);
17599f7d55eSStanislav Gatev     for (const auto *ParamDecl : FuncDecl->parameters()) {
17699f7d55eSStanislav Gatev       assert(ParamDecl != nullptr);
17799f7d55eSStanislav Gatev       auto &ParamLoc = createStorageLocation(*ParamDecl);
17899f7d55eSStanislav Gatev       setStorageLocation(*ParamDecl, ParamLoc);
179782eced5SStanislav Gatev       if (Value *ParamVal = createValue(ParamDecl->getType()))
180782eced5SStanislav Gatev         setValue(ParamLoc, *ParamVal);
18199f7d55eSStanislav Gatev     }
18299f7d55eSStanislav Gatev   }
18399f7d55eSStanislav Gatev 
18499f7d55eSStanislav Gatev   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) {
1855520c583SEric Li     auto *Parent = MethodDecl->getParent();
1865520c583SEric Li     assert(Parent != nullptr);
1875520c583SEric Li     if (Parent->isLambda())
1885520c583SEric Li       MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext());
1895520c583SEric Li 
1905520c583SEric Li     if (MethodDecl && !MethodDecl->isStatic()) {
19199f7d55eSStanislav Gatev       QualType ThisPointeeType = MethodDecl->getThisObjectType();
19299f7d55eSStanislav Gatev       // FIXME: Add support for union types.
19399f7d55eSStanislav Gatev       if (!ThisPointeeType->isUnionType()) {
19499f7d55eSStanislav Gatev         auto &ThisPointeeLoc = createStorageLocation(ThisPointeeType);
19599f7d55eSStanislav Gatev         DACtx.setThisPointeeStorageLocation(ThisPointeeLoc);
196782eced5SStanislav Gatev         if (Value *ThisPointeeVal = createValue(ThisPointeeType))
197782eced5SStanislav Gatev           setValue(ThisPointeeLoc, *ThisPointeeVal);
19899f7d55eSStanislav Gatev       }
19999f7d55eSStanislav Gatev     }
20099f7d55eSStanislav Gatev   }
20199f7d55eSStanislav Gatev }
20299f7d55eSStanislav Gatev 
pushCall(const CallExpr * Call) const203300fbf56SSam Estep Environment Environment::pushCall(const CallExpr *Call) const {
204300fbf56SSam Estep   Environment Env(*this);
205300fbf56SSam Estep 
206300fbf56SSam Estep   // FIXME: Currently this only works if the callee is never a method and the
207300fbf56SSam Estep   // same callee is never analyzed from multiple separate callsites. To
208300fbf56SSam Estep   // generalize this, we'll need to store a "context" field (probably a stack of
209300fbf56SSam Estep   // `const CallExpr *`s) in the `Environment`, and then change the
210300fbf56SSam Estep   // `DataflowAnalysisContext` class to hold a map from contexts to "frames",
211300fbf56SSam Estep   // where each frame stores its own version of what are currently the
212300fbf56SSam Estep   // `DeclToLoc`, `ExprToLoc`, and `ThisPointeeLoc` fields.
213300fbf56SSam Estep 
214300fbf56SSam Estep   const auto *FuncDecl = Call->getDirectCallee();
215300fbf56SSam Estep   assert(FuncDecl != nullptr);
216*1f8ae9d7SWeverything   assert(FuncDecl->getBody() != nullptr);
217300fbf56SSam Estep   // FIXME: In order to allow the callee to reference globals, we probably need
218300fbf56SSam Estep   // to call `initGlobalVars` here in some way.
219300fbf56SSam Estep 
220300fbf56SSam Estep   auto ParamIt = FuncDecl->param_begin();
221300fbf56SSam Estep   auto ArgIt = Call->arg_begin();
222300fbf56SSam Estep   auto ArgEnd = Call->arg_end();
223300fbf56SSam Estep 
224300fbf56SSam Estep   // FIXME: Parameters don't always map to arguments 1:1; examples include
225300fbf56SSam Estep   // overloaded operators implemented as member functions, and parameter packs.
226300fbf56SSam Estep   for (; ArgIt != ArgEnd; ++ParamIt, ++ArgIt) {
227*1f8ae9d7SWeverything     assert(ParamIt != FuncDecl->param_end());
228300fbf56SSam Estep 
229300fbf56SSam Estep     const VarDecl *Param = *ParamIt;
230300fbf56SSam Estep     const Expr *Arg = *ArgIt;
231300fbf56SSam Estep     auto *ArgLoc = Env.getStorageLocation(*Arg, SkipPast::Reference);
232300fbf56SSam Estep     assert(ArgLoc != nullptr);
233300fbf56SSam Estep     Env.setStorageLocation(*Param, *ArgLoc);
234300fbf56SSam Estep   }
235300fbf56SSam Estep 
236300fbf56SSam Estep   return Env;
237300fbf56SSam Estep }
238300fbf56SSam Estep 
equivalentTo(const Environment & Other,Environment::ValueModel & Model) const2396b8800dfSStanislav Gatev bool Environment::equivalentTo(const Environment &Other,
2406b8800dfSStanislav Gatev                                Environment::ValueModel &Model) const {
241af7bc39bSStanislav Gatev   assert(DACtx == Other.DACtx);
2426b8800dfSStanislav Gatev 
2436b8800dfSStanislav Gatev   if (DeclToLoc != Other.DeclToLoc)
2446b8800dfSStanislav Gatev     return false;
2456b8800dfSStanislav Gatev 
2466b8800dfSStanislav Gatev   if (ExprToLoc != Other.ExprToLoc)
2476b8800dfSStanislav Gatev     return false;
2486b8800dfSStanislav Gatev 
249bbcf11f5SYitzhak Mandelbaum   // Compare the contents for the intersection of their domains.
2506b8800dfSStanislav Gatev   for (auto &Entry : LocToVal) {
2516b8800dfSStanislav Gatev     const StorageLocation *Loc = Entry.first;
2526b8800dfSStanislav Gatev     assert(Loc != nullptr);
2536b8800dfSStanislav Gatev 
2546b8800dfSStanislav Gatev     Value *Val = Entry.second;
2556b8800dfSStanislav Gatev     assert(Val != nullptr);
2566b8800dfSStanislav Gatev 
2576b8800dfSStanislav Gatev     auto It = Other.LocToVal.find(Loc);
2586b8800dfSStanislav Gatev     if (It == Other.LocToVal.end())
259bbcf11f5SYitzhak Mandelbaum       continue;
2606b8800dfSStanislav Gatev     assert(It->second != nullptr);
2616b8800dfSStanislav Gatev 
2621e571585SStanislav Gatev     if (!equivalentValues(Loc->getType(), Val, *this, It->second, Other, Model))
2636b8800dfSStanislav Gatev       return false;
2646b8800dfSStanislav Gatev   }
2656b8800dfSStanislav Gatev 
2666b8800dfSStanislav Gatev   return true;
267af7bc39bSStanislav Gatev }
268af7bc39bSStanislav Gatev 
join(const Environment & Other,Environment::ValueModel & Model)269d3597ec0SStanislav Gatev LatticeJoinEffect Environment::join(const Environment &Other,
2706b8800dfSStanislav Gatev                                     Environment::ValueModel &Model) {
271af7bc39bSStanislav Gatev   assert(DACtx == Other.DACtx);
272af7bc39bSStanislav Gatev 
273af7bc39bSStanislav Gatev   auto Effect = LatticeJoinEffect::Unchanged;
274af7bc39bSStanislav Gatev 
27537b4782eSYitzhak Mandelbaum   Environment JoinedEnv(*DACtx);
27637b4782eSYitzhak Mandelbaum 
27737b4782eSYitzhak Mandelbaum   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
27837b4782eSYitzhak Mandelbaum   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
279af7bc39bSStanislav Gatev     Effect = LatticeJoinEffect::Changed;
280af7bc39bSStanislav Gatev 
28137b4782eSYitzhak Mandelbaum   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
28237b4782eSYitzhak Mandelbaum   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
283c95cb4deSStanislav Gatev     Effect = LatticeJoinEffect::Changed;
284c95cb4deSStanislav Gatev 
28537b4782eSYitzhak Mandelbaum   JoinedEnv.MemberLocToStruct =
286baa0f221SStanislav Gatev       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
28737b4782eSYitzhak Mandelbaum   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
288baa0f221SStanislav Gatev     Effect = LatticeJoinEffect::Changed;
289baa0f221SStanislav Gatev 
29037b4782eSYitzhak Mandelbaum   // FIXME: set `Effect` as needed.
291955a05a2SStanislav Gatev   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
292955a05a2SStanislav Gatev       *FlowConditionToken, *Other.FlowConditionToken);
29337b4782eSYitzhak Mandelbaum 
29437b4782eSYitzhak Mandelbaum   for (auto &Entry : LocToVal) {
295d3597ec0SStanislav Gatev     const StorageLocation *Loc = Entry.first;
296d3597ec0SStanislav Gatev     assert(Loc != nullptr);
297d3597ec0SStanislav Gatev 
298d3597ec0SStanislav Gatev     Value *Val = Entry.second;
299d3597ec0SStanislav Gatev     assert(Val != nullptr);
300d3597ec0SStanislav Gatev 
301d3597ec0SStanislav Gatev     auto It = Other.LocToVal.find(Loc);
302d3597ec0SStanislav Gatev     if (It == Other.LocToVal.end())
303d3597ec0SStanislav Gatev       continue;
304d3597ec0SStanislav Gatev     assert(It->second != nullptr);
305d3597ec0SStanislav Gatev 
306bbcf11f5SYitzhak Mandelbaum     if (Val == It->second) {
30737b4782eSYitzhak Mandelbaum       JoinedEnv.LocToVal.insert({Loc, Val});
308d3597ec0SStanislav Gatev       continue;
309d3597ec0SStanislav Gatev     }
310d3597ec0SStanislav Gatev 
31137b4782eSYitzhak Mandelbaum     if (Value *MergedVal = mergeDistinctValues(
31237b4782eSYitzhak Mandelbaum             Loc->getType(), Val, *this, It->second, Other, JoinedEnv, Model))
31337b4782eSYitzhak Mandelbaum       JoinedEnv.LocToVal.insert({Loc, MergedVal});
314d3597ec0SStanislav Gatev   }
31537b4782eSYitzhak Mandelbaum   if (LocToVal.size() != JoinedEnv.LocToVal.size())
316af7bc39bSStanislav Gatev     Effect = LatticeJoinEffect::Changed;
317af7bc39bSStanislav Gatev 
31837b4782eSYitzhak Mandelbaum   *this = std::move(JoinedEnv);
3191e571585SStanislav Gatev 
320af7bc39bSStanislav Gatev   return Effect;
321af7bc39bSStanislav Gatev }
322af7bc39bSStanislav Gatev 
createStorageLocation(QualType Type)323af7bc39bSStanislav Gatev StorageLocation &Environment::createStorageLocation(QualType Type) {
32412c7352fSWei Yi Tee   return DACtx->getStableStorageLocation(Type);
325af7bc39bSStanislav Gatev }
326af7bc39bSStanislav Gatev 
createStorageLocation(const VarDecl & D)327af7bc39bSStanislav Gatev StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
328af7bc39bSStanislav Gatev   // Evaluated declarations are always assigned the same storage locations to
329af7bc39bSStanislav Gatev   // ensure that the environment stabilizes across loop iterations. Storage
330af7bc39bSStanislav Gatev   // locations for evaluated declarations are stored in the analysis context.
33112c7352fSWei Yi Tee   return DACtx->getStableStorageLocation(D);
332af7bc39bSStanislav Gatev }
333af7bc39bSStanislav Gatev 
createStorageLocation(const Expr & E)334e7481f6eSStanislav Gatev StorageLocation &Environment::createStorageLocation(const Expr &E) {
335e7481f6eSStanislav Gatev   // Evaluated expressions are always assigned the same storage locations to
336e7481f6eSStanislav Gatev   // ensure that the environment stabilizes across loop iterations. Storage
337e7481f6eSStanislav Gatev   // locations for evaluated expressions are stored in the analysis context.
33812c7352fSWei Yi Tee   return DACtx->getStableStorageLocation(E);
339e7481f6eSStanislav Gatev }
340e7481f6eSStanislav Gatev 
setStorageLocation(const ValueDecl & D,StorageLocation & Loc)341af7bc39bSStanislav Gatev void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
342af7bc39bSStanislav Gatev   assert(DeclToLoc.find(&D) == DeclToLoc.end());
343af7bc39bSStanislav Gatev   DeclToLoc[&D] = &Loc;
344af7bc39bSStanislav Gatev }
345af7bc39bSStanislav Gatev 
getStorageLocation(const ValueDecl & D,SkipPast SP) const346e7481f6eSStanislav Gatev StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
347e7481f6eSStanislav Gatev                                                  SkipPast SP) const {
348af7bc39bSStanislav Gatev   auto It = DeclToLoc.find(&D);
349e7481f6eSStanislav Gatev   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
350e7481f6eSStanislav Gatev }
351e7481f6eSStanislav Gatev 
setStorageLocation(const Expr & E,StorageLocation & Loc)352e7481f6eSStanislav Gatev void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
35345643cfcSEric Li   const Expr &CanonE = ignoreCFGOmittedNodes(E);
35445643cfcSEric Li   assert(ExprToLoc.find(&CanonE) == ExprToLoc.end());
35545643cfcSEric Li   ExprToLoc[&CanonE] = &Loc;
356e7481f6eSStanislav Gatev }
357e7481f6eSStanislav Gatev 
getStorageLocation(const Expr & E,SkipPast SP) const358e7481f6eSStanislav Gatev StorageLocation *Environment::getStorageLocation(const Expr &E,
359e7481f6eSStanislav Gatev                                                  SkipPast SP) const {
360b000b770SStanislav Gatev   // FIXME: Add a test with parens.
36145643cfcSEric Li   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
362e7481f6eSStanislav Gatev   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
363af7bc39bSStanislav Gatev }
364af7bc39bSStanislav Gatev 
getThisPointeeStorageLocation() const36599f7d55eSStanislav Gatev StorageLocation *Environment::getThisPointeeStorageLocation() const {
36699f7d55eSStanislav Gatev   return DACtx->getThisPointeeStorageLocation();
36799f7d55eSStanislav Gatev }
36899f7d55eSStanislav Gatev 
getOrCreateNullPointerValue(QualType PointeeType)369b611376eSWei Yi Tee PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
370b611376eSWei Yi Tee   return DACtx->getOrCreateNullPointerValue(PointeeType);
371b611376eSWei Yi Tee }
372b611376eSWei Yi Tee 
setValue(const StorageLocation & Loc,Value & Val)3737d941d6dSStanislav Gatev void Environment::setValue(const StorageLocation &Loc, Value &Val) {
3747d941d6dSStanislav Gatev   LocToVal[&Loc] = &Val;
3757d941d6dSStanislav Gatev 
3767d941d6dSStanislav Gatev   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
3777d941d6dSStanislav Gatev     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
3787d941d6dSStanislav Gatev 
3797d941d6dSStanislav Gatev     const QualType Type = AggregateLoc.getType();
3807d941d6dSStanislav Gatev     assert(Type->isStructureOrClassType());
3817d941d6dSStanislav Gatev 
38267136d0eSYitzhak Mandelbaum     for (const FieldDecl *Field : getObjectFields(Type)) {
3837d941d6dSStanislav Gatev       assert(Field != nullptr);
384baa0f221SStanislav Gatev       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
385baa0f221SStanislav Gatev       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
38618c84e2dSYitzhak Mandelbaum       if (auto *FieldVal = StructVal->getChild(*Field))
38718c84e2dSYitzhak Mandelbaum         setValue(FieldLoc, *FieldVal);
3887d941d6dSStanislav Gatev     }
3897d941d6dSStanislav Gatev   }
390baa0f221SStanislav Gatev 
391c0c9d717SDmitri Gribenko   auto It = MemberLocToStruct.find(&Loc);
392c0c9d717SDmitri Gribenko   if (It != MemberLocToStruct.end()) {
393baa0f221SStanislav Gatev     // `Loc` is the location of a struct member so we need to also update the
394baa0f221SStanislav Gatev     // value of the member in the corresponding `StructValue`.
395baa0f221SStanislav Gatev 
396c0c9d717SDmitri Gribenko     assert(It->second.first != nullptr);
397c0c9d717SDmitri Gribenko     StructValue &StructVal = *It->second.first;
398baa0f221SStanislav Gatev 
399c0c9d717SDmitri Gribenko     assert(It->second.second != nullptr);
400c0c9d717SDmitri Gribenko     const ValueDecl &Member = *It->second.second;
401baa0f221SStanislav Gatev 
402baa0f221SStanislav Gatev     StructVal.setChild(Member, Val);
403baa0f221SStanislav Gatev   }
404af7bc39bSStanislav Gatev }
405af7bc39bSStanislav Gatev 
getValue(const StorageLocation & Loc) const406af7bc39bSStanislav Gatev Value *Environment::getValue(const StorageLocation &Loc) const {
407af7bc39bSStanislav Gatev   auto It = LocToVal.find(&Loc);
408af7bc39bSStanislav Gatev   return It == LocToVal.end() ? nullptr : It->second;
409af7bc39bSStanislav Gatev }
410af7bc39bSStanislav Gatev 
getValue(const ValueDecl & D,SkipPast SP) const411e7481f6eSStanislav Gatev Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
412e7481f6eSStanislav Gatev   auto *Loc = getStorageLocation(D, SP);
413e7481f6eSStanislav Gatev   if (Loc == nullptr)
414e7481f6eSStanislav Gatev     return nullptr;
415e7481f6eSStanislav Gatev   return getValue(*Loc);
416e7481f6eSStanislav Gatev }
417e7481f6eSStanislav Gatev 
getValue(const Expr & E,SkipPast SP) const418e7481f6eSStanislav Gatev Value *Environment::getValue(const Expr &E, SkipPast SP) const {
419e7481f6eSStanislav Gatev   auto *Loc = getStorageLocation(E, SP);
420e7481f6eSStanislav Gatev   if (Loc == nullptr)
421e7481f6eSStanislav Gatev     return nullptr;
422e7481f6eSStanislav Gatev   return getValue(*Loc);
423e7481f6eSStanislav Gatev }
424e7481f6eSStanislav Gatev 
createValue(QualType Type)425782eced5SStanislav Gatev Value *Environment::createValue(QualType Type) {
426af7bc39bSStanislav Gatev   llvm::DenseSet<QualType> Visited;
427208c25fcSYitzhak Mandelbaum   int CreatedValuesCount = 0;
428208c25fcSYitzhak Mandelbaum   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
429208c25fcSYitzhak Mandelbaum                                                 CreatedValuesCount);
430208c25fcSYitzhak Mandelbaum   if (CreatedValuesCount > MaxCompositeValueSize) {
431cfb81690SNathan James     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
432cfb81690SNathan James                  << '\n';
433208c25fcSYitzhak Mandelbaum   }
434208c25fcSYitzhak Mandelbaum   return Val;
435af7bc39bSStanislav Gatev }
436af7bc39bSStanislav Gatev 
createValueUnlessSelfReferential(QualType Type,llvm::DenseSet<QualType> & Visited,int Depth,int & CreatedValuesCount)437782eced5SStanislav Gatev Value *Environment::createValueUnlessSelfReferential(
438208c25fcSYitzhak Mandelbaum     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
439208c25fcSYitzhak Mandelbaum     int &CreatedValuesCount) {
440af7bc39bSStanislav Gatev   assert(!Type.isNull());
441af7bc39bSStanislav Gatev 
442208c25fcSYitzhak Mandelbaum   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
443208c25fcSYitzhak Mandelbaum   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
444208c25fcSYitzhak Mandelbaum       Depth > MaxCompositeValueDepth)
445208c25fcSYitzhak Mandelbaum     return nullptr;
446208c25fcSYitzhak Mandelbaum 
4471e571585SStanislav Gatev   if (Type->isBooleanType()) {
4481e571585SStanislav Gatev     CreatedValuesCount++;
4491e571585SStanislav Gatev     return &makeAtomicBoolValue();
4501e571585SStanislav Gatev   }
4511e571585SStanislav Gatev 
452af7bc39bSStanislav Gatev   if (Type->isIntegerType()) {
453208c25fcSYitzhak Mandelbaum     CreatedValuesCount++;
454782eced5SStanislav Gatev     return &takeOwnership(std::make_unique<IntegerValue>());
455af7bc39bSStanislav Gatev   }
456af7bc39bSStanislav Gatev 
457af7bc39bSStanislav Gatev   if (Type->isReferenceType()) {
458208c25fcSYitzhak Mandelbaum     CreatedValuesCount++;
459a157d839SSimon Pilgrim     QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType();
460af7bc39bSStanislav Gatev     auto &PointeeLoc = createStorageLocation(PointeeType);
461af7bc39bSStanislav Gatev 
46280c12bdbSKazu Hirata     if (Visited.insert(PointeeType.getCanonicalType()).second) {
463208c25fcSYitzhak Mandelbaum       Value *PointeeVal = createValueUnlessSelfReferential(
464208c25fcSYitzhak Mandelbaum           PointeeType, Visited, Depth, CreatedValuesCount);
465af7bc39bSStanislav Gatev       Visited.erase(PointeeType.getCanonicalType());
466782eced5SStanislav Gatev 
467782eced5SStanislav Gatev       if (PointeeVal != nullptr)
468782eced5SStanislav Gatev         setValue(PointeeLoc, *PointeeVal);
469af7bc39bSStanislav Gatev     }
470af7bc39bSStanislav Gatev 
471782eced5SStanislav Gatev     return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc));
472af7bc39bSStanislav Gatev   }
473af7bc39bSStanislav Gatev 
474af7bc39bSStanislav Gatev   if (Type->isPointerType()) {
475208c25fcSYitzhak Mandelbaum     CreatedValuesCount++;
476a157d839SSimon Pilgrim     QualType PointeeType = Type->castAs<PointerType>()->getPointeeType();
477af7bc39bSStanislav Gatev     auto &PointeeLoc = createStorageLocation(PointeeType);
478af7bc39bSStanislav Gatev 
47980c12bdbSKazu Hirata     if (Visited.insert(PointeeType.getCanonicalType()).second) {
480208c25fcSYitzhak Mandelbaum       Value *PointeeVal = createValueUnlessSelfReferential(
481208c25fcSYitzhak Mandelbaum           PointeeType, Visited, Depth, CreatedValuesCount);
482af7bc39bSStanislav Gatev       Visited.erase(PointeeType.getCanonicalType());
483782eced5SStanislav Gatev 
484782eced5SStanislav Gatev       if (PointeeVal != nullptr)
485782eced5SStanislav Gatev         setValue(PointeeLoc, *PointeeVal);
486af7bc39bSStanislav Gatev     }
487af7bc39bSStanislav Gatev 
488782eced5SStanislav Gatev     return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc));
489af7bc39bSStanislav Gatev   }
490af7bc39bSStanislav Gatev 
491af7bc39bSStanislav Gatev   if (Type->isStructureOrClassType()) {
492208c25fcSYitzhak Mandelbaum     CreatedValuesCount++;
49399f7d55eSStanislav Gatev     // FIXME: Initialize only fields that are accessed in the context that is
49499f7d55eSStanislav Gatev     // being analyzed.
495af7bc39bSStanislav Gatev     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
49667136d0eSYitzhak Mandelbaum     for (const FieldDecl *Field : getObjectFields(Type)) {
497af7bc39bSStanislav Gatev       assert(Field != nullptr);
498af7bc39bSStanislav Gatev 
499af7bc39bSStanislav Gatev       QualType FieldType = Field->getType();
500af7bc39bSStanislav Gatev       if (Visited.contains(FieldType.getCanonicalType()))
501af7bc39bSStanislav Gatev         continue;
502af7bc39bSStanislav Gatev 
503af7bc39bSStanislav Gatev       Visited.insert(FieldType.getCanonicalType());
50418c84e2dSYitzhak Mandelbaum       if (auto *FieldValue = createValueUnlessSelfReferential(
50518c84e2dSYitzhak Mandelbaum               FieldType, Visited, Depth + 1, CreatedValuesCount))
50618c84e2dSYitzhak Mandelbaum         FieldValues.insert({Field, FieldValue});
507af7bc39bSStanislav Gatev       Visited.erase(FieldType.getCanonicalType());
508af7bc39bSStanislav Gatev     }
509af7bc39bSStanislav Gatev 
510782eced5SStanislav Gatev     return &takeOwnership(
511782eced5SStanislav Gatev         std::make_unique<StructValue>(std::move(FieldValues)));
512af7bc39bSStanislav Gatev   }
513af7bc39bSStanislav Gatev 
514af7bc39bSStanislav Gatev   return nullptr;
515af7bc39bSStanislav Gatev }
516af7bc39bSStanislav Gatev 
skip(StorageLocation & Loc,SkipPast SP) const517e7481f6eSStanislav Gatev StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
518e7481f6eSStanislav Gatev   switch (SP) {
519e7481f6eSStanislav Gatev   case SkipPast::None:
520e7481f6eSStanislav Gatev     return Loc;
521e7481f6eSStanislav Gatev   case SkipPast::Reference:
522e7481f6eSStanislav Gatev     // References cannot be chained so we only need to skip past one level of
523e7481f6eSStanislav Gatev     // indirection.
524e7481f6eSStanislav Gatev     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
52597d69cdaSWei Yi Tee       return Val->getReferentLoc();
526e7481f6eSStanislav Gatev     return Loc;
52799f7d55eSStanislav Gatev   case SkipPast::ReferenceThenPointer:
52899f7d55eSStanislav Gatev     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
52999f7d55eSStanislav Gatev     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
53099f7d55eSStanislav Gatev       return Val->getPointeeLoc();
53199f7d55eSStanislav Gatev     return LocPastRef;
532e7481f6eSStanislav Gatev   }
533e7481f6eSStanislav Gatev   llvm_unreachable("bad SkipPast kind");
534e7481f6eSStanislav Gatev }
535e7481f6eSStanislav Gatev 
skip(const StorageLocation & Loc,SkipPast SP) const536e7481f6eSStanislav Gatev const StorageLocation &Environment::skip(const StorageLocation &Loc,
537e7481f6eSStanislav Gatev                                          SkipPast SP) const {
538e7481f6eSStanislav Gatev   return skip(*const_cast<StorageLocation *>(&Loc), SP);
539e7481f6eSStanislav Gatev }
540e7481f6eSStanislav Gatev 
addToFlowCondition(BoolValue & Val)541ae60884dSStanislav Gatev void Environment::addToFlowCondition(BoolValue &Val) {
542955a05a2SStanislav Gatev   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
543ae60884dSStanislav Gatev }
544ae60884dSStanislav Gatev 
flowConditionImplies(BoolValue & Val) const5451e571585SStanislav Gatev bool Environment::flowConditionImplies(BoolValue &Val) const {
546955a05a2SStanislav Gatev   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
547ae60884dSStanislav Gatev }
548ae60884dSStanislav Gatev 
dump() const549b5414b56SDmitri Gribenko void Environment::dump() const {
550b5414b56SDmitri Gribenko   DACtx->dumpFlowCondition(*FlowConditionToken);
551b5414b56SDmitri Gribenko }
552b5414b56SDmitri Gribenko 
553af7bc39bSStanislav Gatev } // namespace dataflow
554af7bc39bSStanislav Gatev } // namespace clang
555