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