clang 24.0.0git
RegionStore.cpp
Go to the documentation of this file.
1//== RegionStore.cpp - Field-sensitive store model --------------*- 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 a basic region store model. In this model, we do have field
10// sensitivity. But we assume nothing about the heap shape. So recursive data
11// structures are largely ignored. Basically we do 1-limiting analysis.
12// Parameter pointers are assumed with no aliasing. Pointee objects of
13// parameters are created lazily.
14//
15//===----------------------------------------------------------------------===//
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/CharUnits.h"
28#include "llvm/ADT/ImmutableMap.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/Support/TimeProfiler.h"
31#include "llvm/Support/raw_ostream.h"
32#include <limits>
33#include <optional>
34#include <utility>
35
36using namespace clang;
37using namespace ento;
38
39//===----------------------------------------------------------------------===//
40// Representation of binding keys.
41//===----------------------------------------------------------------------===//
42
43namespace {
44class BindingKey {
45public:
46 enum Kind {
47 Default = 0x0,
48 Direct = 0x1,
49 Symbolic = 0x2,
50 };
51
52private:
53 llvm::PointerIntPair<const MemRegion *, 2> P;
54 uint64_t Data;
55
56 /// Create a key for a binding to region \p r, which has a symbolic offset
57 /// from region \p Base.
58 explicit BindingKey(const SubRegion *r, const SubRegion *Base, Kind k)
59 : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) {
60 assert(r && Base && "Must have known regions.");
61 assert(getConcreteOffsetRegion() == Base && "Failed to store base region");
62 }
63
64 /// Create a key for a binding at \p offset from base region \p r.
65 explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
66 : P(r, k), Data(offset) {
67 assert(r && "Must have known regions.");
68 assert(getOffset() == offset && "Failed to store offset");
69 assert((r == r->getBaseRegion() ||
71 "Not a base");
72 }
73
74public:
75 bool isDirect() const { return P.getInt() & Direct; }
76 bool isDefault() const { return !isDirect(); }
77 bool hasSymbolicOffset() const { return P.getInt() & Symbolic; }
78
79 const MemRegion *getRegion() const { return P.getPointer(); }
80 uint64_t getOffset() const {
81 assert(!hasSymbolicOffset());
82 return Data;
83 }
84
85 const SubRegion *getConcreteOffsetRegion() const {
86 assert(hasSymbolicOffset());
87 return reinterpret_cast<const SubRegion *>(static_cast<uintptr_t>(Data));
88 }
89
90 const MemRegion *getBaseRegion() const {
91 if (hasSymbolicOffset())
92 return getConcreteOffsetRegion()->getBaseRegion();
93 return getRegion()->getBaseRegion();
94 }
95
96 void Profile(llvm::FoldingSetNodeID& ID) const {
97 ID.AddPointer(P.getOpaqueValue());
98 ID.AddInteger(Data);
99 }
100
101 static BindingKey Make(const MemRegion *R, Kind k);
102
103 bool operator<(const BindingKey &X) const {
104 if (P.getOpaqueValue() < X.P.getOpaqueValue())
105 return true;
106 if (P.getOpaqueValue() > X.P.getOpaqueValue())
107 return false;
108 return Data < X.Data;
109 }
110
111 bool operator==(const BindingKey &X) const {
112 return P.getOpaqueValue() == X.P.getOpaqueValue() &&
113 Data == X.Data;
114 }
115
116 LLVM_DUMP_METHOD void dump() const;
117};
118
119std::string locDescr(Loc L) {
120 std::string S;
121 llvm::raw_string_ostream OS(S);
122 L.dumpToStream(OS);
123 return OS.str();
124}
125} // end anonymous namespace
126
127BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
128 const RegionOffset &RO = R->getAsOffset();
129 if (RO.hasSymbolicOffset())
130 return BindingKey(cast<SubRegion>(R), cast<SubRegion>(RO.getRegion()), k);
131
132 return BindingKey(RO.getRegion(), RO.getOffset(), k);
133}
134
135namespace llvm {
136static inline raw_ostream &operator<<(raw_ostream &Out, BindingKey K) {
137 Out << "\"kind\": \"" << (K.isDirect() ? "Direct" : "Default")
138 << "\", \"offset\": ";
139
140 if (!K.hasSymbolicOffset())
141 Out << K.getOffset();
142 else
143 Out << "null";
144
145 return Out;
146}
147
148} // namespace llvm
149
150#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
151void BindingKey::dump() const { llvm::errs() << *this; }
152#endif
153
154//===----------------------------------------------------------------------===//
155// Actual Store type.
156//===----------------------------------------------------------------------===//
157
158typedef llvm::ImmutableMap<BindingKey, SVal> ClusterBindings;
159typedef llvm::ImmutableMapRef<BindingKey, SVal> ClusterBindingsRef;
160typedef std::pair<BindingKey, SVal> BindingPair;
161
162typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings>
164
165namespace {
166class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *,
167 ClusterBindings> {
168 ClusterBindings::Factory *CBFactory;
169
170 // This flag indicates whether the current bindings are within the analysis
171 // that has started from main(). It affects how we perform loads from
172 // global variables that have initializers: if we have observed the
173 // program execution from the start and we know that these variables
174 // have not been overwritten yet, we can be sure that their initializers
175 // are still relevant. This flag never gets changed when the bindings are
176 // updated, so it could potentially be moved into RegionStoreManager
177 // (as if it's the same bindings but a different loading procedure)
178 // however that would have made the manager needlessly stateful.
179 bool IsMainAnalysis;
180
181public:
182 typedef llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>
183 ParentTy;
184
185 RegionBindingsRef(ClusterBindings::Factory &CBFactory,
186 const RegionBindings::TreeTy *T,
187 RegionBindings::TreeTy::Factory *F, bool IsMainAnalysis)
188 : RegionBindingsRef(ParentTy(T, F), CBFactory, IsMainAnalysis) {}
189
190 RegionBindingsRef(const ParentTy &P, ClusterBindings::Factory &CBFactory,
191 bool IsMainAnalysis)
192 : ParentTy(P), CBFactory(&CBFactory), IsMainAnalysis(IsMainAnalysis) {}
193
194 RegionBindingsRef removeCluster(const MemRegion *BaseRegion) const {
195 return RegionBindingsRef(ParentTy::remove(BaseRegion), *CBFactory,
196 IsMainAnalysis);
197 }
198
199 template <typename PredFn>
200 RegionBindingsRef filterClusters(PredFn Pred) const {
201 return RegionBindingsRef(ParentTy::filter(Pred), *CBFactory,
202 IsMainAnalysis);
203 }
204
205 RegionBindingsRef addBinding(BindingKey K, SVal V) const;
206
207 RegionBindingsRef addBinding(const MemRegion *R,
208 BindingKey::Kind k, SVal V) const;
209
210 const SVal *lookup(BindingKey K) const;
211 const SVal *lookup(const MemRegion *R, BindingKey::Kind k) const;
212 using llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>::lookup;
213
214 RegionBindingsRef removeBinding(BindingKey K);
215
216 RegionBindingsRef removeBinding(const MemRegion *R,
217 BindingKey::Kind k);
218
219 RegionBindingsRef removeBinding(const MemRegion *R) {
220 return removeBinding(R, BindingKey::Direct).
221 removeBinding(R, BindingKey::Default);
222 }
223
224 std::optional<SVal> getDirectBinding(const MemRegion *R) const;
225
226 /// getDefaultBinding - Returns an SVal* representing an optional default
227 /// binding associated with a region and its subregions.
228 std::optional<SVal> getDefaultBinding(const MemRegion *R) const;
229
230 /// Return the internal tree as a Store.
231 Store asStore() const {
232 llvm::PointerIntPair<Store, 1, bool> Ptr = {
233 asImmutableMap().getRootWithoutRetain(), IsMainAnalysis};
234 return reinterpret_cast<Store>(Ptr.getOpaqueValue());
235 }
236
237 bool isMainAnalysis() const {
238 return IsMainAnalysis;
239 }
240
241 void printJson(raw_ostream &Out, const char *NL = "\n",
242 unsigned int Space = 0, bool IsDot = false) const {
243 using namespace llvm;
244 DenseMap<const MemRegion *, std::string> StringifyCache;
245 auto ToString = [&StringifyCache](const MemRegion *R) {
246 auto [Place, Inserted] = StringifyCache.try_emplace(R);
247 if (!Inserted)
248 return Place->second;
249 std::string Res;
250 raw_string_ostream OS(Res);
251 OS << R;
252 Place->second = Res;
253 return Res;
254 };
255
256 using Cluster =
257 std::pair<const MemRegion *, ImmutableMap<BindingKey, SVal>>;
258 using Binding = std::pair<BindingKey, SVal>;
259
260 const auto MemSpaceBeforeRegionName = [&ToString](const Cluster *L,
261 const Cluster *R) {
262 if (isa<MemSpaceRegion>(L->first) && !isa<MemSpaceRegion>(R->first))
263 return true;
264 if (!isa<MemSpaceRegion>(L->first) && isa<MemSpaceRegion>(R->first))
265 return false;
266 return ToString(L->first) < ToString(R->first);
267 };
268
269 const auto SymbolicBeforeOffset = [&ToString](const BindingKey &L,
270 const BindingKey &R) {
271 if (L.hasSymbolicOffset() && !R.hasSymbolicOffset())
272 return true;
273 if (!L.hasSymbolicOffset() && R.hasSymbolicOffset())
274 return false;
275 if (L.hasSymbolicOffset() && R.hasSymbolicOffset())
276 return ToString(L.getRegion()) < ToString(R.getRegion());
277 return L.getOffset() < R.getOffset();
278 };
279
280 const auto DefaultBindingBeforeDirectBindings =
281 [&SymbolicBeforeOffset](const Binding *LPtr, const Binding *RPtr) {
282 const BindingKey &L = LPtr->first;
283 const BindingKey &R = RPtr->first;
284 if (L.isDefault() && !R.isDefault())
285 return true;
286 if (!L.isDefault() && R.isDefault())
287 return false;
288 assert(L.isDefault() == R.isDefault());
289 return SymbolicBeforeOffset(L, R);
290 };
291
292 const auto AddrOf = [](const auto &Item) { return &Item; };
293
294 std::vector<const Cluster *> SortedClusters;
295 SortedClusters.reserve(std::distance(begin(), end()));
296 append_range(SortedClusters, map_range(*this, AddrOf));
297 llvm::sort(SortedClusters, MemSpaceBeforeRegionName);
298
299 for (auto [Idx, C] : llvm::enumerate(SortedClusters)) {
300 const auto &[BaseRegion, Bindings] = *C;
301 Indent(Out, Space, IsDot)
302 << "{ \"cluster\": \"" << BaseRegion << "\", \"pointer\": \""
303 << (const void *)BaseRegion << "\", \"items\": [" << NL;
304
305 std::vector<const Binding *> SortedBindings;
306 SortedBindings.reserve(std::distance(Bindings.begin(), Bindings.end()));
307 append_range(SortedBindings, map_range(Bindings, AddrOf));
308 llvm::sort(SortedBindings, DefaultBindingBeforeDirectBindings);
309
310 ++Space;
311 for (auto [Idx, B] : llvm::enumerate(SortedBindings)) {
312 const auto &[Key, Value] = *B;
313 Indent(Out, Space, IsDot) << "{ " << Key << ", \"value\": ";
314 Value.printJson(Out, /*AddQuotes=*/true);
315 Out << " }";
316 if (Idx != SortedBindings.size() - 1)
317 Out << ',';
318 Out << NL;
319 }
320 --Space;
321 Indent(Out, Space, IsDot) << "]}";
322 if (Idx != SortedClusters.size() - 1)
323 Out << ',';
324 Out << NL;
325 }
326 }
327
328 LLVM_DUMP_METHOD void dump() const { printJson(llvm::errs()); }
329
330protected:
331 RegionBindingsRef
332 commitBindingsToCluster(const MemRegion *BaseRegion,
333 const ClusterBindings &Bindings) const;
334};
335} // end anonymous namespace
336
337/// This class represents the same as \c RegionBindingsRef, but with a limit on
338/// the number of bindings that can be added.
339class LimitedRegionBindingsRef : public RegionBindingsRef {
340public:
342 SmallVectorImpl<SVal> &EscapedValuesDuringBind,
343 std::optional<unsigned> BindingsLeft)
344 : RegionBindingsRef(Base),
345 EscapedValuesDuringBind(&EscapedValuesDuringBind),
346 BindingsLeft(BindingsLeft) {}
347
349 return BindingsLeft.has_value() && BindingsLeft.value() == 0;
350 }
351
353 EscapedValuesDuringBind->push_back(V);
354 return *this;
355 }
356
360 for (SVal V : llvm::make_range(Begin, End))
362 return *this;
363 }
364
367 data_type_ref BindingKeyAndValue) const {
368 return LimitedRegionBindingsRef{RegionBindingsRef::commitBindingsToCluster(
369 BaseRegion, BindingKeyAndValue),
370 *EscapedValuesDuringBind, BindingsLeft};
371 }
372
375 RegionBindingsRef::removeCluster(BaseRegion), *EscapedValuesDuringBind,
376 BindingsLeft};
377 }
378
380 std::optional<unsigned> NewBindingsLeft = BindingsLeft;
381 if (NewBindingsLeft.has_value()) {
382 assert(NewBindingsLeft.value() != 0);
383 NewBindingsLeft.value() -= 1;
384
385 // If we just exhausted the binding limit, highjack
386 // this bind call for the default binding.
387 if (NewBindingsLeft.value() == 0) {
389 K = BindingKey::Make(K.getRegion(), BindingKey::Default);
390 V = UnknownVal();
391 }
392 }
393
394 return LimitedRegionBindingsRef{RegionBindingsRef::addBinding(K, V),
395 *EscapedValuesDuringBind, NewBindingsLeft};
396 }
397
398 LimitedRegionBindingsRef addBinding(const MemRegion *R, BindingKey::Kind k,
399 SVal V) const {
400 return addBinding(BindingKey::Make(R, k), V);
401 }
402
403private:
404 SmallVectorImpl<SVal> *EscapedValuesDuringBind; // nonnull
405 std::optional<unsigned> BindingsLeft;
406};
407
408typedef const RegionBindingsRef& RegionBindingsConstRef;
410
411std::optional<SVal>
412RegionBindingsRef::getDirectBinding(const MemRegion *R) const {
413 const SVal *V = lookup(R, BindingKey::Direct);
414 return V ? std::optional<SVal>(*V) : std::nullopt;
415}
416
417std::optional<SVal>
418RegionBindingsRef::getDefaultBinding(const MemRegion *R) const {
419 const SVal *V = lookup(R, BindingKey::Default);
420 return V ? std::optional<SVal>(*V) : std::nullopt;
421}
422
423RegionBindingsRef RegionBindingsRef::commitBindingsToCluster(
424 const MemRegion *BaseRegion, const ClusterBindings &Bindings) const {
425 return RegionBindingsRef(ParentTy::add(BaseRegion, Bindings), *CBFactory,
426 IsMainAnalysis);
427}
428
429RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const {
430 const MemRegion *Base = K.getBaseRegion();
431
432 const ClusterBindings *ExistingCluster = lookup(Base);
434 (ExistingCluster ? *ExistingCluster : CBFactory->getEmptyMap());
435 Bindings = CBFactory->add(Bindings, K, V);
436 return commitBindingsToCluster(Base, Bindings);
437}
438
439RegionBindingsRef RegionBindingsRef::addBinding(const MemRegion *R,
440 BindingKey::Kind k,
441 SVal V) const {
442 return addBinding(BindingKey::Make(R, k), V);
443}
444
445const SVal *RegionBindingsRef::lookup(BindingKey K) const {
446 const ClusterBindings *Cluster = lookup(K.getBaseRegion());
447 if (!Cluster)
448 return nullptr;
449 return Cluster->lookup(K);
450}
451
452const SVal *RegionBindingsRef::lookup(const MemRegion *R,
453 BindingKey::Kind k) const {
454 return lookup(BindingKey::Make(R, k));
455}
456
457RegionBindingsRef RegionBindingsRef::removeBinding(BindingKey K) {
458 const MemRegion *Base = K.getBaseRegion();
459 const ClusterBindings *Cluster = lookup(Base);
460 if (!Cluster)
461 return *this;
462
463 ClusterBindings NewCluster = CBFactory->remove(*Cluster, K);
464 if (NewCluster.isEmpty())
465 return removeCluster(Base);
466 return commitBindingsToCluster(Base, NewCluster);
467}
468
469RegionBindingsRef RegionBindingsRef::removeBinding(const MemRegion *R,
470 BindingKey::Kind k){
471 return removeBinding(BindingKey::Make(R, k));
472}
473
474//===----------------------------------------------------------------------===//
475// Main RegionStore logic.
476//===----------------------------------------------------------------------===//
477
478namespace {
479class InvalidateRegionsWorker;
480
481class RegionStoreManager final : public StoreManager {
482public:
483 RegionBindings::Factory RBFactory;
484 mutable ClusterBindings::Factory CBFactory;
485
486 typedef std::vector<SVal> SValListTy;
487private:
488 typedef llvm::DenseMap<const LazyCompoundValData *,
489 SValListTy> LazyBindingsMapTy;
490 LazyBindingsMapTy LazyBindingsMap;
491
492 /// The largest number of fields a struct can have and still be
493 /// considered "small".
494 ///
495 /// This is currently used to decide whether or not it is worth "forcing" a
496 /// LazyCompoundVal on bind.
497 ///
498 /// This is controlled by 'region-store-small-struct-limit' option.
499 /// To disable all small-struct-dependent behavior, set the option to "0".
500 const unsigned SmallStructLimit;
501
502 /// The largest number of element an array can have and still be
503 /// considered "small".
504 ///
505 /// This is currently used to decide whether or not it is worth "forcing" a
506 /// LazyCompoundVal on bind.
507 ///
508 /// This is controlled by 'region-store-small-struct-limit' option.
509 /// To disable all small-struct-dependent behavior, set the option to "0".
510 const unsigned SmallArrayLimit;
511
512 /// The number of bindings a single bind operation can scatter into.
513 /// For example, binding the initializer-list of an array would recurse and
514 /// bind all the individual array elements, potentially causing scalability
515 /// issues. Nullopt if the limit is disabled.
516 const std::optional<unsigned> RegionStoreMaxBindingFanOutPlusOne;
517
518 /// A helper used to populate the work list with the given set of
519 /// regions.
520 void populateWorkList(InvalidateRegionsWorker &W,
521 ArrayRef<SVal> Values,
522 InvalidatedRegions *TopLevelRegions);
523
524 const AnalyzerOptions &getOptions() {
525 return StateMgr.getOwningEngine().getAnalysisManager().options;
526 }
527
528public:
529 RegionStoreManager(ProgramStateManager &mgr)
530 : StoreManager(mgr), RBFactory(mgr.getAllocator()),
531 CBFactory(mgr.getAllocator()),
532 SmallStructLimit(getOptions().RegionStoreSmallStructLimit),
533 SmallArrayLimit(getOptions().RegionStoreSmallArrayLimit),
534 RegionStoreMaxBindingFanOutPlusOne([&]() -> std::optional<unsigned> {
535 unsigned FanOut = getOptions().RegionStoreMaxBindingFanOut;
536 assert(FanOut != std::numeric_limits<unsigned>::max());
537 if (FanOut == 0)
538 return std::nullopt;
539 return FanOut + 1 /*for the default binding*/;
540 }()) {}
541
542 /// setImplicitDefaultValue - Set the default binding for the provided
543 /// MemRegion to the value implicitly defined for compound literals when
544 /// the value is not specified.
545 LimitedRegionBindingsRef
546 setImplicitDefaultValue(LimitedRegionBindingsConstRef B, const MemRegion *R,
547 QualType T);
548
549 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
550 /// type. 'Array' represents the lvalue of the array being decayed
551 /// to a pointer, and the returned SVal represents the decayed
552 /// version of that lvalue (i.e., a pointer to the first element of
553 /// the array). This is called by ExprEngine when evaluating
554 /// casts from arrays to pointers.
555 SVal ArrayToPointer(Loc Array, QualType ElementTy) override;
556
557 /// Creates the Store that correctly represents memory contents before
558 /// the beginning of the analysis of the given top-level stack frame.
559 StoreRef getInitialStore(const StackFrame *SF) override {
560 bool IsMainAnalysis = false;
561 if (const auto *FD = dyn_cast<FunctionDecl>(SF->getDecl()))
562 IsMainAnalysis = FD->isMain() && !Ctx.getLangOpts().CPlusPlus;
563 return StoreRef(RegionBindingsRef(RegionBindingsRef::ParentTy(
564 RBFactory.getEmptyMap(), RBFactory),
565 CBFactory, IsMainAnalysis)
566 .asStore(),
567 *this);
568 }
569
570 //===-------------------------------------------------------------------===//
571 // Binding values to regions.
572 //===-------------------------------------------------------------------===//
573 RegionBindingsRef invalidateGlobalRegion(MemRegion::Kind K,
575 unsigned Count, const StackFrame *SF,
576 RegionBindingsRef B,
577 InvalidatedRegions *Invalidated);
578
579 StoreRef invalidateRegions(Store store, ArrayRef<SVal> Values,
580 ConstCFGElementRef Elem, unsigned Count,
581 const StackFrame *SF, const CallEvent *Call,
583 RegionAndSymbolInvalidationTraits &ITraits,
584 InvalidatedRegions *Invalidated,
585 InvalidatedRegions *InvalidatedTopLevel) override;
586
587 bool scanReachableSymbols(Store S, const MemRegion *R,
588 ScanReachableSymbols &Callbacks) override;
589
590 LimitedRegionBindingsRef
591 removeSubRegionBindings(LimitedRegionBindingsConstRef B, const SubRegion *R);
592 std::optional<SVal>
593 getConstantValFromConstArrayInitializer(RegionBindingsConstRef B,
594 const ElementRegion *R);
595 std::optional<SVal> getConstantValFromInitializer(const FieldRegion *R,
596 bool IsMainAnalysis);
597 std::optional<SVal>
598 getSValFromInitListExpr(const InitListExpr *ILE,
599 const SmallVector<uint64_t, 2> &ConcreteOffsets,
600 QualType ElemT);
601 SVal getSValFromStringLiteral(const StringLiteral *SL, uint64_t Offset,
602 QualType ElemT);
603
604public: // Part of public interface to class.
605 BindResult Bind(Store store, Loc LV, SVal V) override {
606 llvm::SmallVector<SVal, 0> EscapedValuesDuringBind;
607 LimitedRegionBindingsRef BoundedBindings =
608 getRegionBindings(store, EscapedValuesDuringBind);
609 return BindResult{StoreRef(bind(BoundedBindings, LV, V).asStore(), *this),
610 std::move(EscapedValuesDuringBind)};
611 }
612
613 LimitedRegionBindingsRef bind(LimitedRegionBindingsConstRef B, Loc LV,
614 SVal V);
615
616 // BindDefaultInitial is only used to initialize a region with
617 // a default value.
618 BindResult BindDefaultInitial(Store store, const MemRegion *R,
619 SVal V) override {
620 RegionBindingsRef B = getRegionBindings(store);
621 // Use other APIs when you have to wipe the region that was initialized
622 // earlier.
623 assert(!(B.getDefaultBinding(R) || B.getDirectBinding(R)) &&
624 "Double initialization!");
625 B = B.addBinding(BindingKey::Make(R, BindingKey::Default), V);
626 return BindResult{
627 StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this), {}};
628 }
629
630 // BindDefaultZero is used for zeroing constructors that may accidentally
631 // overwrite existing bindings.
632 BindResult BindDefaultZero(Store store, const MemRegion *R) override {
633 // FIXME: The offsets of empty bases can be tricky because of
634 // of the so called "empty base class optimization".
635 // If a base class has been optimized out
636 // we should not try to create a binding, otherwise we should.
637 // Unfortunately, at the moment ASTRecordLayout doesn't expose
638 // the actual sizes of the empty bases
639 // and trying to infer them from offsets/alignments
640 // seems to be error-prone and non-trivial because of the trailing padding.
641 // As a temporary mitigation we don't create bindings for empty bases.
642 if (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R))
643 if (BR->getDecl()->isEmpty())
644 return BindResult{StoreRef(store, *this), {}};
645
646 llvm::SmallVector<SVal, 0> EscapedValuesDuringBind;
647 LimitedRegionBindingsRef B =
648 getRegionBindings(store, EscapedValuesDuringBind);
649 SVal V = svalBuilder.makeZeroVal(Ctx.CharTy);
650 B = removeSubRegionBindings(B, cast<SubRegion>(R));
651 B = B.addBinding(BindingKey::Make(R, BindingKey::Default), V);
652 return BindResult{
653 StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this),
654 std::move(EscapedValuesDuringBind)};
655 }
656
657 /// Attempt to extract the fields of \p LCV and bind them to the struct region
658 /// \p R.
659 ///
660 /// This path is used when it seems advantageous to "force" loading the values
661 /// within a LazyCompoundVal to bind memberwise to the struct region, rather
662 /// than using a Default binding at the base of the entire region. This is a
663 /// heuristic attempting to avoid building long chains of LazyCompoundVals.
664 ///
665 /// \returns The updated store bindings, or \c std::nullopt if binding
666 /// non-lazily would be too expensive.
667 std::optional<LimitedRegionBindingsRef>
668 tryBindSmallStruct(LimitedRegionBindingsConstRef B, const TypedValueRegion *R,
669 const RecordDecl *RD, nonloc::LazyCompoundVal LCV);
670
671 /// BindStruct - Bind a compound value to a structure.
672 LimitedRegionBindingsRef bindStruct(LimitedRegionBindingsConstRef B,
673 const TypedValueRegion *R, SVal V);
674
675 /// BindVector - Bind a compound value to a vector.
676 LimitedRegionBindingsRef bindVector(LimitedRegionBindingsConstRef B,
677 const TypedValueRegion *R, SVal V);
678
679 std::optional<LimitedRegionBindingsRef>
680 tryBindSmallArray(LimitedRegionBindingsConstRef B, const TypedValueRegion *R,
681 const ArrayType *AT, nonloc::LazyCompoundVal LCV);
682
683 LimitedRegionBindingsRef bindArray(LimitedRegionBindingsConstRef B,
684 const TypedValueRegion *R, SVal V);
685
686 /// Clears out all bindings in the given region and assigns a new value
687 /// as a Default binding.
688 LimitedRegionBindingsRef bindAggregate(LimitedRegionBindingsConstRef B,
689 const TypedRegion *R, SVal DefaultVal);
690
691 /// Create a new store with the specified binding removed.
692 /// \param ST the original store, that is the basis for the new store.
693 /// \param L the location whose binding should be removed.
694 StoreRef killBinding(Store ST, Loc L) override;
695
696 void incrementReferenceCount(Store store) override {
697 if (RegionBindings::TreeTy *T = getRegionBindingsTree(store))
698 T->retain();
699 }
700
701 /// If the StoreManager supports it, decrement the reference count of
702 /// the specified Store object. If the reference count hits 0, the memory
703 /// associated with the object is recycled.
704 void decrementReferenceCount(Store store) override {
705 if (RegionBindings::TreeTy *T = getRegionBindingsTree(store))
706 T->release();
707 }
708
709 bool includedInBindings(Store store, const MemRegion *region) const override;
710
711 /// Return the value bound to specified location in a given state.
712 ///
713 /// The high level logic for this method is this:
714 /// getBinding (L)
715 /// if L has binding
716 /// return L's binding
717 /// else if L is in killset
718 /// return unknown
719 /// else
720 /// if L is on stack or heap
721 /// return undefined
722 /// else
723 /// return symbolic
724 SVal getBinding(Store S, Loc L, QualType T) override {
725 return getBinding(getRegionBindings(S), L, T);
726 }
727
728 std::optional<SVal> getDefaultBinding(Store S, const MemRegion *R) override {
729 RegionBindingsRef B = getRegionBindings(S);
730 // Default bindings are always applied over a base region so look up the
731 // base region's default binding, otherwise the lookup will fail when R
732 // is at an offset from R->getBaseRegion().
733 return B.getDefaultBinding(R->getBaseRegion());
734 }
735
736 SVal getBinding(RegionBindingsConstRef B, Loc L, QualType T = QualType());
737
738 SVal getBindingForElement(RegionBindingsConstRef B, const ElementRegion *R);
739
740 SVal getBindingForField(RegionBindingsConstRef B, const FieldRegion *R);
741
742 SVal getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion *R);
743
744 SVal getBindingForVar(RegionBindingsConstRef B, const VarRegion *R);
745
746 SVal getBindingForLazySymbol(const TypedValueRegion *R);
747
748 SVal getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
749 const TypedValueRegion *R,
750 QualType Ty);
751
752 SVal getLazyBinding(const SubRegion *LazyBindingRegion,
753 RegionBindingsRef LazyBinding);
754
755 /// Get bindings for the values in a struct and return a CompoundVal, used
756 /// when doing struct copy:
757 /// struct s x, y;
758 /// x = y;
759 /// y's value is retrieved by this method.
760 SVal getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R);
761 SVal getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R);
762 NonLoc createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R);
763
764 /// Used to lazily generate derived symbols for bindings that are defined
765 /// implicitly by default bindings in a super region.
766 ///
767 /// Note that callers may need to specially handle LazyCompoundVals, which
768 /// are returned as is in case the caller needs to treat them differently.
769 std::optional<SVal>
770 getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
771 const MemRegion *superR,
772 const TypedValueRegion *R, QualType Ty);
773
774 /// Get the state and region whose binding this region \p R corresponds to.
775 ///
776 /// If there is no lazy binding for \p R, the returned value will have a null
777 /// \c second. Note that a null pointer can represents a valid Store.
778 std::pair<Store, const SubRegion *>
779 findLazyBinding(RegionBindingsConstRef B, const SubRegion *R,
780 const SubRegion *originalRegion);
781
782 /// Returns the cached set of interesting SVals contained within a lazy
783 /// binding.
784 ///
785 /// The precise value of "interesting" is determined for the purposes of
786 /// RegionStore's internal analysis. It must always contain all regions and
787 /// symbols, but may omit constants and other kinds of SVal.
788 ///
789 /// In contrast to compound values, LazyCompoundVals are also added
790 /// to the 'interesting values' list in addition to the child interesting
791 /// values.
792 const SValListTy &getInterestingValues(nonloc::LazyCompoundVal LCV);
793
794 //===------------------------------------------------------------------===//
795 // State pruning.
796 //===------------------------------------------------------------------===//
797
798 /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
799 /// It returns a new Store with these values removed.
800 StoreRef removeDeadBindings(Store store, const StackFrame *SF,
801 SymbolReaper &SymReaper) override;
802
803 //===------------------------------------------------------------------===//
804 // Utility methods.
805 //===------------------------------------------------------------------===//
806
807 RegionBindingsRef getRegionBindings(Store store) const {
808 llvm::PointerIntPair<Store, 1, bool> Ptr;
809 Ptr.setFromOpaqueValue(const_cast<void *>(store));
810 return {CBFactory,
811 static_cast<const RegionBindings::TreeTy *>(Ptr.getPointer()),
812 RBFactory.getTreeFactory(), Ptr.getInt()};
813 }
814
815 static RegionBindings::TreeTy *getRegionBindingsTree(Store store) {
816 llvm::PointerIntPair<Store, 1, bool> Ptr;
817 Ptr.setFromOpaqueValue(const_cast<void *>(store));
818 return static_cast<RegionBindings::TreeTy *>(
819 const_cast<void *>(Ptr.getPointer()));
820 }
821
822 LimitedRegionBindingsRef
823 getRegionBindings(Store store,
824 SmallVectorImpl<SVal> &EscapedValuesDuringBind) const {
825 return LimitedRegionBindingsRef(
826 getRegionBindings(store), EscapedValuesDuringBind,
827 /*BindingsLeft=*/RegionStoreMaxBindingFanOutPlusOne);
828 }
829
830 void printJson(raw_ostream &Out, Store S, const char *NL = "\n",
831 unsigned int Space = 0, bool IsDot = false) const override;
832
833 void iterBindings(Store store, BindingsHandler& f) override {
834 RegionBindingsRef B = getRegionBindings(store);
835 for (const auto &[Region, Cluster] : B) {
836 for (const auto &[Key, Value] : Cluster) {
837 if (!Key.isDirect())
838 continue;
839 if (const SubRegion *R = dyn_cast<SubRegion>(Key.getRegion())) {
840 // FIXME: Possibly incorporate the offset?
841 if (!f.HandleBinding(*this, store, R, Value))
842 return;
843 }
844 }
845 }
846 }
847};
848
849} // end anonymous namespace
850
851//===----------------------------------------------------------------------===//
852// RegionStore creation.
853//===----------------------------------------------------------------------===//
854
855std::unique_ptr<StoreManager>
857 return std::make_unique<RegionStoreManager>(StMgr);
858}
859
860//===----------------------------------------------------------------------===//
861// Region Cluster analysis.
862//===----------------------------------------------------------------------===//
863
864namespace {
865/// Used to determine which global regions are automatically included in the
866/// initial worklist of a ClusterAnalysis.
867enum GlobalsFilterKind {
868 /// Don't include any global regions.
869 GFK_None,
870 /// Only include system globals.
871 GFK_SystemOnly,
872 /// Include all global regions.
873 GFK_All
874};
875
876template <typename DERIVED>
877class ClusterAnalysis {
878protected:
879 typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap;
880 typedef const MemRegion * WorkListElement;
882
884
885 WorkList WL;
886
887 RegionStoreManager &RM;
888 ASTContext &Ctx;
889 SValBuilder &svalBuilder;
890
891 RegionBindingsRef B;
892
893
894protected:
895 const ClusterBindings *getCluster(const MemRegion *R) {
896 return B.lookup(R);
897 }
898
899 /// Returns true if all clusters in the given memspace should be initially
900 /// included in the cluster analysis. Subclasses may provide their
901 /// own implementation.
902 bool includeEntireMemorySpace(const MemRegion *Base) {
903 return false;
904 }
905
906public:
907 ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
908 RegionBindingsRef b)
909 : RM(rm), Ctx(StateMgr.getContext()),
910 svalBuilder(StateMgr.getSValBuilder()), B(std::move(b)) {}
911
912 RegionBindingsRef getRegionBindings() const { return B; }
913
914 bool isVisited(const ClusterBindings *C) const { return Visited.count(C); }
915
916 void GenerateClusters() {
917 // Scan the entire set of bindings and record the region clusters.
918 for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end();
919 RI != RE; ++RI){
920 const MemRegion *Base = RI.getKey();
921
922 const ClusterBindings &Cluster = RI.getData();
923 assert(!Cluster.isEmpty() && "Empty clusters should be removed");
924 static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
925
926 // If the base's memspace should be entirely invalidated, add the cluster
927 // to the workspace up front.
928 if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base))
929 AddToWorkList(WorkListElement(Base), &Cluster);
930 }
931 }
932
933 bool AddToWorkList(WorkListElement E, const ClusterBindings *C) {
934 if (C && !Visited.insert(C).second)
935 return false;
936 WL.push_back(E);
937 return true;
938 }
939
940 bool AddToWorkList(const MemRegion *R) {
941 return static_cast<DERIVED*>(this)->AddToWorkList(R);
942 }
943
944 void RunWorkList() {
945 while (!WL.empty()) {
946 WorkListElement E = WL.pop_back_val();
947 const MemRegion *BaseR = E;
948
949 static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR));
950 }
951 }
952
953 void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {}
954 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {}
955
956 void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C,
957 bool Flag) {
958 static_cast<DERIVED*>(this)->VisitCluster(BaseR, C);
959 }
960};
961}
962
963//===----------------------------------------------------------------------===//
964// Binding invalidation.
965//===----------------------------------------------------------------------===//
966
967bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R,
968 ScanReachableSymbols &Callbacks) {
969 assert(R == R->getBaseRegion() && "Should only be called for base regions");
970 RegionBindingsRef B = getRegionBindings(S);
971 const ClusterBindings *Cluster = B.lookup(R);
972
973 if (!Cluster)
974 return true;
975
976 for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end();
977 RI != RE; ++RI) {
978 if (!Callbacks.scan(RI.getData()))
979 return false;
980 }
981
982 return true;
983}
984
985static inline bool isUnionField(const FieldRegion *FR) {
986 return FR->getDecl()->getParent()->isUnion();
987}
988
990
991static void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) {
992 assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
993
994 const MemRegion *Base = K.getConcreteOffsetRegion();
995 const MemRegion *R = K.getRegion();
996
997 while (R != Base) {
998 if (const FieldRegion *FR = dyn_cast<FieldRegion>(R))
999 if (!isUnionField(FR))
1000 Fields.push_back(FR->getDecl());
1001
1002 R = cast<SubRegion>(R)->getSuperRegion();
1003 }
1004}
1005
1006static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) {
1007 assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
1008
1009 if (Fields.empty())
1010 return true;
1011
1012 FieldVector FieldsInBindingKey;
1013 getSymbolicOffsetFields(K, FieldsInBindingKey);
1014
1015 ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size();
1016 if (Delta >= 0)
1017 return std::equal(FieldsInBindingKey.begin() + Delta,
1018 FieldsInBindingKey.end(),
1019 Fields.begin());
1020 else
1021 return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(),
1022 Fields.begin() - Delta);
1023}
1024
1025/// Collects all bindings in \p Cluster that may refer to bindings within
1026/// \p Top.
1027///
1028/// Each binding is a pair whose \c first is the key (a BindingKey) and whose
1029/// \c second is the value (an SVal).
1030///
1031/// The \p IncludeAllDefaultBindings parameter specifies whether to include
1032/// default bindings that may extend beyond \p Top itself, e.g. if \p Top is
1033/// an aggregate within a larger aggregate with a default binding.
1034static void
1036 SValBuilder &SVB, const ClusterBindings &Cluster,
1037 const SubRegion *Top, BindingKey TopKey,
1038 bool IncludeAllDefaultBindings) {
1039 FieldVector FieldsInSymbolicSubregions;
1040 if (TopKey.hasSymbolicOffset()) {
1041 getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions);
1042 Top = TopKey.getConcreteOffsetRegion();
1043 TopKey = BindingKey::Make(Top, BindingKey::Default);
1044 }
1045
1046 // Find the length (in bits) of the region being invalidated.
1047 uint64_t Length = UINT64_MAX;
1048 SVal Extent = Top->getMemRegionManager().getStaticSize(Top, SVB);
1049 if (std::optional<nonloc::ConcreteInt> ExtentCI =
1050 Extent.getAs<nonloc::ConcreteInt>()) {
1051 const llvm::APSInt &ExtentInt = ExtentCI->getValue();
1052 assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned());
1053 // Extents are in bytes but region offsets are in bits. Be careful!
1054 Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth();
1055 } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(Top)) {
1056 if (FR->getDecl()->isBitField())
1057 Length = FR->getDecl()->getBitWidthValue();
1058 }
1059
1060 for (const auto &StoreEntry : Cluster) {
1061 BindingKey NextKey = StoreEntry.first;
1062 if (NextKey.getRegion() == TopKey.getRegion()) {
1063 // FIXME: This doesn't catch the case where we're really invalidating a
1064 // region with a symbolic offset. Example:
1065 // R: points[i].y
1066 // Next: points[0].x
1067
1068 if (NextKey.getOffset() > TopKey.getOffset() &&
1069 NextKey.getOffset() - TopKey.getOffset() < Length) {
1070 // Case 1: The next binding is inside the region we're invalidating.
1071 // Include it.
1072 Bindings.push_back(StoreEntry);
1073
1074 } else if (NextKey.getOffset() == TopKey.getOffset()) {
1075 // Case 2: The next binding is at the same offset as the region we're
1076 // invalidating. In this case, we need to leave default bindings alone,
1077 // since they may be providing a default value for a regions beyond what
1078 // we're invalidating.
1079 // FIXME: This is probably incorrect; consider invalidating an outer
1080 // struct whose first field is bound to a LazyCompoundVal.
1081 if (IncludeAllDefaultBindings || NextKey.isDirect())
1082 Bindings.push_back(StoreEntry);
1083 }
1084
1085 } else if (NextKey.hasSymbolicOffset()) {
1086 const MemRegion *Base = NextKey.getConcreteOffsetRegion();
1087 if (Top->isSubRegionOf(Base) && Top != Base) {
1088 // Case 3: The next key is symbolic and we just changed something within
1089 // its concrete region. We don't know if the binding is still valid, so
1090 // we'll be conservative and include it.
1091 if (IncludeAllDefaultBindings || NextKey.isDirect())
1092 if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
1093 Bindings.push_back(StoreEntry);
1094 } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) {
1095 // Case 4: The next key is symbolic, but we changed a known
1096 // super-region. In this case the binding is certainly included.
1097 if (BaseSR->isSubRegionOf(Top))
1098 if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
1099 Bindings.push_back(StoreEntry);
1100 }
1101 }
1102 }
1103}
1104
1105static void
1107 SValBuilder &SVB, const ClusterBindings &Cluster,
1108 const SubRegion *Top, bool IncludeAllDefaultBindings) {
1109 collectSubRegionBindings(Bindings, SVB, Cluster, Top,
1110 BindingKey::Make(Top, BindingKey::Default),
1111 IncludeAllDefaultBindings);
1112}
1113
1114LimitedRegionBindingsRef
1115RegionStoreManager::removeSubRegionBindings(LimitedRegionBindingsConstRef B,
1116 const SubRegion *Top) {
1117 BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default);
1118 const MemRegion *ClusterHead = TopKey.getBaseRegion();
1119
1120 if (Top == ClusterHead) {
1121 // We can remove an entire cluster's bindings all in one go.
1122 return B.removeCluster(Top);
1123 }
1124
1125 const ClusterBindings *Cluster = B.lookup(ClusterHead);
1126 if (!Cluster) {
1127 // If we're invalidating a region with a symbolic offset, we need to make
1128 // sure we don't treat the base region as uninitialized anymore.
1129 if (TopKey.hasSymbolicOffset()) {
1130 const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
1131 return B.addBinding(Concrete, BindingKey::Default, UnknownVal());
1132 }
1133 return B;
1134 }
1135
1136 SmallVector<BindingPair, 32> Bindings;
1137 collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey,
1138 /*IncludeAllDefaultBindings=*/false);
1139
1140 ClusterBindingsRef Result(*Cluster, CBFactory);
1141 for (BindingKey Key : llvm::make_first_range(Bindings))
1142 Result = Result.remove(Key);
1143
1144 // If we're invalidating a region with a symbolic offset, we need to make sure
1145 // we don't treat the base region as uninitialized anymore.
1146 // FIXME: This isn't very precise; see the example in
1147 // collectSubRegionBindings.
1148 if (TopKey.hasSymbolicOffset()) {
1149 const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
1150 Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default),
1151 UnknownVal());
1152 }
1153
1154 if (Result.isEmpty())
1155 return B.removeCluster(ClusterHead);
1156 return B.addWithoutDecreasingLimit(ClusterHead, Result.asImmutableMap());
1157}
1158
1159namespace {
1160class InvalidateRegionsWorker : public ClusterAnalysis<InvalidateRegionsWorker>
1161{
1162 ConstCFGElementRef Elem;
1163 unsigned Count;
1164 const StackFrame *SF;
1166 RegionAndSymbolInvalidationTraits &ITraits;
1168 GlobalsFilterKind GlobalsFilter;
1169public:
1170 InvalidateRegionsWorker(RegionStoreManager &rm, ProgramStateManager &stateMgr,
1171 RegionBindingsRef b, ConstCFGElementRef elem,
1172 unsigned count, const StackFrame *SF,
1174 RegionAndSymbolInvalidationTraits &ITraitsIn,
1176 GlobalsFilterKind GFK)
1177 : ClusterAnalysis<InvalidateRegionsWorker>(rm, stateMgr, b), Elem(elem),
1178 Count(count), SF(SF), IS(is), ITraits(ITraitsIn), Regions(r),
1179 GlobalsFilter(GFK) {}
1180
1181 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
1182 void VisitBinding(SVal V);
1183
1184 using ClusterAnalysis::AddToWorkList;
1185
1186 bool AddToWorkList(const MemRegion *R);
1187
1188 /// Returns true if all clusters in the memory space for \p Base should be
1189 /// be invalidated.
1190 bool includeEntireMemorySpace(const MemRegion *Base);
1191
1192 /// Returns true if the memory space of the given region is one of the global
1193 /// regions specially included at the start of invalidation.
1194 bool isInitiallyIncludedGlobalRegion(const MemRegion *R);
1195};
1196}
1197
1198bool InvalidateRegionsWorker::AddToWorkList(const MemRegion *R) {
1199 bool doNotInvalidateSuperRegion = ITraits.hasTrait(
1201 const MemRegion *BaseR = doNotInvalidateSuperRegion ? R : R->getBaseRegion();
1202 return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR));
1203}
1204
1205void InvalidateRegionsWorker::VisitBinding(SVal V) {
1206 // A symbol? Mark it touched by the invalidation.
1207 if (SymbolRef Sym = V.getAsSymbol())
1208 IS.insert(Sym);
1209
1210 if (const MemRegion *R = V.getAsRegion()) {
1211 AddToWorkList(R);
1212 return;
1213 }
1214
1215 // Is it a LazyCompoundVal? All references get invalidated as well.
1216 if (std::optional<nonloc::LazyCompoundVal> LCS =
1217 V.getAs<nonloc::LazyCompoundVal>()) {
1218
1219 // `getInterestingValues()` returns SVals contained within LazyCompoundVals,
1220 // so there is no need to visit them.
1221 for (SVal V : RM.getInterestingValues(*LCS))
1223 VisitBinding(V);
1224
1225 return;
1226 }
1227}
1228
1229void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
1230 const ClusterBindings *C) {
1231
1232 bool PreserveRegionsContents =
1233 ITraits.hasTrait(baseR,
1235
1236 if (C) {
1237 for (SVal Val : llvm::make_second_range(*C))
1238 VisitBinding(Val);
1239
1240 // Invalidate regions contents.
1241 if (!PreserveRegionsContents)
1242 B = B.removeCluster(baseR);
1243 }
1244
1245 if (const auto *TO = dyn_cast<TypedValueRegion>(baseR)) {
1246 if (const auto *RD = TO->getValueType()->getAsCXXRecordDecl()) {
1247
1248 // Lambdas can affect all static local variables without explicitly
1249 // capturing those.
1250 // We invalidate all static locals referenced inside the lambda body.
1251 if (RD->isLambda() && RD->getLambdaCallOperator()->getBody()) {
1252 using namespace ast_matchers;
1253
1254 const char *DeclBind = "DeclBind";
1256 to(varDecl(hasStaticStorageDuration()).bind(DeclBind)))));
1257 auto Matches =
1258 match(RefToStatic, *RD->getLambdaCallOperator()->getBody(),
1259 RD->getASTContext());
1260
1261 for (BoundNodes &Match : Matches) {
1262 auto *VD = Match.getNodeAs<VarDecl>(DeclBind);
1263 const VarRegion *ToInvalidate =
1264 RM.getRegionManager().getVarRegion(VD, SF);
1265 AddToWorkList(ToInvalidate);
1266 }
1267 }
1268 }
1269 }
1270
1271 // BlockDataRegion? If so, invalidate captured variables that are passed
1272 // by reference.
1273 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
1274 for (auto Var : BR->referenced_vars()) {
1275 const VarRegion *VR = Var.getCapturedRegion();
1276 const VarDecl *VD = VR->getDecl();
1277 if (VD->hasAttr<BlocksAttr>() || !VD->hasLocalStorage()) {
1278 AddToWorkList(VR);
1279 }
1280 else if (Loc::isLocType(VR->getValueType())) {
1281 // Map the current bindings to a Store to retrieve the value
1282 // of the binding. If that binding itself is a region, we should
1283 // invalidate that region. This is because a block may capture
1284 // a pointer value, but the thing pointed by that pointer may
1285 // get invalidated.
1286 SVal V = RM.getBinding(B, loc::MemRegionVal(VR));
1287 if (std::optional<Loc> L = V.getAs<Loc>()) {
1288 if (const MemRegion *LR = L->getAsRegion())
1289 AddToWorkList(LR);
1290 }
1291 }
1292 }
1293 return;
1294 }
1295
1296 // Symbolic region?
1297 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
1298 IS.insert(SR->getSymbol());
1299
1300 // Nothing else should be done in the case when we preserve regions context.
1301 if (PreserveRegionsContents)
1302 return;
1303
1304 // Otherwise, we have a normal data region. Record that we touched the region.
1305 if (Regions)
1306 Regions->push_back(baseR);
1307
1309 // Invalidate the region by setting its default value to
1310 // conjured symbol. The type of the symbol is irrelevant.
1311 DefinedOrUnknownSVal V =
1312 svalBuilder.conjureSymbolVal(baseR, Elem, SF, Ctx.IntTy, Count);
1313 B = B.addBinding(baseR, BindingKey::Default, V);
1314 return;
1315 }
1316
1317 if (!baseR->isBoundable())
1318 return;
1319
1320 const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
1321 QualType T = TR->getValueType();
1322
1323 if (isInitiallyIncludedGlobalRegion(baseR)) {
1324 // If the region is a global and we are invalidating all globals,
1325 // erasing the entry is good enough. This causes all globals to be lazily
1326 // symbolicated from the same base symbol.
1327 return;
1328 }
1329
1330 if (T->isRecordType()) {
1331 // Invalidate the region by setting its default value to
1332 // conjured symbol. The type of the symbol is irrelevant.
1333 DefinedOrUnknownSVal V =
1334 svalBuilder.conjureSymbolVal(baseR, Elem, SF, Ctx.IntTy, Count);
1335 B = B.addBinding(baseR, BindingKey::Default, V);
1336 return;
1337 }
1338
1339 if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
1340 bool doNotInvalidateSuperRegion = ITraits.hasTrait(
1341 baseR,
1343
1344 if (doNotInvalidateSuperRegion) {
1345 // We are not doing blank invalidation of the whole array region so we
1346 // have to manually invalidate each elements.
1347 std::optional<uint64_t> NumElements;
1348
1349 // Compute lower and upper offsets for region within array.
1350 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1351 NumElements = CAT->getZExtSize();
1352 if (!NumElements) // We are not dealing with a constant size array
1353 goto conjure_default;
1354 QualType ElementTy = AT->getElementType();
1355 uint64_t ElemSize = Ctx.getTypeSize(ElementTy);
1356 const RegionOffset &RO = baseR->getAsOffset();
1357 const MemRegion *SuperR = baseR->getBaseRegion();
1358 if (RO.hasSymbolicOffset()) {
1359 // If base region has a symbolic offset,
1360 // we revert to invalidating the super region.
1361 if (SuperR)
1362 AddToWorkList(SuperR);
1363 goto conjure_default;
1364 }
1365
1366 uint64_t LowerOffset = RO.getOffset();
1367 uint64_t UpperOffset = LowerOffset + *NumElements * ElemSize;
1368 bool UpperOverflow = UpperOffset < LowerOffset;
1369
1370 // Invalidate regions which are within array boundaries,
1371 // or have a symbolic offset.
1372 if (!SuperR)
1373 goto conjure_default;
1374
1375 const ClusterBindings *C = B.lookup(SuperR);
1376 if (!C)
1377 goto conjure_default;
1378
1379 for (const auto &[BK, V] : *C) {
1380 std::optional<uint64_t> ROffset =
1381 BK.hasSymbolicOffset() ? std::optional<uint64_t>() : BK.getOffset();
1382
1383 // Check offset is not symbolic and within array's boundaries.
1384 // Handles arrays of 0 elements and of 0-sized elements as well.
1385 if (!ROffset ||
1386 ((*ROffset >= LowerOffset && *ROffset < UpperOffset) ||
1387 (UpperOverflow &&
1388 (*ROffset >= LowerOffset || *ROffset < UpperOffset)) ||
1389 (LowerOffset == UpperOffset && *ROffset == LowerOffset))) {
1390 B = B.removeBinding(BK);
1391 // Bound symbolic regions need to be invalidated for dead symbol
1392 // detection.
1393 const MemRegion *R = V.getAsRegion();
1394 if (isa_and_nonnull<SymbolicRegion>(R))
1395 VisitBinding(V);
1396 }
1397 }
1398 }
1399 conjure_default:
1400 // Set the default value of the array to conjured symbol.
1401 DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(
1402 baseR, Elem, SF, AT->getElementType(), Count);
1403 B = B.addBinding(baseR, BindingKey::Default, V);
1404 return;
1405 }
1406
1407 DefinedOrUnknownSVal V =
1408 svalBuilder.conjureSymbolVal(baseR, Elem, SF, T, Count);
1409 assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
1410 B = B.addBinding(baseR, BindingKey::Direct, V);
1411}
1412
1413bool InvalidateRegionsWorker::isInitiallyIncludedGlobalRegion(
1414 const MemRegion *R) {
1415 switch (GlobalsFilter) {
1416 case GFK_None:
1417 return false;
1418 case GFK_SystemOnly:
1419 return isa<GlobalSystemSpaceRegion>(R->getRawMemorySpace());
1420 case GFK_All:
1421 return isa<NonStaticGlobalSpaceRegion>(R->getRawMemorySpace());
1422 }
1423
1424 llvm_unreachable("unknown globals filter");
1425}
1426
1427bool InvalidateRegionsWorker::includeEntireMemorySpace(const MemRegion *Base) {
1428 if (isInitiallyIncludedGlobalRegion(Base))
1429 return true;
1430
1431 const MemSpaceRegion *MemSpace = Base->getRawMemorySpace();
1432 return ITraits.hasTrait(MemSpace,
1434}
1435
1436RegionBindingsRef RegionStoreManager::invalidateGlobalRegion(
1437 MemRegion::Kind K, ConstCFGElementRef Elem, unsigned Count,
1438 const StackFrame *SF, RegionBindingsRef B,
1439 InvalidatedRegions *Invalidated) {
1440 // Bind the globals memory space to a new symbol that we will use to derive
1441 // the bindings for all globals.
1442 const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
1443 SVal V = svalBuilder.conjureSymbolVal(
1444 /* symbolTag = */ (const void *)GS, Elem, SF,
1445 /* type does not matter */ Ctx.IntTy, Count);
1446
1447 B = B.removeBinding(GS)
1448 .addBinding(BindingKey::Make(GS, BindingKey::Default), V);
1449
1450 // Even if there are no bindings in the global scope, we still need to
1451 // record that we touched it.
1452 if (Invalidated)
1453 Invalidated->push_back(GS);
1454
1455 return B;
1456}
1457
1458void RegionStoreManager::populateWorkList(InvalidateRegionsWorker &W,
1459 ArrayRef<SVal> Values,
1460 InvalidatedRegions *TopLevelRegions) {
1461 for (SVal V : Values) {
1462 if (auto LCS = V.getAs<nonloc::LazyCompoundVal>()) {
1463 for (SVal S : getInterestingValues(*LCS))
1464 if (const MemRegion *R = S.getAsRegion())
1465 W.AddToWorkList(R);
1466
1467 continue;
1468 }
1469
1470 if (const MemRegion *R = V.getAsRegion()) {
1471 if (TopLevelRegions)
1472 TopLevelRegions->push_back(R);
1473 W.AddToWorkList(R);
1474 continue;
1475 }
1476 }
1477}
1478
1479StoreRef RegionStoreManager::invalidateRegions(
1480 Store store, ArrayRef<SVal> Values, ConstCFGElementRef Elem, unsigned Count,
1481 const StackFrame *SF, const CallEvent *Call, InvalidatedSymbols &IS,
1482 RegionAndSymbolInvalidationTraits &ITraits,
1483 InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) {
1484 GlobalsFilterKind GlobalsFilter;
1485 if (Call) {
1486 if (Call->isInSystemHeader())
1487 GlobalsFilter = GFK_SystemOnly;
1488 else
1489 GlobalsFilter = GFK_All;
1490 } else {
1491 GlobalsFilter = GFK_None;
1492 }
1493
1494 RegionBindingsRef B = getRegionBindings(store);
1495 InvalidateRegionsWorker W(*this, StateMgr, B, Elem, Count, SF, IS, ITraits,
1496 Invalidated, GlobalsFilter);
1497
1498 // Scan the bindings and generate the clusters.
1499 W.GenerateClusters();
1500
1501 // Add the regions to the worklist.
1502 populateWorkList(W, Values, TopLevelRegions);
1503
1504 W.RunWorkList();
1505
1506 // Return the new bindings.
1507 B = W.getRegionBindings();
1508
1509 // For calls, determine which global regions should be invalidated and
1510 // invalidate them. (Note that function-static and immutable globals are never
1511 // invalidated by this.)
1512 // TODO: This could possibly be more precise with modules.
1513 switch (GlobalsFilter) {
1514 case GFK_All:
1515 B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind, Elem,
1516 Count, SF, B, Invalidated);
1517 [[fallthrough]];
1518 case GFK_SystemOnly:
1519 B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind, Elem,
1520 Count, SF, B, Invalidated);
1521 [[fallthrough]];
1522 case GFK_None:
1523 break;
1524 }
1525
1526 return StoreRef(B.asStore(), *this);
1527}
1528
1529//===----------------------------------------------------------------------===//
1530// Location and region casting.
1531//===----------------------------------------------------------------------===//
1532
1533/// ArrayToPointer - Emulates the "decay" of an array to a pointer
1534/// type. 'Array' represents the lvalue of the array being decayed
1535/// to a pointer, and the returned SVal represents the decayed
1536/// version of that lvalue (i.e., a pointer to the first element of
1537/// the array). This is called by ExprEngine when evaluating casts
1538/// from arrays to pointers.
1539SVal RegionStoreManager::ArrayToPointer(Loc Array, QualType T) {
1541 return Array;
1542
1544 return UnknownVal();
1545
1546 const SubRegion *R =
1547 cast<SubRegion>(Array.castAs<loc::MemRegionVal>().getRegion());
1548 NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
1549 return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, R, Ctx));
1550}
1551
1552//===----------------------------------------------------------------------===//
1553// Loading values from regions.
1554//===----------------------------------------------------------------------===//
1555
1556SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) {
1557 assert(!isa<UnknownVal>(L) && "location unknown");
1558 assert(!isa<UndefinedVal>(L) && "location undefined");
1559
1560 // For access to concrete addresses, return UnknownVal. Checks
1561 // for null dereferences (and similar errors) are done by checkers, not
1562 // the Store.
1563 // FIXME: We can consider lazily symbolicating such memory, but we really
1564 // should defer this when we can reason easily about symbolicating arrays
1565 // of bytes.
1566 if (L.getAs<loc::ConcreteInt>()) {
1567 return UnknownVal();
1568 }
1569 if (!L.getAs<loc::MemRegionVal>()) {
1570 return UnknownVal();
1571 }
1572
1573 const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion();
1574
1575 if (isa<BlockDataRegion>(MR)) {
1576 return UnknownVal();
1577 }
1578
1579 // Auto-detect the binding type.
1580 if (T.isNull()) {
1581 if (const auto *TVR = dyn_cast<TypedValueRegion>(MR))
1582 T = TVR->getValueType();
1583 else if (const auto *TR = dyn_cast<TypedRegion>(MR))
1584 T = TR->getLocationType()->getPointeeType();
1585 else if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1586 T = SR->getPointeeStaticType();
1587 }
1588 assert(!T.isNull() && "Unable to auto-detect binding type!");
1589 assert(!T->isVoidType() && "Attempting to dereference a void pointer!");
1590
1591 if (!isa<TypedValueRegion>(MR))
1592 MR = GetElementZeroRegion(cast<SubRegion>(MR), T);
1593
1594 // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
1595 // instead of 'Loc', and have the other Loc cases handled at a higher level.
1596 const TypedValueRegion *R = cast<TypedValueRegion>(MR);
1597 QualType RTy = R->getValueType();
1598
1599 // FIXME: we do not yet model the parts of a complex type, so treat the
1600 // whole thing as "unknown".
1601 if (RTy->isAnyComplexType())
1602 return UnknownVal();
1603
1604 // FIXME: We should eventually handle funny addressing. e.g.:
1605 //
1606 // int x = ...;
1607 // int *p = &x;
1608 // char *q = (char*) p;
1609 // char c = *q; // returns the first byte of 'x'.
1610 //
1611 // Such funny addressing will occur due to layering of regions.
1612 if (RTy->isStructureOrClassType())
1613 return getBindingForStruct(B, R);
1614
1615 // FIXME: Handle unions.
1616 if (RTy->isUnionType())
1617 return createLazyBinding(B, R);
1618
1619 if (RTy->isArrayType()) {
1620 if (RTy->isConstantArrayType())
1621 return getBindingForArray(B, R);
1622 else
1623 return UnknownVal();
1624 }
1625
1626 // FIXME: handle Vector types.
1627 if (RTy->isVectorType())
1628 return UnknownVal();
1629
1630 if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
1631 return svalBuilder.evalCast(getBindingForField(B, FR), T, QualType{});
1632
1633 if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
1634 // FIXME: Here we actually perform an implicit conversion from the loaded
1635 // value to the element type. Eventually we want to compose these values
1636 // more intelligently. For example, an 'element' can encompass multiple
1637 // bound regions (e.g., several bound bytes), or could be a subset of
1638 // a larger value.
1639 return svalBuilder.evalCast(getBindingForElement(B, ER), T, QualType{});
1640 }
1641
1642 if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
1643 // FIXME: Here we actually perform an implicit conversion from the loaded
1644 // value to the ivar type. What we should model is stores to ivars
1645 // that blow past the extent of the ivar. If the address of the ivar is
1646 // reinterpretted, it is possible we stored a different value that could
1647 // fit within the ivar. Either we need to cast these when storing them
1648 // or reinterpret them lazily (as we do here).
1649 return svalBuilder.evalCast(getBindingForObjCIvar(B, IVR), T, QualType{});
1650 }
1651
1652 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
1653 // FIXME: Here we actually perform an implicit conversion from the loaded
1654 // value to the variable type. What we should model is stores to variables
1655 // that blow past the extent of the variable. If the address of the
1656 // variable is reinterpretted, it is possible we stored a different value
1657 // that could fit within the variable. Either we need to cast these when
1658 // storing them or reinterpret them lazily (as we do here).
1659 return svalBuilder.evalCast(getBindingForVar(B, VR), T, QualType{});
1660 }
1661
1662 const SVal *V = B.lookup(R, BindingKey::Direct);
1663
1664 // Check if the region has a binding.
1665 if (V)
1666 return *V;
1667
1668 // The location does not have a bound value. This means that it has
1669 // the value it had upon its creation and/or entry to the analyzed
1670 // function/method. These are either symbolic values or 'undefined'.
1671 if (isa<StackLocalsSpaceRegion>(R->getRawMemorySpace())) {
1672 // All stack variables are considered to have undefined values
1673 // upon creation. All heap allocated blocks are considered to
1674 // have undefined values as well unless they are explicitly bound
1675 // to specific values.
1676 return UndefinedVal();
1677 }
1678
1679 // All other values are symbolic.
1680 return svalBuilder.getRegionValueSymbolVal(R);
1681}
1682
1684 QualType RegionTy;
1685 if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R))
1686 RegionTy = TVR->getValueType();
1687
1688 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1689 RegionTy = SR->getSymbol()->getType();
1690
1691 return RegionTy;
1692}
1693
1694/// Checks to see if store \p B has a lazy binding for region \p R.
1695///
1696/// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected
1697/// if there are additional bindings within \p R.
1698///
1699/// Note that unlike RegionStoreManager::findLazyBinding, this will not search
1700/// for lazy bindings for super-regions of \p R.
1701static std::optional<nonloc::LazyCompoundVal>
1703 const SubRegion *R, bool AllowSubregionBindings) {
1704 std::optional<SVal> V = B.getDefaultBinding(R);
1705 if (!V)
1706 return std::nullopt;
1707
1708 std::optional<nonloc::LazyCompoundVal> LCV =
1709 V->getAs<nonloc::LazyCompoundVal>();
1710 if (!LCV)
1711 return std::nullopt;
1712
1713 // If the LCV is for a subregion, the types might not match, and we shouldn't
1714 // reuse the binding.
1715 QualType RegionTy = getUnderlyingType(R);
1716 if (!RegionTy.isNull() &&
1717 !RegionTy->isVoidPointerType()) {
1718 QualType SourceRegionTy = LCV->getRegion()->getValueType();
1719 if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy))
1720 return std::nullopt;
1721 }
1722
1723 if (!AllowSubregionBindings) {
1724 // If there are any other bindings within this region, we shouldn't reuse
1725 // the top-level binding.
1727 collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R,
1728 /*IncludeAllDefaultBindings=*/true);
1729 if (Bindings.size() > 1)
1730 return std::nullopt;
1731 }
1732
1733 return *LCV;
1734}
1735
1736std::pair<Store, const SubRegion *>
1737RegionStoreManager::findLazyBinding(RegionBindingsConstRef B,
1738 const SubRegion *R,
1739 const SubRegion *originalRegion) {
1740 if (originalRegion != R) {
1741 if (std::optional<nonloc::LazyCompoundVal> V =
1742 getExistingLazyBinding(svalBuilder, B, R, true))
1743 return std::make_pair(V->getStore(), V->getRegion());
1744 }
1745
1746 typedef std::pair<Store, const SubRegion *> StoreRegionPair;
1747 StoreRegionPair Result = StoreRegionPair();
1748
1749 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1750 Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()),
1751 originalRegion);
1752
1753 if (Result.second)
1754 Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second);
1755
1756 } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
1757 Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()),
1758 originalRegion);
1759
1760 if (Result.second)
1761 Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second);
1762
1763 } else if (const CXXBaseObjectRegion *BaseReg =
1764 dyn_cast<CXXBaseObjectRegion>(R)) {
1765 // C++ base object region is another kind of region that we should blast
1766 // through to look for lazy compound value. It is like a field region.
1767 Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()),
1768 originalRegion);
1769
1770 if (Result.second)
1771 Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg,
1772 Result.second);
1773 }
1774
1775 return Result;
1776}
1777
1778/// This is a helper function for `getConstantValFromConstArrayInitializer`.
1779///
1780/// Return an array of extents of the declared array type.
1781///
1782/// E.g. for `int x[1][2][3];` returns { 1, 2, 3 }.
1783static SmallVector<uint64_t, 2>
1785 assert(CAT && "ConstantArrayType should not be null");
1788 do {
1789 Extents.push_back(CAT->getZExtSize());
1790 } while ((CAT = dyn_cast<ConstantArrayType>(CAT->getElementType())));
1791 return Extents;
1792}
1793
1794/// This is a helper function for `getConstantValFromConstArrayInitializer`.
1795///
1796/// Return an array of offsets from nested ElementRegions and a root base
1797/// region. The array is never empty and a base region is never null.
1798///
1799/// E.g. for `Element{Element{Element{VarRegion},1},2},3}` returns { 3, 2, 1 }.
1800/// This represents an access through indirection: `arr[1][2][3];`
1801///
1802/// \param ER The given (possibly nested) ElementRegion.
1803///
1804/// \note The result array is in the reverse order of indirection expression:
1805/// arr[1][2][3] -> { 3, 2, 1 }. This helps to provide complexity O(n), where n
1806/// is a number of indirections. It may not affect performance in real-life
1807/// code, though.
1808static std::pair<SmallVector<SVal, 2>, const MemRegion *>
1810 assert(ER && "ConstantArrayType should not be null");
1811 const MemRegion *Base;
1812 SmallVector<SVal, 2> SValOffsets;
1813 do {
1814 SValOffsets.push_back(ER->getIndex());
1815 Base = ER->getSuperRegion();
1816 ER = dyn_cast<ElementRegion>(Base);
1817 } while (ER);
1818 return {SValOffsets, Base};
1819}
1820
1821/// This is a helper function for `getConstantValFromConstArrayInitializer`.
1822///
1823/// Flatten per-dimension SVal offsets into a linear index, bounds-check
1824/// against the total allocation, and decompose back into per-dimension
1825/// uint64_t indices.
1826///
1827/// \param SrcOffsets [in] Per-dimension offsets in reversed order
1828/// (as received from `getElementRegionOffsetsWithBase`).
1829/// \param ArrayExtents [in] Extents per dimension (outer to inner).
1830/// \param DstOffsets [out] Normalized per-dimension indices.
1831/// \returns:
1832/// - `std::nullopt` on success.
1833/// - `UndefinedVal` if the flat offset is out of bounds.
1834/// - `UnknownVal` if any index is symbolic.
1835///
1836/// \example:
1837/// const int arr[10][20][30] = {}; // ArrayExtents { 10, 20, 30 }
1838/// int x1 = arr[4][5][6]; // SrcOffsets { NonLoc(6), NonLoc(5), NonLoc(4) }
1839/// // DstOffsets { 4, 5, 6 }, returns std::nullopt
1840/// int x2 = arr[0][0][35]; // DstOffsets { 0, 1, 5 }, returns std::nullopt
1841/// int x3 = arr[0][25][-5]; // DstOffsets { 1, 4, 25 }, returns std::nullopt
1842/// int x4 = arr[10][0][0]; // returns UndefinedVal (flat offset >= total)
1843/// int x5 = arr[4][5][x1]; // returns UnknownVal
1844static std::optional<SVal>
1846 const SmallVector<uint64_t, 2> ArrayExtents,
1847 SmallVector<uint64_t, 2> &DstOffsets) {
1848 // Flatten to a linear offset so that both positive overflow and negative
1849 // indices across sub-array boundaries resolve to the correct element.
1850 int64_t FlatOffset = 0;
1851 auto ExtentIt = ArrayExtents.begin();
1852 for (SVal V : llvm::reverse(SrcOffsets)) {
1853 auto CI = V.getAs<nonloc::ConcreteInt>();
1854 if (!CI)
1855 return UnknownVal();
1856 FlatOffset = FlatOffset * static_cast<int64_t>(*(ExtentIt++)) +
1857 CI->getValue()->getExtValue();
1858 }
1859
1860 int64_t TotalSize = 1;
1861 for (uint64_t E : ArrayExtents)
1862 TotalSize *= static_cast<int64_t>(E);
1863
1864 if (FlatOffset < 0 || FlatOffset >= TotalSize)
1865 return UndefinedVal();
1866
1867 DstOffsets.resize(ArrayExtents.size());
1868 uint64_t Remaining = static_cast<uint64_t>(FlatOffset);
1869 for (int I = DstOffsets.size() - 1; I >= 0; --I) {
1870 DstOffsets[I] = Remaining % ArrayExtents[I];
1871 Remaining /= ArrayExtents[I];
1872 }
1873
1874 return std::nullopt;
1875}
1876
1877std::optional<SVal> RegionStoreManager::getConstantValFromConstArrayInitializer(
1878 RegionBindingsConstRef B, const ElementRegion *R) {
1879 assert(R && "ElementRegion should not be null");
1880
1881 // Treat an n-dimensional array.
1882 SmallVector<SVal, 2> SValOffsets;
1883 const MemRegion *Base;
1884 std::tie(SValOffsets, Base) = getElementRegionOffsetsWithBase(R);
1885 const VarRegion *VR = dyn_cast<VarRegion>(Base);
1886 if (!VR)
1887 return std::nullopt;
1888
1889 assert(!SValOffsets.empty() && "getElementRegionOffsets guarantees the "
1890 "offsets vector is not empty.");
1891
1892 // Check if the containing array has an initialized value that we can trust.
1893 // We can trust a const value or a value of a global initializer in main().
1894 const VarDecl *VD = VR->getDecl();
1895 if (!VD->getType().isConstQualified() &&
1896 !R->getElementType().isConstQualified() &&
1897 (!B.isMainAnalysis() || !VD->hasGlobalStorage()))
1898 return std::nullopt;
1899
1900 // Array's declaration should have `ConstantArrayType` type, because only this
1901 // type contains an array extent. It may happen that array type can be of
1902 // `IncompleteArrayType` type. To get the declaration of `ConstantArrayType`
1903 // type, we should find the declaration in the redeclarations chain that has
1904 // the initialization expression.
1905 // NOTE: `getAnyInitializer` has an out-parameter, which returns a new `VD`
1906 // from which an initializer is obtained. We replace current `VD` with the new
1907 // `VD`. If the return value of the function is null than `VD` won't be
1908 // replaced.
1909 const Expr *Init = VD->getAnyInitializer(VD);
1910 // NOTE: If `Init` is non-null, then a new `VD` is non-null for sure. So check
1911 // `Init` for null only and don't worry about the replaced `VD`.
1912 if (!Init)
1913 return std::nullopt;
1914
1915 // Array's declaration should have ConstantArrayType type, because only this
1916 // type contains an array extent.
1917 const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(VD->getType());
1918 if (!CAT)
1919 return std::nullopt;
1920
1921 // Get array extents.
1922 SmallVector<uint64_t, 2> Extents = getConstantArrayExtents(CAT);
1923
1924 // The number of offsets should equal to the numbers of extents,
1925 // otherwise wrong type punning occurred. For instance:
1926 // int arr[1][2][3];
1927 // auto ptr = (int(*)[42])arr;
1928 // auto x = ptr[4][2]; // UB
1929 // FIXME: Should return UndefinedVal.
1930 if (SValOffsets.size() != Extents.size())
1931 return std::nullopt;
1932
1933 SmallVector<uint64_t, 2> ConcreteOffsets;
1934 if (std::optional<SVal> V = convertOffsetsFromSvalToUnsigneds(
1935 SValOffsets, Extents, ConcreteOffsets))
1936 return *V;
1937
1938 // Handle InitListExpr.
1939 // Example:
1940 // const char arr[4][2] = { { 1, 2 }, { 3 }, 4, 5 };
1941 if (const auto *ILE = dyn_cast<InitListExpr>(Init))
1942 return getSValFromInitListExpr(ILE, ConcreteOffsets, R->getElementType());
1943
1944 // Handle StringLiteral.
1945 // Example:
1946 // const char arr[] = "abc";
1947 if (const auto *SL = dyn_cast<StringLiteral>(Init))
1948 return getSValFromStringLiteral(SL, ConcreteOffsets.front(),
1949 R->getElementType());
1950
1951 // FIXME: Handle CompoundLiteralExpr.
1952
1953 return std::nullopt;
1954}
1955
1956/// Returns an SVal, if possible, for the specified position of an
1957/// initialization list.
1958///
1959/// \param ILE The given initialization list.
1960/// \param Offsets The array of unsigned offsets. E.g. for the expression
1961/// `int x = arr[1][2][3];` an array should be { 1, 2, 3 }.
1962/// \param ElemT The type of the result SVal expression.
1963/// \return Optional SVal for the particular position in the initialization
1964/// list. E.g. for the list `{{1, 2},[3, 4],{5, 6}, {}}` offsets:
1965/// - {1, 1} returns SVal{4}, because it's the second position in the second
1966/// sublist;
1967/// - {3, 0} returns SVal{0}, because there's no explicit value at this
1968/// position in the sublist.
1969///
1970/// NOTE: Inorder to get a valid SVal, a caller shall guarantee valid offsets
1971/// for the given initialization list. Otherwise SVal can be an equivalent to 0
1972/// or lead to assertion.
1973std::optional<SVal> RegionStoreManager::getSValFromInitListExpr(
1974 const InitListExpr *ILE, const SmallVector<uint64_t, 2> &Offsets,
1975 QualType ElemT) {
1976 assert(ILE && "InitListExpr should not be null");
1977
1978 for (uint64_t Offset : Offsets) {
1979 // C++20 [dcl.init.string] 9.4.2.1:
1980 // An array of ordinary character type [...] can be initialized by [...]
1981 // an appropriately-typed string-literal enclosed in braces.
1982 // Example:
1983 // const char arr[] = { "abc" };
1984 if (ILE->isStringLiteralInit())
1985 if (const auto *SL = dyn_cast<StringLiteral>(ILE->getInit(0)))
1986 return getSValFromStringLiteral(SL, Offset, ElemT);
1987
1988 // C++20 [expr.add] 9.4.17.5 (excerpt):
1989 // i-th array element is value-initialized for each k < i ≤ n,
1990 // where k is an expression-list size and n is an array extent.
1991 if (Offset >= ILE->getNumInits())
1992 return svalBuilder.makeZeroVal(ElemT);
1993
1994 const Expr *E = ILE->getInit(Offset);
1995 const auto *IL = dyn_cast<InitListExpr>(E);
1996 if (!IL)
1997 // Return a constant value, if it is presented.
1998 // FIXME: Support other SVals.
1999 return svalBuilder.getConstantVal(E);
2000
2001 // Go to the nested initializer list.
2002 ILE = IL;
2003 }
2004
2005 assert(ILE);
2006
2007 // FIXME: Unhandeled InitListExpr sub-expression, possibly constructing an
2008 // enum?
2009 return std::nullopt;
2010}
2011
2012/// Returns an SVal, if possible, for the specified position in a string
2013/// literal.
2014///
2015/// \param SL The given string literal.
2016/// \param Offset The unsigned offset. E.g. for the expression
2017/// `char x = str[42];` an offset should be 42.
2018/// E.g. for the string "abc" offset:
2019/// - 1 returns SVal{b}, because it's the second position in the string.
2020/// - 42 returns SVal{0}, because there's no explicit value at this
2021/// position in the string.
2022/// \param ElemT The type of the result SVal expression.
2023///
2024/// NOTE: We return `0` for every offset >= the literal length for array
2025/// declarations, like:
2026/// const char str[42] = "123"; // Literal length is 4.
2027/// char c = str[41]; // Offset is 41.
2028/// FIXME: Nevertheless, we can't do the same for pointer declaraions, like:
2029/// const char * const str = "123"; // Literal length is 4.
2030/// char c = str[41]; // Offset is 41. Returns `0`, but Undef
2031/// // expected.
2032/// It should be properly handled before reaching this point.
2033/// The main problem is that we can't distinguish between these declarations,
2034/// because in case of array we can get the Decl from VarRegion, but in case
2035/// of pointer the region is a StringRegion, which doesn't contain a Decl.
2036/// Possible solution could be passing an array extent along with the offset.
2037SVal RegionStoreManager::getSValFromStringLiteral(const StringLiteral *SL,
2038 uint64_t Offset,
2039 QualType ElemT) {
2040 assert(SL && "StringLiteral should not be null");
2041 // C++20 [dcl.init.string] 9.4.2.3:
2042 // If there are fewer initializers than there are array elements, each
2043 // element not explicitly initialized shall be zero-initialized [dcl.init].
2044 uint32_t Code = (Offset >= SL->getLength()) ? 0 : SL->getCodeUnit(Offset);
2045 return svalBuilder.makeIntVal(Code, ElemT);
2046}
2047
2048static std::optional<SVal> getDerivedSymbolForBinding(
2049 RegionBindingsConstRef B, const TypedValueRegion *BaseRegion,
2050 const TypedValueRegion *SubReg, const ASTContext &Ctx, SValBuilder &SVB) {
2051 assert(BaseRegion);
2052 QualType BaseTy = BaseRegion->getValueType();
2053 QualType Ty = SubReg->getValueType();
2054 if (BaseTy->isScalarType() && Ty->isScalarType()) {
2055 if (Ctx.getTypeSizeInChars(BaseTy) >= Ctx.getTypeSizeInChars(Ty)) {
2056 if (const std::optional<SVal> &ParentValue =
2057 B.getDirectBinding(BaseRegion)) {
2058 if (SymbolRef ParentValueAsSym = ParentValue->getAsSymbol())
2059 return SVB.getDerivedRegionValueSymbolVal(ParentValueAsSym, SubReg);
2060
2061 if (ParentValue->isUndef())
2062 return UndefinedVal();
2063
2064 // Other cases: give up. We are indexing into a larger object
2065 // that has some value, but we don't know how to handle that yet.
2066 return UnknownVal();
2067 }
2068 }
2069 }
2070 return std::nullopt;
2071}
2072
2073SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
2074 const ElementRegion* R) {
2075 // Check if the region has a binding.
2076 if (const std::optional<SVal> &V = B.getDirectBinding(R))
2077 return *V;
2078
2079 const MemRegion* superR = R->getSuperRegion();
2080
2081 // Check if the region is an element region of a string literal.
2082 if (const StringRegion *StrR = dyn_cast<StringRegion>(superR)) {
2083 // FIXME: Handle loads from strings where the literal is treated as
2084 // an integer, e.g., *((unsigned int*)"hello"). Such loads are UB according
2085 // to C++20 7.2.1.11 [basic.lval].
2086 QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
2087 if (!Ctx.hasSameUnqualifiedType(T, R->getElementType()))
2088 return UnknownVal();
2089 if (const auto CI = R->getIndex().getAs<nonloc::ConcreteInt>()) {
2090 const llvm::APSInt &Idx = CI->getValue();
2091 if (Idx < 0)
2092 return UndefinedVal();
2093 const StringLiteral *SL = StrR->getStringLiteral();
2094 return getSValFromStringLiteral(SL, Idx.getZExtValue(), T);
2095 }
2096 } else if (isa<ElementRegion, VarRegion>(superR)) {
2097 if (std::optional<SVal> V = getConstantValFromConstArrayInitializer(B, R))
2098 return *V;
2099 }
2100
2101 // Check for loads from a code text region. For such loads, just give up.
2102 if (isa<CodeTextRegion>(superR))
2103 return UnknownVal();
2104
2105 // Handle the case where we are indexing into a larger scalar object.
2106 // For example, this handles:
2107 // int x = ...
2108 // char *y = &x;
2109 // return *y;
2110 // FIXME: This is a hack, and doesn't do anything really intelligent yet.
2111 const RegionRawOffset &O = R->getAsArrayOffset();
2112
2113 // If we cannot reason about the offset, return an unknown value.
2114 if (!O.getRegion())
2115 return UnknownVal();
2116
2117 if (const TypedValueRegion *baseR = dyn_cast<TypedValueRegion>(O.getRegion()))
2118 if (auto V = getDerivedSymbolForBinding(B, baseR, R, Ctx, svalBuilder))
2119 return *V;
2120
2121 return getBindingForFieldOrElementCommon(B, R, R->getElementType());
2122}
2123
2124std::optional<SVal>
2125RegionStoreManager::getConstantValFromInitializer(const FieldRegion *R,
2126 bool IsMainAnalysis) {
2127 SmallVector<const SubRegion *, 4> Path;
2128 const MemRegion *Cur = R;
2129 while (Cur && !isa<VarRegion>(Cur)) {
2131 Path.push_back(cast<SubRegion>(Cur));
2132 Cur = cast<SubRegion>(Cur)->getSuperRegion();
2133 } else {
2134 return std::nullopt;
2135 }
2136 }
2137
2138 const auto *VR = dyn_cast<VarRegion>(Cur);
2139 if (!VR)
2140 return std::nullopt;
2141
2142 const VarDecl *VD = VR->getDecl();
2143 QualType LeafTy = R->getDecl()->getType();
2144
2145 bool TrustInit =
2146 (VD->getType().isConstQualified() || LeafTy.isConstQualified() ||
2147 (IsMainAnalysis && VD->hasGlobalStorage()));
2148 if (!TrustInit)
2149 return std::nullopt;
2150
2151 const Expr *Init = VD->getAnyInitializer();
2152 if (!Init)
2153 return std::nullopt;
2154
2155 const Expr *E = Init;
2156 for (const SubRegion *SR : llvm::reverse(Path)) {
2157 // If E is not an InitListExpr, it may be an ImplicitValueInitExpr
2158 // representing zero-initialization of this aggregate element.
2160 return svalBuilder.makeZeroVal(LeafTy);
2161
2162 const auto *ILE = dyn_cast<InitListExpr>(E);
2163 if (!ILE)
2164 return std::nullopt;
2165
2166 if (const auto *FR = dyn_cast<FieldRegion>(SR)) {
2167 if (ILE->getType()->isUnionType()) {
2168 // A union InitListExpr has one init for one member. We can only
2169 // resolve if the accessed field matches the initialized member.
2170 const FieldDecl *InitField = ILE->getInitializedFieldInUnion();
2171 if (InitField != FR->getDecl())
2172 return std::nullopt;
2173 if (ILE->getNumInits() == 0)
2174 return svalBuilder.makeZeroVal(LeafTy);
2175 E = ILE->getInit(0);
2176 } else {
2177 unsigned Idx = FR->getDecl()->getFieldIndex();
2178 if (Idx >= ILE->getNumInits())
2179 return std::nullopt;
2180 E = ILE->getInit(Idx);
2181 }
2182 continue;
2183 }
2184
2185 if (const auto *ER = dyn_cast<ElementRegion>(SR)) {
2186 auto CI = ER->getIndex().getAs<nonloc::ConcreteInt>();
2187 if (!CI)
2188 return std::nullopt;
2189 uint64_t Idx = CI->getValue()->getZExtValue();
2190 if (Idx < ILE->getNumInits())
2191 E = ILE->getInit(Idx);
2192 else if (const Expr *Filler = ILE->getArrayFiller())
2193 E = Filler;
2194 else
2195 return std::nullopt;
2196 continue;
2197 }
2198
2199 return std::nullopt;
2200 }
2201
2202 return svalBuilder.getConstantVal(E);
2203}
2204
2205SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
2206 const FieldRegion* R) {
2207
2208 // Check if the region has a binding.
2209 if (const std::optional<SVal> &V = B.getDirectBinding(R))
2210 return *V;
2211
2212 // Try to resolve the field value from the variable's initializer.
2213 if (std::optional<SVal> V =
2214 getConstantValFromInitializer(R, B.isMainAnalysis()))
2215 return *V;
2216
2217 QualType Ty = R->getDecl()->getType();
2218
2219 // Handle the case where we are accessing into a larger scalar object.
2220 // For example, this handles:
2221 // struct header {
2222 // unsigned a : 1;
2223 // unsigned b : 1;
2224 // };
2225 // struct parse_t {
2226 // unsigned bits0 : 1;
2227 // unsigned bits2 : 2; // <-- header
2228 // unsigned bits4 : 4;
2229 // };
2230 // int parse(parse_t *p) {
2231 // unsigned copy = p->bits2;
2232 // header *bits = (header *)&copy;
2233 // return bits->b; <-- here
2234 // }
2235 if (const auto *Base = dyn_cast<TypedValueRegion>(R->getBaseRegion()))
2236 if (auto V = getDerivedSymbolForBinding(B, Base, R, Ctx, svalBuilder))
2237 return *V;
2238
2239 return getBindingForFieldOrElementCommon(B, R, Ty);
2240}
2241
2242std::optional<SVal> RegionStoreManager::getBindingForDerivedDefaultValue(
2243 RegionBindingsConstRef B, const MemRegion *superR,
2244 const TypedValueRegion *R, QualType Ty) {
2245
2246 if (const std::optional<SVal> &D = B.getDefaultBinding(superR)) {
2247 SVal val = *D;
2248 if (SymbolRef parentSym = val.getAsSymbol())
2249 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
2250
2251 if (val.isZeroConstant())
2252 return svalBuilder.makeZeroVal(Ty);
2253
2254 if (val.isUnknownOrUndef())
2255 return val;
2256
2257 // Lazy bindings are usually handled through getExistingLazyBinding().
2258 // We should unify these two code paths at some point.
2260 return val;
2261
2262 llvm_unreachable("Unknown default value");
2263 }
2264
2265 return std::nullopt;
2266}
2267
2268SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion,
2269 RegionBindingsRef LazyBinding) {
2270 SVal Result;
2271 if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion))
2272 Result = getBindingForElement(LazyBinding, ER);
2273 else
2274 Result = getBindingForField(LazyBinding,
2275 cast<FieldRegion>(LazyBindingRegion));
2276
2277 // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
2278 // default value for /part/ of an aggregate from a default value for the
2279 // /entire/ aggregate. The most common case of this is when struct Outer
2280 // has as its first member a struct Inner, which is copied in from a stack
2281 // variable. In this case, even if the Outer's default value is symbolic, 0,
2282 // or unknown, it gets overridden by the Inner's default value of undefined.
2283 //
2284 // This is a general problem -- if the Inner is zero-initialized, the Outer
2285 // will now look zero-initialized. The proper way to solve this is with a
2286 // new version of RegionStore that tracks the extent of a binding as well
2287 // as the offset.
2288 //
2289 // This hack only takes care of the undefined case because that can very
2290 // quickly result in a warning.
2291 if (Result.isUndef())
2292 Result = UnknownVal();
2293
2294 return Result;
2295}
2296
2297SVal
2298RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
2299 const TypedValueRegion *R,
2300 QualType Ty) {
2301
2302 // At this point we have already checked in either getBindingForElement or
2303 // getBindingForField if 'R' has a direct binding.
2304
2305 // Lazy binding?
2306 Store lazyBindingStore = nullptr;
2307 const SubRegion *lazyBindingRegion = nullptr;
2308 std::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R);
2309 if (lazyBindingRegion)
2310 return getLazyBinding(lazyBindingRegion,
2311 getRegionBindings(lazyBindingStore));
2312
2313 // Record whether or not we see a symbolic index. That can completely
2314 // be out of scope of our lookup.
2315 bool hasSymbolicIndex = false;
2316
2317 // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
2318 // default value for /part/ of an aggregate from a default value for the
2319 // /entire/ aggregate. The most common case of this is when struct Outer
2320 // has as its first member a struct Inner, which is copied in from a stack
2321 // variable. In this case, even if the Outer's default value is symbolic, 0,
2322 // or unknown, it gets overridden by the Inner's default value of undefined.
2323 //
2324 // This is a general problem -- if the Inner is zero-initialized, the Outer
2325 // will now look zero-initialized. The proper way to solve this is with a
2326 // new version of RegionStore that tracks the extent of a binding as well
2327 // as the offset.
2328 //
2329 // This hack only takes care of the undefined case because that can very
2330 // quickly result in a warning.
2331 bool hasPartialLazyBinding = false;
2332
2333 const SubRegion *SR = R;
2334 while (SR) {
2335 const MemRegion *Base = SR->getSuperRegion();
2336 if (std::optional<SVal> D =
2337 getBindingForDerivedDefaultValue(B, Base, R, Ty)) {
2338 if (D->getAs<nonloc::LazyCompoundVal>()) {
2339 hasPartialLazyBinding = true;
2340 break;
2341 }
2342
2343 return *D;
2344 }
2345
2346 if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) {
2347 NonLoc index = ER->getIndex();
2348 if (!index.isConstant())
2349 hasSymbolicIndex = true;
2350 }
2351
2352 // If our super region is a field or element itself, walk up the region
2353 // hierarchy to see if there is a default value installed in an ancestor.
2354 SR = dyn_cast<SubRegion>(Base);
2355 }
2356
2357 if (isa<StackLocalsSpaceRegion>(R->getRawMemorySpace())) {
2358 if (isa<ElementRegion>(R)) {
2359 // Currently we don't reason specially about Clang-style vectors. Check
2360 // if superR is a vector and if so return Unknown.
2361 if (const TypedValueRegion *typedSuperR =
2362 dyn_cast<TypedValueRegion>(R->getSuperRegion())) {
2363 if (typedSuperR->getValueType()->isVectorType())
2364 return UnknownVal();
2365 }
2366 }
2367
2368 // FIXME: We also need to take ElementRegions with symbolic indexes into
2369 // account. This case handles both directly accessing an ElementRegion
2370 // with a symbolic offset, but also fields within an element with
2371 // a symbolic offset.
2372 if (hasSymbolicIndex)
2373 return UnknownVal();
2374
2375 // Additionally allow introspection of a block's internal layout.
2376 // Try to get direct binding if all other attempts failed thus far.
2377 // Else, return UndefinedVal()
2378 if (!hasPartialLazyBinding && !isa<BlockDataRegion>(R->getBaseRegion())) {
2379 if (const std::optional<SVal> &V = B.getDefaultBinding(R))
2380 return *V;
2381 return UndefinedVal();
2382 }
2383 }
2384
2385 // All other values are symbolic.
2386 return svalBuilder.getRegionValueSymbolVal(R);
2387}
2388
2389SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B,
2390 const ObjCIvarRegion* R) {
2391 // Check if the region has a binding.
2392 if (const std::optional<SVal> &V = B.getDirectBinding(R))
2393 return *V;
2394
2395 const MemRegion *superR = R->getSuperRegion();
2396
2397 // Check if the super region has a default binding.
2398 if (const std::optional<SVal> &V = B.getDefaultBinding(superR)) {
2399 if (SymbolRef parentSym = V->getAsSymbol())
2400 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
2401
2402 // Other cases: give up.
2403 return UnknownVal();
2404 }
2405
2406 return getBindingForLazySymbol(R);
2407}
2408
2409SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B,
2410 const VarRegion *R) {
2411
2412 // Check if the region has a binding.
2413 if (std::optional<SVal> V = B.getDirectBinding(R))
2414 return *V;
2415
2416 if (std::optional<SVal> V = B.getDefaultBinding(R))
2417 return *V;
2418
2419 // Lazily derive a value for the VarRegion.
2420 const VarDecl *VD = R->getDecl();
2421 const MemSpaceRegion *MS = R->getRawMemorySpace();
2422
2423 // Arguments are always symbolic.
2425 return svalBuilder.getRegionValueSymbolVal(R);
2426
2427 // Is 'VD' declared constant, or is it a function reference whose
2428 // binding is necessarily immutable? If so, retrieve the value
2429 // from its initializer.
2430 if (VD->getType().isConstQualified() ||
2432 if (const Expr *Init = VD->getAnyInitializer()) {
2433 if (std::optional<SVal> V = svalBuilder.getConstantVal(Init))
2434 return *V;
2435
2436 // If the variable has an immutable binding and an initializer but we
2437 // couldn't evaluate the initializer, treat the value as unknown.
2438 return UnknownVal();
2439 }
2440 }
2441
2442 // This must come after the check for constants because closure-captured
2443 // constant variables may appear in UnknownSpaceRegion.
2445 return svalBuilder.getRegionValueSymbolVal(R);
2446
2447 if (isa<GlobalsSpaceRegion>(MS)) {
2448 QualType T = VD->getType();
2449
2450 // If we're in main(), then global initializers have not become stale yet.
2451 if (B.isMainAnalysis())
2452 if (const Expr *Init = VD->getAnyInitializer())
2453 if (std::optional<SVal> V = svalBuilder.getConstantVal(Init))
2454 return *V;
2455
2456 // Function-scoped static variables are default-initialized to 0; if they
2457 // have an initializer, it would have been processed by now.
2458 // FIXME: This is only true when we're starting analysis from main().
2459 // We're losing a lot of coverage here.
2461 return svalBuilder.makeZeroVal(T);
2462
2463 if (std::optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) {
2464 assert(!V->getAs<nonloc::LazyCompoundVal>());
2465 return *V;
2466 }
2467
2468 return svalBuilder.getRegionValueSymbolVal(R);
2469 }
2470
2471 return UndefinedVal();
2472}
2473
2474SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
2475 // All other values are symbolic.
2476 return svalBuilder.getRegionValueSymbolVal(R);
2477}
2478
2479const RegionStoreManager::SValListTy &
2480RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) {
2481 // First, check the cache.
2482 LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData());
2483 if (I != LazyBindingsMap.end())
2484 return I->second;
2485
2486 // If we don't have a list of values cached, start constructing it.
2487 SValListTy List;
2488
2489 const SubRegion *LazyR = LCV.getRegion();
2490 RegionBindingsRef B = getRegionBindings(LCV.getStore());
2491
2492 // If this region had /no/ bindings at the time, there are no interesting
2493 // values to return.
2494 const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion());
2495 if (!Cluster)
2496 return (LazyBindingsMap[LCV.getCVData()] = std::move(List));
2497
2498 SmallVector<BindingPair, 32> Bindings;
2499 collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR,
2500 /*IncludeAllDefaultBindings=*/true);
2501 for (SVal V : llvm::make_second_range(Bindings)) {
2502 if (V.isUnknownOrUndef() || V.isConstant())
2503 continue;
2504
2505 if (auto InnerLCV = V.getAs<nonloc::LazyCompoundVal>()) {
2506 const SValListTy &InnerList = getInterestingValues(*InnerLCV);
2507 llvm::append_range(List, InnerList);
2508 }
2509
2510 List.push_back(V);
2511 }
2512
2513 return (LazyBindingsMap[LCV.getCVData()] = std::move(List));
2514}
2515
2516NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B,
2517 const TypedValueRegion *R) {
2518 if (std::optional<nonloc::LazyCompoundVal> V =
2519 getExistingLazyBinding(svalBuilder, B, R, false))
2520 return *V;
2521
2522 return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R);
2523}
2524
2525SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B,
2526 const TypedValueRegion *R) {
2527 const RecordDecl *RD =
2528 R->getValueType()->castAsCanonical<RecordType>()->getDecl();
2529 if (!RD->getDefinition())
2530 return UnknownVal();
2531
2532 // We also create a LCV for copying empty structs because then the store
2533 // behavior doesn't depend on the struct layout.
2534 // This way even an empty struct can carry taint, no matter if creduce drops
2535 // the last field member or not.
2536 return createLazyBinding(B, R);
2537}
2538
2539SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B,
2540 const TypedValueRegion *R) {
2541 assert(Ctx.getAsConstantArrayType(R->getValueType()) &&
2542 "Only constant array types can have compound bindings.");
2543
2544 return createLazyBinding(B, R);
2545}
2546
2547bool RegionStoreManager::includedInBindings(Store store,
2548 const MemRegion *region) const {
2549 RegionBindingsRef B = getRegionBindings(store);
2550 region = region->getBaseRegion();
2551
2552 // Quick path: if the base is the head of a cluster, the region is live.
2553 if (B.lookup(region))
2554 return true;
2555
2556 // Slow path: if the region is the VALUE of any binding, it is live.
2557 for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) {
2558 const ClusterBindings &Cluster = RI.getData();
2559 for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
2560 CI != CE; ++CI) {
2561 SVal D = CI.getData();
2562 if (const MemRegion *R = D.getAsRegion())
2563 if (R->getBaseRegion() == region)
2564 return true;
2565 }
2566 }
2567
2568 return false;
2569}
2570
2571//===----------------------------------------------------------------------===//
2572// Binding values to regions.
2573//===----------------------------------------------------------------------===//
2574
2575StoreRef RegionStoreManager::killBinding(Store ST, Loc L) {
2576 if (std::optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>())
2577 if (const MemRegion* R = LV->getRegion())
2578 return StoreRef(getRegionBindings(ST)
2579 .removeBinding(R)
2580 .asImmutableMap()
2581 .getRootWithoutRetain(),
2582 *this);
2583
2584 return StoreRef(ST, *this);
2585}
2586
2587LimitedRegionBindingsRef
2588RegionStoreManager::bind(LimitedRegionBindingsConstRef B, Loc L, SVal V) {
2589 llvm::TimeTraceScope TimeScope("RegionStoreManager::bind",
2590 [&L]() { return locDescr(L); });
2591
2593 return B.withValuesEscaped(V);
2594
2595 // We only care about region locations.
2596 auto MemRegVal = L.getAs<loc::MemRegionVal>();
2597 if (!MemRegVal)
2598 return B;
2599
2600 const MemRegion *R = MemRegVal->getRegion();
2601
2602 // Binding directly to a symbolic region should be treated as binding
2603 // to element 0.
2604 if (const auto *SymReg = dyn_cast<SymbolicRegion>(R)) {
2605 QualType Ty = SymReg->getPointeeStaticType();
2606 if (Ty->isVoidType())
2607 Ty = StateMgr.getContext().CharTy;
2608 R = GetElementZeroRegion(SymReg, Ty);
2609 }
2610
2611 // Check if the region is a struct region.
2612 if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) {
2613 QualType Ty = TR->getValueType();
2614 if (Ty->isArrayType())
2615 return bindArray(B, TR, V);
2616 if (Ty->isStructureOrClassType())
2617 return bindStruct(B, TR, V);
2618 if (Ty->isVectorType())
2619 return bindVector(B, TR, V);
2620 if (Ty->isUnionType())
2621 return bindAggregate(B, TR, V);
2622 }
2623
2624 assert((!isa<CXXThisRegion>(R) || !B.lookup(R)) &&
2625 "'this' pointer is not an l-value and is not assignable");
2626
2627 // Clear out bindings that may overlap with this binding.
2628 auto NewB = removeSubRegionBindings(B, cast<SubRegion>(R));
2629
2630 // LazyCompoundVals should be always bound as 'default' bindings.
2631 auto KeyKind = isa<nonloc::LazyCompoundVal>(V) ? BindingKey::Default
2632 : BindingKey::Direct;
2633 return NewB.addBinding(BindingKey::Make(R, KeyKind), V);
2634}
2635
2636LimitedRegionBindingsRef
2637RegionStoreManager::setImplicitDefaultValue(LimitedRegionBindingsConstRef B,
2638 const MemRegion *R, QualType T) {
2640 return B;
2641
2642 // Preserve an existing aggregate default binding. This handles partially
2643 // initialized union-containing aggregates where bindAggregate() may already
2644 // have installed a more precise default value at offset 0. Still allow
2645 // implicit defaults for scalars and pointers so regular zero-initialization
2646 // continues to work, e.g. for `new int[10]{}`.
2647 if (T->isAggregateType() && B.getDefaultBinding(R).has_value()) {
2648 return B;
2649 }
2650
2651 SVal V;
2652
2653 if (Loc::isLocType(T))
2654 V = svalBuilder.makeNullWithType(T);
2655 else if (T->isIntegralOrEnumerationType())
2656 V = svalBuilder.makeZeroVal(T);
2657 else if (T->isStructureOrClassType() || T->isArrayType()) {
2658 // Set the default value to a zero constant when it is a structure
2659 // or array. The type doesn't really matter.
2660 V = svalBuilder.makeZeroVal(Ctx.IntTy);
2661 }
2662 else {
2663 // We can't represent values of this type, but we still need to set a value
2664 // to record that the region has been initialized.
2665 // If this assertion ever fires, a new case should be added above -- we
2666 // should know how to default-initialize any value we can symbolicate.
2667 assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
2668 V = UnknownVal();
2669 }
2670
2671 return B.addBinding(R, BindingKey::Default, V);
2672}
2673
2674std::optional<LimitedRegionBindingsRef> RegionStoreManager::tryBindSmallArray(
2675 LimitedRegionBindingsConstRef B, const TypedValueRegion *R,
2676 const ArrayType *AT, nonloc::LazyCompoundVal LCV) {
2678 return B.withValuesEscaped(LCV);
2679
2680 auto CAT = dyn_cast<ConstantArrayType>(AT);
2681
2682 // If we don't know the size, create a lazyCompoundVal instead.
2683 if (!CAT)
2684 return std::nullopt;
2685
2686 QualType Ty = CAT->getElementType();
2687 if (!(Ty->isScalarType() || Ty->isReferenceType()))
2688 return std::nullopt;
2689
2690 // If the array is too big, create a LCV instead.
2691 uint64_t ArrSize = CAT->getLimitedSize();
2692 if (ArrSize > SmallArrayLimit)
2693 return std::nullopt;
2694
2695 LimitedRegionBindingsRef NewB = B;
2696
2697 for (uint64_t i = 0; i < ArrSize; ++i) {
2698 auto Idx = svalBuilder.makeArrayIndex(i);
2699 const ElementRegion *SrcER =
2700 MRMgr.getElementRegion(Ty, Idx, LCV.getRegion(), Ctx);
2701 SVal V = getBindingForElement(getRegionBindings(LCV.getStore()), SrcER);
2702
2703 const ElementRegion *DstER = MRMgr.getElementRegion(Ty, Idx, R, Ctx);
2704 NewB = bind(NewB, loc::MemRegionVal(DstER), V);
2705 }
2706
2707 return NewB;
2708}
2709
2710LimitedRegionBindingsRef
2711RegionStoreManager::bindArray(LimitedRegionBindingsConstRef B,
2712 const TypedValueRegion *R, SVal Init) {
2713 llvm::TimeTraceScope TimeScope("RegionStoreManager::bindArray",
2714 [R]() { return R->getDescriptiveName(); });
2716 return B.withValuesEscaped(Init);
2717
2718 const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
2719 QualType ElementTy = AT->getElementType();
2720 std::optional<uint64_t> Size;
2721
2722 if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
2723 Size = CAT->getZExtSize();
2724
2725 // Check if the init expr is a literal. If so, bind the rvalue instead.
2726 // FIXME: It's not responsibility of the Store to transform this lvalue
2727 // to rvalue. ExprEngine or maybe even CFG should do this before binding.
2728 if (std::optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) {
2729 SVal V = getBinding(B.asStore(), *MRV, R->getValueType());
2730 return bindAggregate(B, R, V);
2731 }
2732
2733 // FIXME Single value constant should have been handled before this call to
2734 // bindArray. This is only a hotfix to not crash.
2735 if (Init.isConstant())
2736 return bindAggregate(B, R, Init);
2737
2738 if (std::optional LCV = Init.getAs<nonloc::LazyCompoundVal>()) {
2739 if (std::optional NewB = tryBindSmallArray(B, R, AT, *LCV))
2740 return *NewB;
2741 return bindAggregate(B, R, Init);
2742 }
2743
2744 // We may get non-CompoundVal accidentally due to imprecise cast logic or
2745 // that we are binding a genuinely symbolic/unknown/undefined array value.
2746 // Preserve Init as a default binding rather than lossily converting to
2747 // UnknownVal(), and handle every non-CompoundVal case exhaustively (like
2748 // bindStruct()/bindVector() do) rather than enumerating specific SVal
2749 // kinds one at a time.
2752 return bindAggregate(B, R, Init);
2753 }
2754
2755 // Remaining case: explicit compound values.
2756 const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>();
2757 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2758 uint64_t i = 0;
2759
2760 LimitedRegionBindingsRef NewB = B;
2761
2762 for (; Size ? i < *Size : true; ++i, ++VI) {
2763 // The init list might be shorter than the array length.
2764 if (VI == VE)
2765 break;
2766 if (NewB.hasExhaustedBindingLimit())
2767 return NewB.withValuesEscaped(VI, VE);
2768
2769 NonLoc Idx = svalBuilder.makeArrayIndex(i);
2770 const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
2771
2772 if (ElementTy->isStructureOrClassType())
2773 NewB = bindStruct(NewB, ER, *VI);
2774 else if (ElementTy->isArrayType())
2775 NewB = bindArray(NewB, ER, *VI);
2776 else
2777 NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2778 }
2779
2780 // If the init list is shorter than the array length (or the array has
2781 // variable length), set the array default value. Values that are already set
2782 // are not overwritten.
2783 if (!Size || i < *Size)
2784 NewB = setImplicitDefaultValue(NewB, R, ElementTy);
2785
2786 return NewB;
2787}
2788
2789LimitedRegionBindingsRef
2790RegionStoreManager::bindVector(LimitedRegionBindingsConstRef B,
2791 const TypedValueRegion *R, SVal V) {
2792 llvm::TimeTraceScope TimeScope("RegionStoreManager::bindVector",
2793 [R]() { return R->getDescriptiveName(); });
2795 return B.withValuesEscaped(V);
2796
2797 QualType T = R->getValueType();
2798 const VectorType *VT = T->castAs<VectorType>(); // Use castAs for typedefs.
2799
2800 // Handle lazy compound values and symbolic values.
2802 return bindAggregate(B, R, V);
2803
2804 // We may get non-CompoundVal accidentally due to imprecise cast logic or
2805 // that we are binding symbolic struct value. Kill the field values, and if
2806 // the value is symbolic go and bind it as a "default" binding.
2808 return bindAggregate(B, R, UnknownVal());
2809 }
2810
2811 QualType ElemType = VT->getElementType();
2812 nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>();
2813 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2814 unsigned index = 0, numElements = VT->getNumElements();
2815 LimitedRegionBindingsRef NewB = B;
2816
2817 for ( ; index != numElements ; ++index) {
2818 if (VI == VE)
2819 break;
2820
2821 if (NewB.hasExhaustedBindingLimit())
2822 return NewB.withValuesEscaped(VI, VE);
2823
2824 NonLoc Idx = svalBuilder.makeArrayIndex(index);
2825 const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx);
2826
2827 if (ElemType->isArrayType())
2828 NewB = bindArray(NewB, ER, *VI);
2829 else if (ElemType->isStructureOrClassType())
2830 NewB = bindStruct(NewB, ER, *VI);
2831 else
2832 NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2833 }
2834 return NewB;
2835}
2836
2837std::optional<LimitedRegionBindingsRef> RegionStoreManager::tryBindSmallStruct(
2838 LimitedRegionBindingsConstRef B, const TypedValueRegion *R,
2839 const RecordDecl *RD, nonloc::LazyCompoundVal LCV) {
2841 return B.withValuesEscaped(LCV);
2842
2843 FieldVector Fields;
2844
2845 if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD))
2846 if (Class->getNumBases() != 0 || Class->getNumVBases() != 0)
2847 return std::nullopt;
2848
2849 for (const auto *FD : RD->fields()) {
2850 if (FD->isUnnamedBitField())
2851 continue;
2852
2853 // If there are too many fields, or if any of the fields are aggregates,
2854 // just use the LCV as a default binding.
2855 if (Fields.size() == SmallStructLimit)
2856 return std::nullopt;
2857
2858 QualType Ty = FD->getType();
2859
2860 // Zero length arrays are basically no-ops, so we also ignore them here.
2861 if (Ty->isConstantArrayType() &&
2863 continue;
2864
2865 if (!(Ty->isScalarType() || Ty->isReferenceType()))
2866 return std::nullopt;
2867
2868 Fields.push_back(FD);
2869 }
2870
2871 LimitedRegionBindingsRef NewB = B;
2872
2873 for (const FieldDecl *Field : Fields) {
2874 const FieldRegion *SourceFR = MRMgr.getFieldRegion(Field, LCV.getRegion());
2875 SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR);
2876
2877 const FieldRegion *DestFR = MRMgr.getFieldRegion(Field, R);
2878 NewB = bind(NewB, loc::MemRegionVal(DestFR), V);
2879 }
2880
2881 return NewB;
2882}
2883
2884LimitedRegionBindingsRef
2885RegionStoreManager::bindStruct(LimitedRegionBindingsConstRef B,
2886 const TypedValueRegion *R, SVal V) {
2887 llvm::TimeTraceScope TimeScope("RegionStoreManager::bindStruct",
2888 [R]() { return R->getDescriptiveName(); });
2890 return B.withValuesEscaped(V);
2891
2892 QualType T = R->getValueType();
2893 assert(T->isStructureOrClassType());
2894
2895 const auto *RD = T->castAsRecordDecl();
2896 if (!RD->isCompleteDefinition())
2897 return B;
2898
2899 // Handle lazy compound values and symbolic values.
2900 if (std::optional<nonloc::LazyCompoundVal> LCV =
2901 V.getAs<nonloc::LazyCompoundVal>()) {
2902 if (std::optional NewB = tryBindSmallStruct(B, R, RD, *LCV))
2903 return *NewB;
2904 return bindAggregate(B, R, V);
2905 }
2907 return bindAggregate(B, R, V);
2908
2909 // We may get non-CompoundVal accidentally due to imprecise cast logic or
2910 // that we are binding symbolic struct value. Kill the field values, and if
2911 // the value is symbolic go and bind it as a "default" binding.
2912 if (V.isUnknown() || !isa<nonloc::CompoundVal>(V))
2913 return bindAggregate(B, R, UnknownVal());
2914
2915 // The raw CompoundVal is essentially a symbolic InitListExpr: an (immutable)
2916 // list of other values. It appears pretty much only when there's an actual
2917 // initializer list expression in the program, and the analyzer tries to
2918 // unwrap it as soon as possible.
2919 // This code is where such unwrap happens: when the compound value is put into
2920 // the object that it was supposed to initialize (it's an *initializer* list,
2921 // after all), instead of binding the whole value to the whole object, we bind
2922 // sub-values to sub-objects. Sub-values may themselves be compound values,
2923 // and in this case the procedure becomes recursive.
2924 // FIXME: The annoying part about compound values is that they don't carry
2925 // any sort of information about which value corresponds to which sub-object.
2926 // It's simply a list of values in the middle of nowhere; we expect to match
2927 // them to sub-objects, essentially, "by index": first value binds to
2928 // the first field, second value binds to the second field, etc.
2929 // It would have been much safer to organize non-lazy compound values as
2930 // a mapping from fields/bases to values.
2931 const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>();
2932 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2933
2934 LimitedRegionBindingsRef NewB = B;
2935
2936 // In C++17 aggregates may have base classes, handle those as well.
2937 // They appear before fields in the initializer list / compound value.
2938 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
2939 // If the object was constructed with a constructor, its value is a
2940 // LazyCompoundVal. If it's a raw CompoundVal, it means that we're
2941 // performing aggregate initialization. The only exception from this
2942 // rule is sending an Objective-C++ message that returns a C++ object
2943 // to a nil receiver; in this case the semantics is to return a
2944 // zero-initialized object even if it's a C++ object that doesn't have
2945 // this sort of constructor; the CompoundVal is empty in this case.
2946 assert((CRD->isAggregate() || (Ctx.getLangOpts().ObjC && VI == VE)) &&
2947 "Non-aggregates are constructed with a constructor!");
2948
2949 for (const auto &B : CRD->bases()) {
2950 // (Multiple inheritance is fine though.)
2951 assert(!B.isVirtual() && "Aggregates cannot have virtual base classes!");
2952
2953 if (VI == VE)
2954 break;
2955 if (NewB.hasExhaustedBindingLimit())
2956 return NewB.withValuesEscaped(VI, VE);
2957
2958 QualType BTy = B.getType();
2959 assert(BTy->isStructureOrClassType() && "Base classes must be classes!");
2960
2961 const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl();
2962 assert(BRD && "Base classes must be C++ classes!");
2963
2964 const CXXBaseObjectRegion *BR =
2965 MRMgr.getCXXBaseObjectRegion(BRD, R, /*IsVirtual=*/false);
2966
2967 NewB = bindStruct(NewB, BR, *VI);
2968
2969 ++VI;
2970 }
2971 }
2972
2974
2975 for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
2976
2977 if (VI == VE)
2978 break;
2979
2980 if (NewB.hasExhaustedBindingLimit())
2981 return NewB.withValuesEscaped(VI, VE);
2982
2983 // Skip any unnamed bitfields to stay in sync with the initializers.
2984 if (FI->isUnnamedBitField())
2985 continue;
2986
2987 QualType FTy = FI->getType();
2988 const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
2989
2990 if (FTy->isArrayType())
2991 NewB = bindArray(NewB, FR, *VI);
2992 else if (FTy->isStructureOrClassType())
2993 NewB = bindStruct(NewB, FR, *VI);
2994 else
2995 NewB = bind(NewB, loc::MemRegionVal(FR), *VI);
2996 ++VI;
2997 }
2998
2999 if (NewB.hasExhaustedBindingLimit())
3000 return NewB.withValuesEscaped(VI, VE);
3001
3002 // There may be fewer values in the initialize list than the fields of struct.
3003 if (FI != FE) {
3004 NewB = NewB.addBinding(R, BindingKey::Default,
3005 svalBuilder.makeIntVal(0, false));
3006 }
3007
3008 return NewB;
3009}
3010
3011LimitedRegionBindingsRef
3012RegionStoreManager::bindAggregate(LimitedRegionBindingsConstRef B,
3013 const TypedRegion *R, SVal Val) {
3014 llvm::TimeTraceScope TimeScope("RegionStoreManager::bindAggregate",
3015 [R]() { return R->getDescriptiveName(); });
3017 return B.withValuesEscaped(Val);
3018
3019 // Remove the old bindings, using 'R' as the root of all regions
3020 // we will invalidate. Then add the new binding.
3021 return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val);
3022}
3023
3024//===----------------------------------------------------------------------===//
3025// State pruning.
3026//===----------------------------------------------------------------------===//
3027
3028namespace {
3029class RemoveDeadBindingsWorker
3030 : public ClusterAnalysis<RemoveDeadBindingsWorker> {
3031 SmallVector<const SymbolicRegion *, 12> Postponed;
3032 SymbolReaper &SymReaper;
3033 const StackFrame *CurrentSF;
3034
3035public:
3036 RemoveDeadBindingsWorker(RegionStoreManager &rm,
3037 ProgramStateManager &stateMgr, RegionBindingsRef b,
3038 SymbolReaper &symReaper, const StackFrame *SF)
3039 : ClusterAnalysis<RemoveDeadBindingsWorker>(rm, stateMgr, b),
3040 SymReaper(symReaper), CurrentSF(SF) {}
3041
3042 // Called by ClusterAnalysis.
3043 void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C);
3044 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
3045 using ClusterAnalysis<RemoveDeadBindingsWorker>::VisitCluster;
3046
3047 using ClusterAnalysis::AddToWorkList;
3048
3049 bool AddToWorkList(const MemRegion *R);
3050
3051 bool UpdatePostponed();
3052 void VisitBinding(SVal V);
3053};
3054}
3055
3056bool RemoveDeadBindingsWorker::AddToWorkList(const MemRegion *R) {
3057 const MemRegion *BaseR = R->getBaseRegion();
3058 return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR));
3059}
3060
3061void RemoveDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
3062 const ClusterBindings &C) {
3063
3064 if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
3065 if (SymReaper.isLive(VR))
3066 AddToWorkList(baseR, &C);
3067
3068 return;
3069 }
3070
3071 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
3072 if (SymReaper.isLive(SR->getSymbol()))
3073 AddToWorkList(SR, &C);
3074 else
3075 Postponed.push_back(SR);
3076
3077 return;
3078 }
3079
3081 AddToWorkList(baseR, &C);
3082 return;
3083 }
3084
3085 // CXXThisRegion in the current or parent stack frame is live.
3086 if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
3087 const auto *StackReg =
3089 const StackFrame *RegSF = StackReg->getStackFrame();
3090 if (CurrentSF && (RegSF == CurrentSF || RegSF->isParentOf(CurrentSF)))
3091 AddToWorkList(TR, &C);
3092 }
3093}
3094
3095void RemoveDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
3096 const ClusterBindings *C) {
3097 if (!C)
3098 return;
3099
3100 // Mark the symbol for any SymbolicRegion with live bindings as live itself.
3101 // This means we should continue to track that symbol.
3102 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR))
3103 SymReaper.markLive(SymR->getSymbol());
3104
3105 for (const auto &[Key, Val] : *C) {
3106 // Element index of a binding key is live.
3107 SymReaper.markElementIndicesLive(Key.getRegion());
3108
3109 VisitBinding(Val);
3110 }
3111}
3112
3113void RemoveDeadBindingsWorker::VisitBinding(SVal V) {
3114 // Is it a LazyCompoundVal? All referenced regions are live as well.
3115 // The LazyCompoundVal itself is not live but should be readable.
3116 if (auto LCS = V.getAs<nonloc::LazyCompoundVal>()) {
3117 SymReaper.markLazilyCopied(LCS->getRegion());
3118
3119 for (SVal V : RM.getInterestingValues(*LCS)) {
3120 if (auto DepLCS = V.getAs<nonloc::LazyCompoundVal>())
3121 SymReaper.markLazilyCopied(DepLCS->getRegion());
3122 else
3123 VisitBinding(V);
3124 }
3125
3126 return;
3127 }
3128
3129 // If V is a region, then add it to the worklist.
3130 if (const MemRegion *R = V.getAsRegion()) {
3131 AddToWorkList(R);
3132 SymReaper.markLive(R);
3133
3134 // All regions captured by a block are also live.
3135 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
3136 for (auto Var : BR->referenced_vars())
3137 AddToWorkList(Var.getCapturedRegion());
3138 }
3139 }
3140
3141
3142 // Update the set of live symbols.
3143 for (SymbolRef Sym : V.symbols())
3144 SymReaper.markLive(Sym);
3145}
3146
3147bool RemoveDeadBindingsWorker::UpdatePostponed() {
3148 // See if any postponed SymbolicRegions are actually live now, after
3149 // having done a scan.
3150 bool Changed = false;
3151
3152 for (const SymbolicRegion *SR : Postponed) {
3153 if (SymReaper.isLive(SR->getSymbol())) {
3154 Changed |= AddToWorkList(SR);
3155 SR = nullptr;
3156 }
3157 }
3158
3159 return Changed;
3160}
3161
3162StoreRef RegionStoreManager::removeDeadBindings(Store store,
3163 const StackFrame *SF,
3164 SymbolReaper &SymReaper) {
3165 RegionBindingsRef B = getRegionBindings(store);
3166 RemoveDeadBindingsWorker W(*this, StateMgr, B, SymReaper, SF);
3167 W.GenerateClusters();
3168
3169 // Enqueue the region roots onto the worklist.
3170 for (const MemRegion *Reg : SymReaper.regions()) {
3171 W.AddToWorkList(Reg);
3172 }
3173
3174 do W.RunWorkList(); while (W.UpdatePostponed());
3175
3176 // We have now scanned the store, marking reachable regions and symbols
3177 // as live. We now remove all the regions that are dead from the store
3178 // as well as update DSymbols with the set symbols that are now dead.
3179 // A cluster that has been visited has been marked live.
3180 B = B.filterClusters([&](const auto &E) { return W.isVisited(&E.second); });
3181
3182 return StoreRef(B.asStore(), *this);
3183}
3184
3185//===----------------------------------------------------------------------===//
3186// Utility methods.
3187//===----------------------------------------------------------------------===//
3188
3189void RegionStoreManager::printJson(raw_ostream &Out, Store S, const char *NL,
3190 unsigned int Space, bool IsDot) const {
3191 RegionBindingsRef Bindings = getRegionBindings(S);
3192
3193 Indent(Out, Space, IsDot) << "\"store\": ";
3194
3195 if (Bindings.isEmpty()) {
3196 Out << "null," << NL;
3197 return;
3198 }
3199
3200 Out << "{ \"pointer\": \"" << Bindings.asStore() << "\", \"items\": [" << NL;
3201 Bindings.printJson(Out, NL, Space + 1, IsDot);
3202 Indent(Out, Space, IsDot) << "]}," << NL;
3203}
#define V(N, I)
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
bool is(tok::TokenKind Kind) const
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
llvm::json::Array Array
static std::optional< SVal > convertOffsetsFromSvalToUnsigneds(const SmallVector< SVal, 2 > &SrcOffsets, const SmallVector< uint64_t, 2 > ArrayExtents, SmallVector< uint64_t, 2 > &DstOffsets)
llvm::ImmutableMap< const MemRegion *, ClusterBindings > RegionBindings
static std::optional< SVal > getDerivedSymbolForBinding(RegionBindingsConstRef B, const TypedValueRegion *BaseRegion, const TypedValueRegion *SubReg, const ASTContext &Ctx, SValBuilder &SVB)
std::pair< BindingKey, SVal > BindingPair
static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields)
SmallVector< const FieldDecl *, 8 > FieldVector
llvm::ImmutableMap< BindingKey, SVal > ClusterBindings
static bool isUnionField(const FieldRegion *FR)
const LimitedRegionBindingsRef & LimitedRegionBindingsConstRef
static void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields)
static QualType getUnderlyingType(const SubRegion *R)
llvm::ImmutableMapRef< BindingKey, SVal > ClusterBindingsRef
static SmallVector< uint64_t, 2 > getConstantArrayExtents(const ConstantArrayType *CAT)
This is a helper function for getConstantValFromConstArrayInitializer.
static std::pair< SmallVector< SVal, 2 >, const MemRegion * > getElementRegionOffsetsWithBase(const ElementRegion *ER)
This is a helper function for getConstantValFromConstArrayInitializer.
const RegionBindingsRef & RegionBindingsConstRef
static std::optional< nonloc::LazyCompoundVal > getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B, const SubRegion *R, bool AllowSubregionBindings)
Checks to see if store B has a lazy binding for region R.
static void collectSubRegionBindings(SmallVectorImpl< BindingPair > &Bindings, SValBuilder &SVB, const ClusterBindings &Cluster, const SubRegion *Top, BindingKey TopKey, bool IncludeAllDefaultBindings)
Collects all bindings in Cluster that may refer to bindings within Top.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
__PTRDIFF_TYPE__ ptrdiff_t
A signed integer type that is the result of subtracting two pointers.
This class represents the same as RegionBindingsRef, but with a limit on the number of bindings that ...
LimitedRegionBindingsRef removeCluster(const MemRegion *BaseRegion) const
LimitedRegionBindingsRef withValuesEscaped(nonloc::CompoundVal::iterator Begin, nonloc::CompoundVal::iterator End) const
LimitedRegionBindingsRef withValuesEscaped(SVal V) const
LimitedRegionBindingsRef(RegionBindingsRef Base, SmallVectorImpl< SVal > &EscapedValuesDuringBind, std::optional< unsigned > BindingsLeft)
bool hasExhaustedBindingLimit() const
LimitedRegionBindingsRef addBinding(BindingKey K, SVal V) const
LimitedRegionBindingsRef addBinding(const MemRegion *R, BindingKey::Kind k, SVal V) const
LimitedRegionBindingsRef addWithoutDecreasingLimit(const MemRegion *BaseRegion, data_type_ref BindingKeyAndValue) const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const ConstantArrayType * getAsConstantArrayType(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const LangOptions & getLangOpts() const
CanQualType IntTy
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static uint64_t getConstantArrayElementCount(const ConstantArrayType *CA)
Return number of (potentially nested) constant array elements.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getElementType() const
Definition TypeBase.h:3832
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition TypeBase.h:3947
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3934
bool hasAttr() const
Definition DeclBase.h:586
QualType getType() const
Definition Expr.h:146
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2487
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition Expr.h:5515
unsigned getNumInits() const
Definition Expr.h:5410
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5491
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
field_iterator field_end() const
Definition Decl.h:4712
field_range fields() const
Definition Decl.h:4709
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4690
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4706
field_iterator field_begin() const
Definition Decl.cpp:5386
bool isParentOf(const StackFrame *SF) const
const Decl * getDecl() const
unsigned getLength() const
Definition Expr.h:1969
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
Definition Expr.h:1931
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3999
bool isUnion() const
Definition Decl.h:4109
bool isVoidType() const
Definition TypeBase.h:9200
bool isFunctionReferenceType() const
Definition TypeBase.h:8889
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8918
bool isVoidPointerType() const
Definition Type.cpp:845
bool isArrayType() const
Definition TypeBase.h:8914
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isScalarType() const
Definition TypeBase.h:9310
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2638
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8950
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3200
bool isStructureOrClassType() const
Definition Type.cpp:839
bool isVectorType() const
Definition TypeBase.h:8954
bool isRecordType() const
Definition TypeBase.h:8942
bool isUnionType() const
Definition Type.cpp:851
QualType getType() const
Definition Decl.h:725
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1249
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1192
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1383
unsigned getNumElements() const
Definition TypeBase.h:4413
QualType getElementType() const
Definition TypeBase.h:4412
ElementRegion is used to represent both array elements and casts.
Definition MemRegion.h:1237
LLVM_ATTRIBUTE_RETURNS_NONNULL const FieldDecl * getDecl() const override
Definition MemRegion.h:1163
void dumpToStream(raw_ostream &Out) const
Definition SVals.cpp:379
static bool isLocType(QualType T)
Definition SVals.h:265
DefinedOrUnknownSVal getStaticSize(const MemRegion *MR, SValBuilder &SVB) const
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
virtual bool isBoundable() const
Definition MemRegion.h:210
RegionOffset getAsOffset() const
Compute the offset within the top level memory object.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
@ TK_PreserveContents
Tells that a region's contents is not changed.
Definition MemRegion.h:1678
@ TK_EntireMemSpace
When applied to a MemSpaceRegion, indicates the entire memory space should be invalidated.
Definition MemRegion.h:1688
bool hasTrait(SymbolRef Sym, InvalidationKinds IK) const
bool hasSymbolicOffset() const
Definition MemRegion.h:82
const MemRegion * getRegion() const
It might return null.
Definition MemRegion.h:80
int64_t getOffset() const
Definition MemRegion.h:84
const MemRegion * getRegion() const
Definition MemRegion.h:1230
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing '0' for the specified type.
NonLoc makeArrayIndex(uint64_t idx)
ASTContext & getContext()
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
SVal evalCast(SVal V, QualType CastTy, QualType OriginalTy)
Cast a given SVal to another SVal using given QualType's.
DefinedOrUnknownSVal getDerivedRegionValueSymbolVal(SymbolRef parentSymbol, const TypedValueRegion *region)
loc::ConcreteInt makeNullWithType(QualType type)
Create NULL pointer, with proper pointer bit-width for given address space.
std::optional< SVal > getConstantVal(const Expr *E)
Returns the value of E, if it can be determined in a non-path-sensitive manner.
DefinedOrUnknownSVal getRegionValueSymbolVal(const TypedValueRegion *region)
Make a unique symbol for value of region.
NonLoc makeLazyCompoundVal(const StoreRef &store, const TypedValueRegion *region)
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, ConstCFGElementRef elem, const StackFrame *SF, unsigned count)
Create a new symbol with a unique 'name'.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
bool isZeroConstant() const
Definition SVals.cpp:257
bool isUnknownOrUndef() const
Definition SVals.h:115
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition SVals.cpp:103
bool isConstant() const
Definition SVals.cpp:245
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition SVals.h:88
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:84
bool scan(nonloc::LazyCompoundVal val)
SmallVector< const MemRegion *, 8 > InvalidatedRegions
Definition Store.h:210
SubRegion - A region that subsets another larger region.
Definition MemRegion.h:480
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getSuperRegion() const
Definition MemRegion.h:493
bool isSubRegionOf(const MemRegion *R) const override
Check if the region is a subregion of the given region.
MemRegionManager & getMemRegionManager() const override
symbol_range symbols() const
Definition SymExpr.h:138
static bool canSymbolicate(QualType T)
void markElementIndicesLive(const MemRegion *region)
void markLazilyCopied(const MemRegion *region)
void markLive(SymbolRef Sym)
Unconditionally marks a symbol as live.
bool isLive(SymbolRef Sym)
llvm::iterator_range< RegionSetTy::const_iterator > regions() const
SymbolicRegion - A special, "non-concrete" region.
Definition MemRegion.h:813
TypedValueRegion - An abstract class representing regions having a typed value.
Definition MemRegion.h:569
virtual QualType getValueType() const =0
QualType getLocationType() const override
Definition MemRegion.h:580
QualType getValueType() const override
Definition MemRegion.h:1004
const VarDecl * getDecl() const override=0
llvm::ImmutableList< SVal >::iterator iterator
Definition SVals.h:355
Value representing integer constant.
Definition SVals.h:303
While nonloc::CompoundVal covers a few simple use cases, nonloc::LazyCompoundVal is a more performant...
Definition SVals.h:392
LLVM_ATTRIBUTE_RETURNS_NONNULL const LazyCompoundValData * getCVData() const
Definition SVals.h:402
LLVM_ATTRIBUTE_RETURNS_NONNULL const TypedValueRegion * getRegion() const
This function itself is immaterial.
Definition SVals.cpp:193
const void * getStore() const
It might return null.
Definition SVals.cpp:189
Defines the clang::TargetInfo interface.
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, DeclRefExpr > declRefExpr
Matches expressions that refer to declarations.
const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher > hasDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
internal::Matcher< Stmt > StatementMatcher
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition Store.h:50
const SymExpr * SymbolRef
Definition SymExpr.h:162
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
std::unique_ptr< StoreManager > CreateRegionStoreManager(ProgramStateManager &StMgr)
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Definition StoreRef.h:27
bool InitField(InterpState &S, CodePtr OpPC, uint32_t I)
1) Pops the value from the stack 2) Peeks a pointer from the stack 3) Pushes the value to field I of ...
Definition Interp.h:1911
Top level wrappers for InstallAPI frontend operations.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
bool isa(CodeGen::Address addr)
Definition Address.h:330
CFGBlock::ConstCFGElementRef ConstCFGElementRef
Definition CFG.h:1271
@ Bind
'bind' clause, allowed on routine constructs.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
const FunctionProtoType * T
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t