1 //===-- DataflowEnvironment.cpp ---------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines an Environment class that is used by dataflow analyses 10 // that run over Control-Flow Graphs (CFGs) to keep track of the state of the 11 // program at given program points. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h" 16 #include "clang/AST/Decl.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/Type.h" 19 #include "clang/Analysis/FlowSensitive/DataflowLattice.h" 20 #include "clang/Analysis/FlowSensitive/Value.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/DenseSet.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/Support/Casting.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include <cassert> 27 #include <memory> 28 #include <utility> 29 30 namespace clang { 31 namespace dataflow { 32 33 // FIXME: convert these to parameters of the analysis or environment. Current 34 // settings have been experimentaly validated, but only for a particular 35 // analysis. 36 static constexpr int MaxCompositeValueDepth = 3; 37 static constexpr int MaxCompositeValueSize = 1000; 38 39 /// Returns a map consisting of key-value entries that are present in both maps. 40 template <typename K, typename V> 41 llvm::DenseMap<K, V> intersectDenseMaps(const llvm::DenseMap<K, V> &Map1, 42 const llvm::DenseMap<K, V> &Map2) { 43 llvm::DenseMap<K, V> Result; 44 for (auto &Entry : Map1) { 45 auto It = Map2.find(Entry.first); 46 if (It != Map2.end() && Entry.second == It->second) 47 Result.insert({Entry.first, Entry.second}); 48 } 49 return Result; 50 } 51 52 static bool compareDistinctValues(QualType Type, Value &Val1, 53 const Environment &Env1, Value &Val2, 54 const Environment &Env2, 55 Environment::ValueModel &Model) { 56 // Note: Potentially costly, but, for booleans, we could check whether both 57 // can be proven equivalent in their respective environments. 58 59 // FIXME: move the reference/pointers logic from `areEquivalentValues` to here 60 // and implement separate, join/widen specific handling for 61 // reference/pointers. 62 switch (Model.compare(Type, Val1, Env1, Val2, Env2)) { 63 case ComparisonResult::Same: 64 return true; 65 case ComparisonResult::Different: 66 return false; 67 case ComparisonResult::Unknown: 68 switch (Val1.getKind()) { 69 case Value::Kind::Integer: 70 case Value::Kind::Reference: 71 case Value::Kind::Pointer: 72 case Value::Kind::Struct: 73 // FIXME: this choice intentionally introduces unsoundness to allow 74 // for convergence. Once we have widening support for the 75 // reference/pointer and struct built-in models, this should be 76 // `false`. 77 return true; 78 default: 79 return false; 80 } 81 } 82 llvm_unreachable("All cases covered in switch"); 83 } 84 85 /// Attempts to merge distinct values `Val1` and `Val2` in `Env1` and `Env2`, 86 /// respectively, of the same type `Type`. Merging generally produces a single 87 /// value that (soundly) approximates the two inputs, although the actual 88 /// meaning depends on `Model`. 89 static Value *mergeDistinctValues(QualType Type, Value &Val1, 90 const Environment &Env1, Value &Val2, 91 const Environment &Env2, 92 Environment &MergedEnv, 93 Environment::ValueModel &Model) { 94 // Join distinct boolean values preserving information about the constraints 95 // in the respective path conditions. 96 if (Type->isBooleanType()) { 97 // FIXME: The type check above is a workaround and should be unnecessary. 98 // However, right now we can end up with BoolValue's in integer-typed 99 // variables due to our incorrect handling of boolean-to-integer casts (we 100 // just propagate the BoolValue to the result of the cast). For example: 101 // std::optional<bool> o; 102 // 103 // 104 // int x; 105 // if (o.has_value()) { 106 // x = o.value(); 107 // } 108 auto *Expr1 = cast<BoolValue>(&Val1); 109 auto *Expr2 = cast<BoolValue>(&Val2); 110 auto &MergedVal = MergedEnv.makeAtomicBoolValue(); 111 MergedEnv.addToFlowCondition(MergedEnv.makeOr( 112 MergedEnv.makeAnd(Env1.getFlowConditionToken(), 113 MergedEnv.makeIff(MergedVal, *Expr1)), 114 MergedEnv.makeAnd(Env2.getFlowConditionToken(), 115 MergedEnv.makeIff(MergedVal, *Expr2)))); 116 return &MergedVal; 117 } 118 119 // FIXME: Consider destroying `MergedValue` immediately if `ValueModel::merge` 120 // returns false to avoid storing unneeded values in `DACtx`. 121 if (Value *MergedVal = MergedEnv.createValue(Type)) 122 if (Model.merge(Type, Val1, Env1, Val2, Env2, *MergedVal, MergedEnv)) 123 return MergedVal; 124 125 return nullptr; 126 } 127 128 // When widening does not change `Current`, return value will equal `&Prev`. 129 static Value &widenDistinctValues(QualType Type, Value &Prev, 130 const Environment &PrevEnv, Value &Current, 131 Environment &CurrentEnv, 132 Environment::ValueModel &Model) { 133 // Boolean-model widening. 134 if (isa<BoolValue>(&Prev)) { 135 assert(isa<BoolValue>(Current)); 136 // Widen to Top, because we know they are different values. If previous was 137 // already Top, re-use that to (implicitly) indicate that no change occured. 138 if (isa<TopBoolValue>(Prev)) 139 return Prev; 140 return CurrentEnv.makeTopBoolValue(); 141 } 142 143 // FIXME: Add other built-in model widening. 144 145 // Custom-model widening. 146 if (auto *W = Model.widen(Type, Prev, PrevEnv, Current, CurrentEnv)) 147 return *W; 148 149 // Default of widening is a no-op: leave the current value unchanged. 150 return Current; 151 } 152 153 /// Initializes a global storage value. 154 static void initGlobalVar(const VarDecl &D, Environment &Env) { 155 if (!D.hasGlobalStorage() || 156 Env.getStorageLocation(D, SkipPast::None) != nullptr) 157 return; 158 159 auto &Loc = Env.createStorageLocation(D); 160 Env.setStorageLocation(D, Loc); 161 if (auto *Val = Env.createValue(D.getType())) 162 Env.setValue(Loc, *Val); 163 } 164 165 /// Initializes a global storage value. 166 static void initGlobalVar(const Decl &D, Environment &Env) { 167 if (auto *V = dyn_cast<VarDecl>(&D)) 168 initGlobalVar(*V, Env); 169 } 170 171 /// Initializes global storage values that are declared or referenced from 172 /// sub-statements of `S`. 173 // FIXME: Add support for resetting globals after function calls to enable 174 // the implementation of sound analyses. 175 static void initGlobalVars(const Stmt &S, Environment &Env) { 176 for (auto *Child : S.children()) { 177 if (Child != nullptr) 178 initGlobalVars(*Child, Env); 179 } 180 181 if (auto *DS = dyn_cast<DeclStmt>(&S)) { 182 if (DS->isSingleDecl()) { 183 initGlobalVar(*DS->getSingleDecl(), Env); 184 } else { 185 for (auto *D : DS->getDeclGroup()) 186 initGlobalVar(*D, Env); 187 } 188 } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) { 189 initGlobalVar(*E->getDecl(), Env); 190 } else if (auto *E = dyn_cast<MemberExpr>(&S)) { 191 initGlobalVar(*E->getMemberDecl(), Env); 192 } 193 } 194 195 Environment::Environment(DataflowAnalysisContext &DACtx) 196 : DACtx(&DACtx), FlowConditionToken(&DACtx.makeFlowConditionToken()) {} 197 198 Environment::Environment(const Environment &Other) 199 : DACtx(Other.DACtx), CallStack(Other.CallStack), 200 ReturnLoc(Other.ReturnLoc), ThisPointeeLoc(Other.ThisPointeeLoc), 201 DeclToLoc(Other.DeclToLoc), ExprToLoc(Other.ExprToLoc), 202 LocToVal(Other.LocToVal), MemberLocToStruct(Other.MemberLocToStruct), 203 FlowConditionToken(&DACtx->forkFlowCondition(*Other.FlowConditionToken)) { 204 } 205 206 Environment &Environment::operator=(const Environment &Other) { 207 Environment Copy(Other); 208 *this = std::move(Copy); 209 return *this; 210 } 211 212 Environment::Environment(DataflowAnalysisContext &DACtx, 213 const DeclContext &DeclCtx) 214 : Environment(DACtx) { 215 CallStack.push_back(&DeclCtx); 216 217 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) { 218 assert(FuncDecl->getBody() != nullptr); 219 initGlobalVars(*FuncDecl->getBody(), *this); 220 for (const auto *ParamDecl : FuncDecl->parameters()) { 221 assert(ParamDecl != nullptr); 222 auto &ParamLoc = createStorageLocation(*ParamDecl); 223 setStorageLocation(*ParamDecl, ParamLoc); 224 if (Value *ParamVal = createValue(ParamDecl->getType())) 225 setValue(ParamLoc, *ParamVal); 226 } 227 228 QualType ReturnType = FuncDecl->getReturnType(); 229 ReturnLoc = &createStorageLocation(ReturnType); 230 } 231 232 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) { 233 auto *Parent = MethodDecl->getParent(); 234 assert(Parent != nullptr); 235 if (Parent->isLambda()) 236 MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext()); 237 238 // FIXME: Initialize the ThisPointeeLoc of lambdas too. 239 if (MethodDecl && !MethodDecl->isStatic()) { 240 QualType ThisPointeeType = MethodDecl->getThisObjectType(); 241 ThisPointeeLoc = &createStorageLocation(ThisPointeeType); 242 if (Value *ThisPointeeVal = createValue(ThisPointeeType)) 243 setValue(*ThisPointeeLoc, *ThisPointeeVal); 244 } 245 } 246 247 // Look for global variable references in the constructor-initializers. 248 if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(&DeclCtx)) { 249 for (const auto *Init : CtorDecl->inits()) { 250 const Expr *E = Init->getInit(); 251 assert(E != nullptr); 252 initGlobalVars(*E, *this); 253 } 254 } 255 } 256 257 bool Environment::canDescend(unsigned MaxDepth, 258 const DeclContext *Callee) const { 259 return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee); 260 } 261 262 Environment Environment::pushCall(const CallExpr *Call) const { 263 Environment Env(*this); 264 265 // FIXME: Support references here. 266 Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference); 267 268 if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) { 269 if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) { 270 if (!isa<CXXThisExpr>(Arg)) 271 Env.ThisPointeeLoc = getStorageLocation(*Arg, SkipPast::Reference); 272 // Otherwise (when the argument is `this`), retain the current 273 // environment's `ThisPointeeLoc`. 274 } 275 } 276 277 Env.pushCallInternal(Call->getDirectCallee(), 278 llvm::makeArrayRef(Call->getArgs(), Call->getNumArgs())); 279 280 return Env; 281 } 282 283 Environment Environment::pushCall(const CXXConstructExpr *Call) const { 284 Environment Env(*this); 285 286 // FIXME: Support references here. 287 Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference); 288 289 Env.ThisPointeeLoc = Env.ReturnLoc; 290 291 Env.pushCallInternal(Call->getConstructor(), 292 llvm::makeArrayRef(Call->getArgs(), Call->getNumArgs())); 293 294 return Env; 295 } 296 297 void Environment::pushCallInternal(const FunctionDecl *FuncDecl, 298 ArrayRef<const Expr *> Args) { 299 CallStack.push_back(FuncDecl); 300 301 // FIXME: In order to allow the callee to reference globals, we probably need 302 // to call `initGlobalVars` here in some way. 303 304 auto ParamIt = FuncDecl->param_begin(); 305 306 // FIXME: Parameters don't always map to arguments 1:1; examples include 307 // overloaded operators implemented as member functions, and parameter packs. 308 for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) { 309 assert(ParamIt != FuncDecl->param_end()); 310 311 const Expr *Arg = Args[ArgIndex]; 312 auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference); 313 if (ArgLoc == nullptr) 314 continue; 315 316 const VarDecl *Param = *ParamIt; 317 auto &Loc = createStorageLocation(*Param); 318 setStorageLocation(*Param, Loc); 319 320 QualType ParamType = Param->getType(); 321 if (ParamType->isReferenceType()) { 322 auto &Val = takeOwnership(std::make_unique<ReferenceValue>(*ArgLoc)); 323 setValue(Loc, Val); 324 } else if (auto *ArgVal = getValue(*ArgLoc)) { 325 setValue(Loc, *ArgVal); 326 } else if (Value *Val = createValue(ParamType)) { 327 setValue(Loc, *Val); 328 } 329 } 330 } 331 332 void Environment::popCall(const Environment &CalleeEnv) { 333 // We ignore `DACtx` because it's already the same in both. We don't want the 334 // callee's `DeclCtx`, `ReturnLoc` or `ThisPointeeLoc`. We don't bring back 335 // `DeclToLoc` and `ExprToLoc` because we want to be able to later analyze the 336 // same callee in a different context, and `setStorageLocation` requires there 337 // to not already be a storage location assigned. Conceptually, these maps 338 // capture information from the local scope, so when popping that scope, we do 339 // not propagate the maps. 340 this->LocToVal = std::move(CalleeEnv.LocToVal); 341 this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct); 342 this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken); 343 } 344 345 bool Environment::equivalentTo(const Environment &Other, 346 Environment::ValueModel &Model) const { 347 assert(DACtx == Other.DACtx); 348 349 if (ReturnLoc != Other.ReturnLoc) 350 return false; 351 352 if (ThisPointeeLoc != Other.ThisPointeeLoc) 353 return false; 354 355 if (DeclToLoc != Other.DeclToLoc) 356 return false; 357 358 if (ExprToLoc != Other.ExprToLoc) 359 return false; 360 361 // Compare the contents for the intersection of their domains. 362 for (auto &Entry : LocToVal) { 363 const StorageLocation *Loc = Entry.first; 364 assert(Loc != nullptr); 365 366 Value *Val = Entry.second; 367 assert(Val != nullptr); 368 369 auto It = Other.LocToVal.find(Loc); 370 if (It == Other.LocToVal.end()) 371 continue; 372 assert(It->second != nullptr); 373 374 if (!areEquivalentValues(*Val, *It->second) && 375 !compareDistinctValues(Loc->getType(), *Val, *this, *It->second, Other, 376 Model)) 377 return false; 378 } 379 380 return true; 381 } 382 383 LatticeJoinEffect Environment::widen(const Environment &PrevEnv, 384 Environment::ValueModel &Model) { 385 assert(DACtx == PrevEnv.DACtx); 386 assert(ReturnLoc == PrevEnv.ReturnLoc); 387 assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc); 388 assert(CallStack == PrevEnv.CallStack); 389 390 auto Effect = LatticeJoinEffect::Unchanged; 391 392 // By the API, `PrevEnv` is a previous version of the environment for the same 393 // block, so we have some guarantees about its shape. In particular, it will 394 // be the result of a join or widen operation on previous values for this 395 // block. For `DeclToLoc` and `ExprToLoc`, join guarantees that these maps are 396 // subsets of the maps in `PrevEnv`. So, as long as we maintain this property 397 // here, we don't need change their current values to widen. 398 // 399 // FIXME: `MemberLocToStruct` does not share the above property, because 400 // `join` can cause the map size to increase (when we add fresh data in places 401 // of conflict). Once this issue with join is resolved, re-enable the 402 // assertion below or replace with something that captures the desired 403 // invariant. 404 assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size()); 405 assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size()); 406 // assert(MemberLocToStruct.size() <= PrevEnv.MemberLocToStruct.size()); 407 408 llvm::DenseMap<const StorageLocation *, Value *> WidenedLocToVal; 409 for (auto &Entry : LocToVal) { 410 const StorageLocation *Loc = Entry.first; 411 assert(Loc != nullptr); 412 413 Value *Val = Entry.second; 414 assert(Val != nullptr); 415 416 auto PrevIt = PrevEnv.LocToVal.find(Loc); 417 if (PrevIt == PrevEnv.LocToVal.end()) 418 continue; 419 assert(PrevIt->second != nullptr); 420 421 if (areEquivalentValues(*Val, *PrevIt->second)) { 422 WidenedLocToVal.insert({Loc, Val}); 423 continue; 424 } 425 426 Value &WidenedVal = widenDistinctValues(Loc->getType(), *PrevIt->second, 427 PrevEnv, *Val, *this, Model); 428 WidenedLocToVal.insert({Loc, &WidenedVal}); 429 if (&WidenedVal != PrevIt->second) 430 Effect = LatticeJoinEffect::Changed; 431 } 432 LocToVal = std::move(WidenedLocToVal); 433 // FIXME: update the equivalence calculation for `MemberLocToStruct`, once we 434 // have a systematic way of soundly comparing this map. 435 if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() || 436 ExprToLoc.size() != PrevEnv.ExprToLoc.size() || 437 LocToVal.size() != PrevEnv.LocToVal.size() || 438 MemberLocToStruct.size() != PrevEnv.MemberLocToStruct.size()) 439 Effect = LatticeJoinEffect::Changed; 440 441 return Effect; 442 } 443 444 LatticeJoinEffect Environment::join(const Environment &Other, 445 Environment::ValueModel &Model) { 446 assert(DACtx == Other.DACtx); 447 assert(ReturnLoc == Other.ReturnLoc); 448 assert(ThisPointeeLoc == Other.ThisPointeeLoc); 449 assert(CallStack == Other.CallStack); 450 451 auto Effect = LatticeJoinEffect::Unchanged; 452 453 Environment JoinedEnv(*DACtx); 454 455 JoinedEnv.CallStack = CallStack; 456 JoinedEnv.ReturnLoc = ReturnLoc; 457 JoinedEnv.ThisPointeeLoc = ThisPointeeLoc; 458 459 JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc); 460 if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size()) 461 Effect = LatticeJoinEffect::Changed; 462 463 JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc); 464 if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size()) 465 Effect = LatticeJoinEffect::Changed; 466 467 JoinedEnv.MemberLocToStruct = 468 intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct); 469 if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size()) 470 Effect = LatticeJoinEffect::Changed; 471 472 // FIXME: set `Effect` as needed. 473 // FIXME: update join to detect backedges and simplify the flow condition 474 // accordingly. 475 JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions( 476 *FlowConditionToken, *Other.FlowConditionToken); 477 478 for (auto &Entry : LocToVal) { 479 const StorageLocation *Loc = Entry.first; 480 assert(Loc != nullptr); 481 482 Value *Val = Entry.second; 483 assert(Val != nullptr); 484 485 auto It = Other.LocToVal.find(Loc); 486 if (It == Other.LocToVal.end()) 487 continue; 488 assert(It->second != nullptr); 489 490 if (areEquivalentValues(*Val, *It->second)) { 491 JoinedEnv.LocToVal.insert({Loc, Val}); 492 continue; 493 } 494 495 if (Value *MergedVal = 496 mergeDistinctValues(Loc->getType(), *Val, *this, *It->second, Other, 497 JoinedEnv, Model)) { 498 JoinedEnv.LocToVal.insert({Loc, MergedVal}); 499 Effect = LatticeJoinEffect::Changed; 500 } 501 } 502 if (LocToVal.size() != JoinedEnv.LocToVal.size()) 503 Effect = LatticeJoinEffect::Changed; 504 505 *this = std::move(JoinedEnv); 506 507 return Effect; 508 } 509 510 StorageLocation &Environment::createStorageLocation(QualType Type) { 511 return DACtx->createStorageLocation(Type); 512 } 513 514 StorageLocation &Environment::createStorageLocation(const VarDecl &D) { 515 // Evaluated declarations are always assigned the same storage locations to 516 // ensure that the environment stabilizes across loop iterations. Storage 517 // locations for evaluated declarations are stored in the analysis context. 518 return DACtx->getStableStorageLocation(D); 519 } 520 521 StorageLocation &Environment::createStorageLocation(const Expr &E) { 522 // Evaluated expressions are always assigned the same storage locations to 523 // ensure that the environment stabilizes across loop iterations. Storage 524 // locations for evaluated expressions are stored in the analysis context. 525 return DACtx->getStableStorageLocation(E); 526 } 527 528 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) { 529 assert(DeclToLoc.find(&D) == DeclToLoc.end()); 530 DeclToLoc[&D] = &Loc; 531 } 532 533 StorageLocation *Environment::getStorageLocation(const ValueDecl &D, 534 SkipPast SP) const { 535 auto It = DeclToLoc.find(&D); 536 return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP); 537 } 538 539 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) { 540 const Expr &CanonE = ignoreCFGOmittedNodes(E); 541 assert(ExprToLoc.find(&CanonE) == ExprToLoc.end()); 542 ExprToLoc[&CanonE] = &Loc; 543 } 544 545 StorageLocation *Environment::getStorageLocation(const Expr &E, 546 SkipPast SP) const { 547 // FIXME: Add a test with parens. 548 auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E)); 549 return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP); 550 } 551 552 StorageLocation *Environment::getThisPointeeStorageLocation() const { 553 return ThisPointeeLoc; 554 } 555 556 StorageLocation *Environment::getReturnStorageLocation() const { 557 return ReturnLoc; 558 } 559 560 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) { 561 return DACtx->getOrCreateNullPointerValue(PointeeType); 562 } 563 564 void Environment::setValue(const StorageLocation &Loc, Value &Val) { 565 LocToVal[&Loc] = &Val; 566 567 if (auto *StructVal = dyn_cast<StructValue>(&Val)) { 568 auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc); 569 570 const QualType Type = AggregateLoc.getType(); 571 assert(Type->isStructureOrClassType() || Type->isUnionType()); 572 573 for (const FieldDecl *Field : getObjectFields(Type)) { 574 assert(Field != nullptr); 575 StorageLocation &FieldLoc = AggregateLoc.getChild(*Field); 576 MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field); 577 if (auto *FieldVal = StructVal->getChild(*Field)) 578 setValue(FieldLoc, *FieldVal); 579 } 580 } 581 582 auto It = MemberLocToStruct.find(&Loc); 583 if (It != MemberLocToStruct.end()) { 584 // `Loc` is the location of a struct member so we need to also update the 585 // value of the member in the corresponding `StructValue`. 586 587 assert(It->second.first != nullptr); 588 StructValue &StructVal = *It->second.first; 589 590 assert(It->second.second != nullptr); 591 const ValueDecl &Member = *It->second.second; 592 593 StructVal.setChild(Member, Val); 594 } 595 } 596 597 Value *Environment::getValue(const StorageLocation &Loc) const { 598 auto It = LocToVal.find(&Loc); 599 return It == LocToVal.end() ? nullptr : It->second; 600 } 601 602 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const { 603 auto *Loc = getStorageLocation(D, SP); 604 if (Loc == nullptr) 605 return nullptr; 606 return getValue(*Loc); 607 } 608 609 Value *Environment::getValue(const Expr &E, SkipPast SP) const { 610 auto *Loc = getStorageLocation(E, SP); 611 if (Loc == nullptr) 612 return nullptr; 613 return getValue(*Loc); 614 } 615 616 Value *Environment::createValue(QualType Type) { 617 llvm::DenseSet<QualType> Visited; 618 int CreatedValuesCount = 0; 619 Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0, 620 CreatedValuesCount); 621 if (CreatedValuesCount > MaxCompositeValueSize) { 622 llvm::errs() << "Attempting to initialize a huge value of type: " << Type 623 << '\n'; 624 } 625 return Val; 626 } 627 628 Value *Environment::createValueUnlessSelfReferential( 629 QualType Type, llvm::DenseSet<QualType> &Visited, int Depth, 630 int &CreatedValuesCount) { 631 assert(!Type.isNull()); 632 633 // Allow unlimited fields at depth 1; only cap at deeper nesting levels. 634 if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) || 635 Depth > MaxCompositeValueDepth) 636 return nullptr; 637 638 if (Type->isBooleanType()) { 639 CreatedValuesCount++; 640 return &makeAtomicBoolValue(); 641 } 642 643 if (Type->isIntegerType()) { 644 // FIXME: consider instead `return nullptr`, given that we do nothing useful 645 // with integers, and so distinguishing them serves no purpose, but could 646 // prevent convergence. 647 CreatedValuesCount++; 648 return &takeOwnership(std::make_unique<IntegerValue>()); 649 } 650 651 if (Type->isReferenceType()) { 652 CreatedValuesCount++; 653 QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType(); 654 auto &PointeeLoc = createStorageLocation(PointeeType); 655 656 if (Visited.insert(PointeeType.getCanonicalType()).second) { 657 Value *PointeeVal = createValueUnlessSelfReferential( 658 PointeeType, Visited, Depth, CreatedValuesCount); 659 Visited.erase(PointeeType.getCanonicalType()); 660 661 if (PointeeVal != nullptr) 662 setValue(PointeeLoc, *PointeeVal); 663 } 664 665 return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc)); 666 } 667 668 if (Type->isPointerType()) { 669 CreatedValuesCount++; 670 QualType PointeeType = Type->castAs<PointerType>()->getPointeeType(); 671 auto &PointeeLoc = createStorageLocation(PointeeType); 672 673 if (Visited.insert(PointeeType.getCanonicalType()).second) { 674 Value *PointeeVal = createValueUnlessSelfReferential( 675 PointeeType, Visited, Depth, CreatedValuesCount); 676 Visited.erase(PointeeType.getCanonicalType()); 677 678 if (PointeeVal != nullptr) 679 setValue(PointeeLoc, *PointeeVal); 680 } 681 682 return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc)); 683 } 684 685 if (Type->isStructureOrClassType() || Type->isUnionType()) { 686 CreatedValuesCount++; 687 // FIXME: Initialize only fields that are accessed in the context that is 688 // being analyzed. 689 llvm::DenseMap<const ValueDecl *, Value *> FieldValues; 690 for (const FieldDecl *Field : getObjectFields(Type)) { 691 assert(Field != nullptr); 692 693 QualType FieldType = Field->getType(); 694 if (Visited.contains(FieldType.getCanonicalType())) 695 continue; 696 697 Visited.insert(FieldType.getCanonicalType()); 698 if (auto *FieldValue = createValueUnlessSelfReferential( 699 FieldType, Visited, Depth + 1, CreatedValuesCount)) 700 FieldValues.insert({Field, FieldValue}); 701 Visited.erase(FieldType.getCanonicalType()); 702 } 703 704 return &takeOwnership( 705 std::make_unique<StructValue>(std::move(FieldValues))); 706 } 707 708 return nullptr; 709 } 710 711 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const { 712 switch (SP) { 713 case SkipPast::None: 714 return Loc; 715 case SkipPast::Reference: 716 // References cannot be chained so we only need to skip past one level of 717 // indirection. 718 if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc))) 719 return Val->getReferentLoc(); 720 return Loc; 721 case SkipPast::ReferenceThenPointer: 722 StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference); 723 if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef))) 724 return Val->getPointeeLoc(); 725 return LocPastRef; 726 } 727 llvm_unreachable("bad SkipPast kind"); 728 } 729 730 const StorageLocation &Environment::skip(const StorageLocation &Loc, 731 SkipPast SP) const { 732 return skip(*const_cast<StorageLocation *>(&Loc), SP); 733 } 734 735 void Environment::addToFlowCondition(BoolValue &Val) { 736 DACtx->addFlowConditionConstraint(*FlowConditionToken, Val); 737 } 738 739 bool Environment::flowConditionImplies(BoolValue &Val) const { 740 return DACtx->flowConditionImplies(*FlowConditionToken, Val); 741 } 742 743 void Environment::dump() const { 744 DACtx->dumpFlowCondition(*FlowConditionToken); 745 } 746 747 } // namespace dataflow 748 } // namespace clang 749