1 //===-- DataflowEnvironment.h -----------------------------------*- 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 #ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWENVIRONMENT_H
16 #define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWENVIRONMENT_H
17 
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/Type.h"
22 #include "clang/AST/TypeOrdering.h"
23 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
24 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
25 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
26 #include "clang/Analysis/FlowSensitive/Value.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include <memory>
30 #include <type_traits>
31 #include <utility>
32 
33 namespace clang {
34 namespace dataflow {
35 
36 /// Indicates what kind of indirections should be skipped past when retrieving
37 /// storage locations or values.
38 ///
39 /// FIXME: Consider renaming this or replacing it with a more appropriate model.
40 /// See the discussion in https://reviews.llvm.org/D116596 for context.
41 enum class SkipPast {
42   /// No indirections should be skipped past.
43   None,
44   /// An optional reference should be skipped past.
45   Reference,
46   /// An optional reference should be skipped past, then an optional pointer
47   /// should be skipped past.
48   ReferenceThenPointer,
49 };
50 
51 /// Holds the state of the program (store and heap) at a given program point.
52 ///
53 /// WARNING: Symbolic values that are created by the environment for static
54 /// local and global variables are not currently invalidated on function calls.
55 /// This is unsound and should be taken into account when designing dataflow
56 /// analyses.
57 class Environment {
58 public:
59   /// Supplements `Environment` with non-standard comparison and join
60   /// operations.
61   class ValueModel {
62   public:
63     virtual ~ValueModel() = default;
64 
65     /// Returns true if and only if `Val1` is equivalent to `Val2`.
66     ///
67     /// Requirements:
68     ///
69     ///  `Val1` and `Val2` must be distinct.
70     ///
71     ///  `Val1` and `Val2` must model values of type `Type`.
72     ///
73     ///  `Val1` and `Val2` must be assigned to the same storage location in
74     ///  `Env1` and `Env2` respectively.
75     virtual bool compareEquivalent(QualType Type, const Value &Val1,
76                                    const Environment &Env1, const Value &Val2,
77                                    const Environment &Env2) {
78       // FIXME: Consider adding QualType to StructValue and removing the Type
79       // argument here.
80       //
81       // FIXME: default to a sound comparison and/or expand the comparison logic
82       // built into the framework to support broader forms of equivalence than
83       // strict pointer equality.
84       return true;
85     }
86 
87     /// Modifies `MergedVal` to approximate both `Val1` and `Val2`. This could
88     /// be a strict lattice join or a more general widening operation.
89     ///
90     /// If this function returns true, `MergedVal` will be assigned to a storage
91     /// location of type `Type` in `MergedEnv`.
92     ///
93     /// `Env1` and `Env2` can be used to query child values and path condition
94     /// implications of `Val1` and `Val2` respectively.
95     ///
96     /// Requirements:
97     ///
98     ///  `Val1` and `Val2` must be distinct.
99     ///
100     ///  `Val1`, `Val2`, and `MergedVal` must model values of type `Type`.
101     ///
102     ///  `Val1` and `Val2` must be assigned to the same storage location in
103     ///  `Env1` and `Env2` respectively.
104     virtual bool merge(QualType Type, const Value &Val1,
105                        const Environment &Env1, const Value &Val2,
106                        const Environment &Env2, Value &MergedVal,
107                        Environment &MergedEnv) {
108       return true;
109     }
110   };
111 
112   /// Creates an environment that uses `DACtx` to store objects that encompass
113   /// the state of a program.
114   explicit Environment(DataflowAnalysisContext &DACtx) : DACtx(&DACtx) {}
115 
116   /// Creates an environment that uses `DACtx` to store objects that encompass
117   /// the state of a program.
118   ///
119   /// If `DeclCtx` is a function, initializes the environment with symbolic
120   /// representations of the function parameters.
121   ///
122   /// If `DeclCtx` is a non-static member function, initializes the environment
123   /// with a symbolic representation of the `this` pointee.
124   Environment(DataflowAnalysisContext &DACtx, const DeclContext &DeclCtx);
125 
126   /// Returns true if and only if the environment is equivalent to `Other`, i.e
127   /// the two environments:
128   ///  - have the same mappings from declarations to storage locations,
129   ///  - have the same mappings from expressions to storage locations,
130   ///  - have the same or equivalent (according to `Model`) values assigned to
131   ///    the same storage locations.
132   ///
133   /// Requirements:
134   ///
135   ///  `Other` and `this` must use the same `DataflowAnalysisContext`.
136   bool equivalentTo(const Environment &Other,
137                     Environment::ValueModel &Model) const;
138 
139   /// Joins the environment with `Other` by taking the intersection of storage
140   /// locations and values that are stored in them. Distinct values that are
141   /// assigned to the same storage locations in the environment and `Other` are
142   /// merged using `Model`.
143   ///
144   /// Requirements:
145   ///
146   ///  `Other` and `this` must use the same `DataflowAnalysisContext`.
147   LatticeJoinEffect join(const Environment &Other,
148                          Environment::ValueModel &Model);
149 
150   // FIXME: Rename `createOrGetStorageLocation` to `getOrCreateStorageLocation`,
151   // `getStableStorageLocation`, or something more appropriate.
152 
153   /// Creates a storage location appropriate for `Type`. Does not assign a value
154   /// to the returned storage location in the environment.
155   ///
156   /// Requirements:
157   ///
158   ///  `Type` must not be null.
159   StorageLocation &createStorageLocation(QualType Type);
160 
161   /// Creates a storage location for `D`. Does not assign the returned storage
162   /// location to `D` in the environment. Does not assign a value to the
163   /// returned storage location in the environment.
164   StorageLocation &createStorageLocation(const VarDecl &D);
165 
166   /// Creates a storage location for `E`. Does not assign the returned storage
167   /// location to `E` in the environment. Does not assign a value to the
168   /// returned storage location in the environment.
169   StorageLocation &createStorageLocation(const Expr &E);
170 
171   /// Assigns `Loc` as the storage location of `D` in the environment.
172   ///
173   /// Requirements:
174   ///
175   ///  `D` must not be assigned a storage location in the environment.
176   void setStorageLocation(const ValueDecl &D, StorageLocation &Loc);
177 
178   /// Returns the storage location assigned to `D` in the environment, applying
179   /// the `SP` policy for skipping past indirections, or null if `D` isn't
180   /// assigned a storage location in the environment.
181   StorageLocation *getStorageLocation(const ValueDecl &D, SkipPast SP) const;
182 
183   /// Assigns `Loc` as the storage location of `E` in the environment.
184   ///
185   /// Requirements:
186   ///
187   ///  `E` must not be assigned a storage location in the environment.
188   void setStorageLocation(const Expr &E, StorageLocation &Loc);
189 
190   /// Returns the storage location assigned to `E` in the environment, applying
191   /// the `SP` policy for skipping past indirections, or null if `E` isn't
192   /// assigned a storage location in the environment.
193   StorageLocation *getStorageLocation(const Expr &E, SkipPast SP) const;
194 
195   /// Returns the storage location assigned to the `this` pointee in the
196   /// environment or null if the `this` pointee has no assigned storage location
197   /// in the environment.
198   StorageLocation *getThisPointeeStorageLocation() const;
199 
200   /// Creates a value appropriate for `Type`, if `Type` is supported, otherwise
201   /// return null. If `Type` is a pointer or reference type, creates all the
202   /// necessary storage locations and values for indirections until it finds a
203   /// non-pointer/non-reference type.
204   ///
205   /// Requirements:
206   ///
207   ///  `Type` must not be null.
208   Value *createValue(QualType Type);
209 
210   /// Assigns `Val` as the value of `Loc` in the environment.
211   void setValue(const StorageLocation &Loc, Value &Val);
212 
213   /// Returns the value assigned to `Loc` in the environment or null if `Loc`
214   /// isn't assigned a value in the environment.
215   Value *getValue(const StorageLocation &Loc) const;
216 
217   /// Equivalent to `getValue(getStorageLocation(D, SP), SkipPast::None)` if `D`
218   /// is assigned a storage location in the environment, otherwise returns null.
219   Value *getValue(const ValueDecl &D, SkipPast SP) const;
220 
221   /// Equivalent to `getValue(getStorageLocation(E, SP), SkipPast::None)` if `E`
222   /// is assigned a storage location in the environment, otherwise returns null.
223   Value *getValue(const Expr &E, SkipPast SP) const;
224 
225   /// Transfers ownership of `Loc` to the analysis context and returns a
226   /// reference to it.
227   ///
228   /// Requirements:
229   ///
230   ///  `Loc` must not be null.
231   template <typename T>
232   typename std::enable_if<std::is_base_of<StorageLocation, T>::value, T &>::type
233   takeOwnership(std::unique_ptr<T> Loc) {
234     return DACtx->takeOwnership(std::move(Loc));
235   }
236 
237   /// Transfers ownership of `Val` to the analysis context and returns a
238   /// reference to it.
239   ///
240   /// Requirements:
241   ///
242   ///  `Val` must not be null.
243   template <typename T>
244   typename std::enable_if<std::is_base_of<Value, T>::value, T &>::type
245   takeOwnership(std::unique_ptr<T> Val) {
246     return DACtx->takeOwnership(std::move(Val));
247   }
248 
249   /// Returns a symbolic boolean value that models a boolean literal equal to
250   /// `Value`
251   AtomicBoolValue &getBoolLiteralValue(bool Value) const {
252     return DACtx->getBoolLiteralValue(Value);
253   }
254 
255   /// Returns an atomic boolean value.
256   BoolValue &makeAtomicBoolValue() const {
257     return DACtx->createAtomicBoolValue();
258   }
259 
260   /// Returns a boolean value that represents the conjunction of `LHS` and
261   /// `RHS`. Subsequent calls with the same arguments, regardless of their
262   /// order, will return the same result. If the given boolean values represent
263   /// the same value, the result will be the value itself.
264   BoolValue &makeAnd(BoolValue &LHS, BoolValue &RHS) const {
265     return DACtx->getOrCreateConjunctionValue(LHS, RHS);
266   }
267 
268   /// Returns a boolean value that represents the disjunction of `LHS` and
269   /// `RHS`. Subsequent calls with the same arguments, regardless of their
270   /// order, will return the same result. If the given boolean values represent
271   /// the same value, the result will be the value itself.
272   BoolValue &makeOr(BoolValue &LHS, BoolValue &RHS) const {
273     return DACtx->getOrCreateDisjunctionValue(LHS, RHS);
274   }
275 
276   /// Returns a boolean value that represents the negation of `Val`. Subsequent
277   /// calls with the same argument will return the same result.
278   BoolValue &makeNot(BoolValue &Val) const {
279     return DACtx->getOrCreateNegationValue(Val);
280   }
281 
282   /// Returns a boolean value represents `LHS` => `RHS`. Subsequent calls with
283   /// the same arguments, regardless of their order, will return the same
284   /// result. If the given boolean values represent the same value, the result
285   /// will be a value that represents the true boolean literal.
286   BoolValue &makeImplication(BoolValue &LHS, BoolValue &RHS) const {
287     return &LHS == &RHS ? getBoolLiteralValue(true) : makeOr(makeNot(LHS), RHS);
288   }
289 
290   /// Returns a boolean value represents `LHS` <=> `RHS`. Subsequent calls with
291   /// the same arguments, regardless of their order, will return the same
292   /// result. If the given boolean values represent the same value, the result
293   /// will be a value that represents the true boolean literal.
294   BoolValue &makeIff(BoolValue &LHS, BoolValue &RHS) const {
295     return &LHS == &RHS
296                ? getBoolLiteralValue(true)
297                : makeAnd(makeImplication(LHS, RHS), makeImplication(RHS, LHS));
298   }
299 
300   const llvm::DenseSet<BoolValue *> &getFlowConditionConstraints() const {
301     return FlowConditionConstraints;
302   }
303 
304   /// Adds `Val` to the set of clauses that constitute the flow condition.
305   void addToFlowCondition(BoolValue &Val);
306 
307   /// Returns true if and only if the clauses that constitute the flow condition
308   /// imply that `Val` is true.
309   bool flowConditionImplies(BoolValue &Val) const;
310 
311 private:
312   /// Creates a value appropriate for `Type`, if `Type` is supported, otherwise
313   /// return null.
314   ///
315   /// Recursively initializes storage locations and values until it sees a
316   /// self-referential pointer or reference type. `Visited` is used to track
317   /// which types appeared in the reference/pointer chain in order to avoid
318   /// creating a cyclic dependency with self-referential pointers/references.
319   ///
320   /// Requirements:
321   ///
322   ///  `Type` must not be null.
323   Value *createValueUnlessSelfReferential(QualType Type,
324                                           llvm::DenseSet<QualType> &Visited,
325                                           int Depth, int &CreatedValuesCount);
326 
327   StorageLocation &skip(StorageLocation &Loc, SkipPast SP) const;
328   const StorageLocation &skip(const StorageLocation &Loc, SkipPast SP) const;
329 
330   // `DACtx` is not null and not owned by this object.
331   DataflowAnalysisContext *DACtx;
332 
333   // Maps from program declarations and statements to storage locations that are
334   // assigned to them. Unlike the maps in `DataflowAnalysisContext`, these
335   // include only storage locations that are in scope for a particular basic
336   // block.
337   llvm::DenseMap<const ValueDecl *, StorageLocation *> DeclToLoc;
338   llvm::DenseMap<const Expr *, StorageLocation *> ExprToLoc;
339 
340   llvm::DenseMap<const StorageLocation *, Value *> LocToVal;
341 
342   // Maps locations of struct members to symbolic values of the structs that own
343   // them and the decls of the struct members.
344   llvm::DenseMap<const StorageLocation *,
345                  std::pair<StructValue *, const ValueDecl *>>
346       MemberLocToStruct;
347 
348   llvm::DenseSet<BoolValue *> FlowConditionConstraints;
349 };
350 
351 } // namespace dataflow
352 } // namespace clang
353 
354 #endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWENVIRONMENT_H
355