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/MapVector.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include <cassert> 27 #include <utility> 28 29 namespace clang { 30 namespace dataflow { 31 32 // FIXME: convert these to parameters of the analysis or environment. Current 33 // settings have been experimentaly validated, but only for a particular 34 // analysis. 35 static constexpr int MaxCompositeValueDepth = 3; 36 static constexpr int MaxCompositeValueSize = 1000; 37 38 /// Returns a map consisting of key-value entries that are present in both maps. 39 static llvm::DenseMap<const ValueDecl *, StorageLocation *> intersectDeclToLoc( 40 const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc1, 41 const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc2) { 42 llvm::DenseMap<const ValueDecl *, StorageLocation *> Result; 43 for (auto &Entry : DeclToLoc1) { 44 auto It = DeclToLoc2.find(Entry.first); 45 if (It != DeclToLoc2.end() && Entry.second == It->second) 46 Result.insert({Entry.first, Entry.second}); 47 } 48 return Result; 49 } 50 51 // Whether to consider equivalent two values with an unknown relation. 52 // 53 // FIXME: this function is a hack enabling unsoundness to support 54 // convergence. Once we have widening support for the reference/pointer and 55 // struct built-in models, this should be unconditionally `false` (and inlined 56 // as such at its call sites). 57 static bool equateUnknownValues(Value::Kind K) { 58 switch (K) { 59 case Value::Kind::Integer: 60 case Value::Kind::Pointer: 61 case Value::Kind::Record: 62 return true; 63 default: 64 return false; 65 } 66 } 67 68 static bool compareDistinctValues(QualType Type, Value &Val1, 69 const Environment &Env1, Value &Val2, 70 const Environment &Env2, 71 Environment::ValueModel &Model) { 72 // Note: Potentially costly, but, for booleans, we could check whether both 73 // can be proven equivalent in their respective environments. 74 75 // FIXME: move the reference/pointers logic from `areEquivalentValues` to here 76 // and implement separate, join/widen specific handling for 77 // reference/pointers. 78 switch (Model.compare(Type, Val1, Env1, Val2, Env2)) { 79 case ComparisonResult::Same: 80 return true; 81 case ComparisonResult::Different: 82 return false; 83 case ComparisonResult::Unknown: 84 return equateUnknownValues(Val1.getKind()); 85 } 86 llvm_unreachable("All cases covered in switch"); 87 } 88 89 /// Attempts to merge distinct values `Val1` and `Val2` in `Env1` and `Env2`, 90 /// respectively, of the same type `Type`. Merging generally produces a single 91 /// value that (soundly) approximates the two inputs, although the actual 92 /// meaning depends on `Model`. 93 static Value *mergeDistinctValues(QualType Type, Value &Val1, 94 const Environment &Env1, Value &Val2, 95 const Environment &Env2, 96 Environment &MergedEnv, 97 Environment::ValueModel &Model) { 98 // Join distinct boolean values preserving information about the constraints 99 // in the respective path conditions. 100 if (isa<BoolValue>(&Val1) && isa<BoolValue>(&Val2)) { 101 // FIXME: Checking both values should be unnecessary, since they should have 102 // a consistent shape. However, right now we can end up with BoolValue's in 103 // integer-typed variables due to our incorrect handling of 104 // boolean-to-integer casts (we just propagate the BoolValue to the result 105 // of the cast). So, a join can encounter an integer in one branch but a 106 // bool in the other. 107 // For example: 108 // ``` 109 // std::optional<bool> o; 110 // int x; 111 // if (o.has_value()) 112 // x = o.value(); 113 // ``` 114 auto &Expr1 = cast<BoolValue>(Val1).formula(); 115 auto &Expr2 = cast<BoolValue>(Val2).formula(); 116 auto &A = MergedEnv.arena(); 117 auto &MergedVal = A.makeAtomRef(A.makeAtom()); 118 MergedEnv.assume( 119 A.makeOr(A.makeAnd(A.makeAtomRef(Env1.getFlowConditionToken()), 120 A.makeEquals(MergedVal, Expr1)), 121 A.makeAnd(A.makeAtomRef(Env2.getFlowConditionToken()), 122 A.makeEquals(MergedVal, Expr2)))); 123 return &A.makeBoolValue(MergedVal); 124 } 125 126 Value *MergedVal = nullptr; 127 if (auto *RecordVal1 = dyn_cast<RecordValue>(&Val1)) { 128 auto *RecordVal2 = cast<RecordValue>(&Val2); 129 130 if (&RecordVal1->getLoc() == &RecordVal2->getLoc()) 131 // `RecordVal1` and `RecordVal2` may have different properties associated 132 // with them. Create a new `RecordValue` with the same location but 133 // without any properties so that we soundly approximate both values. If a 134 // particular analysis needs to merge properties, it should do so in 135 // `DataflowAnalysis::merge()`. 136 MergedVal = &MergedEnv.create<RecordValue>(RecordVal1->getLoc()); 137 else 138 // If the locations for the two records are different, need to create a 139 // completely new value. 140 MergedVal = MergedEnv.createValue(Type); 141 } else { 142 MergedVal = MergedEnv.createValue(Type); 143 } 144 145 // FIXME: Consider destroying `MergedValue` immediately if `ValueModel::merge` 146 // returns false to avoid storing unneeded values in `DACtx`. 147 if (MergedVal) 148 if (Model.merge(Type, Val1, Env1, Val2, Env2, *MergedVal, MergedEnv)) 149 return MergedVal; 150 151 return nullptr; 152 } 153 154 // When widening does not change `Current`, return value will equal `&Prev`. 155 static Value &widenDistinctValues(QualType Type, Value &Prev, 156 const Environment &PrevEnv, Value &Current, 157 Environment &CurrentEnv, 158 Environment::ValueModel &Model) { 159 // Boolean-model widening. 160 if (auto *PrevBool = dyn_cast<BoolValue>(&Prev)) { 161 // If previous value was already Top, re-use that to (implicitly) indicate 162 // that no change occurred. 163 if (isa<TopBoolValue>(Prev)) 164 return Prev; 165 166 // We may need to widen to Top, but before we do so, check whether both 167 // values are implied to be either true or false in the current environment. 168 // In that case, we can simply return a literal instead. 169 auto &CurBool = cast<BoolValue>(Current); 170 bool TruePrev = PrevEnv.proves(PrevBool->formula()); 171 bool TrueCur = CurrentEnv.proves(CurBool.formula()); 172 if (TruePrev && TrueCur) 173 return CurrentEnv.getBoolLiteralValue(true); 174 if (!TruePrev && !TrueCur && 175 PrevEnv.proves(PrevEnv.arena().makeNot(PrevBool->formula())) && 176 CurrentEnv.proves(CurrentEnv.arena().makeNot(CurBool.formula()))) 177 return CurrentEnv.getBoolLiteralValue(false); 178 179 return CurrentEnv.makeTopBoolValue(); 180 } 181 182 // FIXME: Add other built-in model widening. 183 184 // Custom-model widening. 185 if (auto *W = Model.widen(Type, Prev, PrevEnv, Current, CurrentEnv)) 186 return *W; 187 188 return equateUnknownValues(Prev.getKind()) ? Prev : Current; 189 } 190 191 // Returns whether the values in `Map1` and `Map2` compare equal for those 192 // keys that `Map1` and `Map2` have in common. 193 template <typename Key> 194 bool compareKeyToValueMaps(const llvm::MapVector<Key, Value *> &Map1, 195 const llvm::MapVector<Key, Value *> &Map2, 196 const Environment &Env1, const Environment &Env2, 197 Environment::ValueModel &Model) { 198 for (auto &Entry : Map1) { 199 Key K = Entry.first; 200 assert(K != nullptr); 201 202 Value *Val = Entry.second; 203 assert(Val != nullptr); 204 205 auto It = Map2.find(K); 206 if (It == Map2.end()) 207 continue; 208 assert(It->second != nullptr); 209 210 if (!areEquivalentValues(*Val, *It->second) && 211 !compareDistinctValues(K->getType(), *Val, Env1, *It->second, Env2, 212 Model)) 213 return false; 214 } 215 216 return true; 217 } 218 219 // Perform a join on two `LocToVal` maps. 220 static llvm::MapVector<const StorageLocation *, Value *> 221 joinLocToVal(const llvm::MapVector<const StorageLocation *, Value *> &LocToVal, 222 const llvm::MapVector<const StorageLocation *, Value *> &LocToVal2, 223 const Environment &Env1, const Environment &Env2, 224 Environment &JoinedEnv, Environment::ValueModel &Model) { 225 llvm::MapVector<const StorageLocation *, Value *> Result; 226 for (auto &Entry : LocToVal) { 227 const StorageLocation *Loc = Entry.first; 228 assert(Loc != nullptr); 229 230 Value *Val = Entry.second; 231 assert(Val != nullptr); 232 233 auto It = LocToVal2.find(Loc); 234 if (It == LocToVal2.end()) 235 continue; 236 assert(It->second != nullptr); 237 238 if (areEquivalentValues(*Val, *It->second)) { 239 Result.insert({Loc, Val}); 240 continue; 241 } 242 243 if (Value *MergedVal = mergeDistinctValues( 244 Loc->getType(), *Val, Env1, *It->second, Env2, JoinedEnv, Model)) { 245 Result.insert({Loc, MergedVal}); 246 } 247 } 248 249 return Result; 250 } 251 252 // Perform widening on either `LocToVal` or `ExprToVal`. `Key` must be either 253 // `const StorageLocation *` or `const Expr *`. 254 template <typename Key> 255 llvm::MapVector<Key, Value *> 256 widenKeyToValueMap(const llvm::MapVector<Key, Value *> &CurMap, 257 const llvm::MapVector<Key, Value *> &PrevMap, 258 Environment &CurEnv, const Environment &PrevEnv, 259 Environment::ValueModel &Model, LatticeJoinEffect &Effect) { 260 llvm::MapVector<Key, Value *> WidenedMap; 261 for (auto &Entry : CurMap) { 262 Key K = Entry.first; 263 assert(K != nullptr); 264 265 Value *Val = Entry.second; 266 assert(Val != nullptr); 267 268 auto PrevIt = PrevMap.find(K); 269 if (PrevIt == PrevMap.end()) 270 continue; 271 assert(PrevIt->second != nullptr); 272 273 if (areEquivalentValues(*Val, *PrevIt->second)) { 274 WidenedMap.insert({K, Val}); 275 continue; 276 } 277 278 Value &WidenedVal = widenDistinctValues(K->getType(), *PrevIt->second, 279 PrevEnv, *Val, CurEnv, Model); 280 WidenedMap.insert({K, &WidenedVal}); 281 if (&WidenedVal != PrevIt->second) 282 Effect = LatticeJoinEffect::Changed; 283 } 284 285 return WidenedMap; 286 } 287 288 /// Initializes a global storage value. 289 static void insertIfGlobal(const Decl &D, 290 llvm::DenseSet<const VarDecl *> &Vars) { 291 if (auto *V = dyn_cast<VarDecl>(&D)) 292 if (V->hasGlobalStorage()) 293 Vars.insert(V); 294 } 295 296 static void insertIfFunction(const Decl &D, 297 llvm::DenseSet<const FunctionDecl *> &Funcs) { 298 if (auto *FD = dyn_cast<FunctionDecl>(&D)) 299 Funcs.insert(FD); 300 } 301 302 static MemberExpr *getMemberForAccessor(const CXXMemberCallExpr &C) { 303 if (!C.getMethodDecl()) 304 return nullptr; 305 auto *Body = dyn_cast_or_null<CompoundStmt>(C.getMethodDecl()->getBody()); 306 if (!Body || Body->size() != 1) 307 return nullptr; 308 if (auto *RS = dyn_cast<ReturnStmt>(*Body->body_begin())) 309 if (auto *Return = RS->getRetValue()) 310 return dyn_cast<MemberExpr>(Return->IgnoreParenImpCasts()); 311 return nullptr; 312 } 313 314 static void 315 getFieldsGlobalsAndFuncs(const Decl &D, FieldSet &Fields, 316 llvm::DenseSet<const VarDecl *> &Vars, 317 llvm::DenseSet<const FunctionDecl *> &Funcs) { 318 insertIfGlobal(D, Vars); 319 insertIfFunction(D, Funcs); 320 if (const auto *Decomp = dyn_cast<DecompositionDecl>(&D)) 321 for (const auto *B : Decomp->bindings()) 322 if (auto *ME = dyn_cast_or_null<MemberExpr>(B->getBinding())) 323 // FIXME: should we be using `E->getFoundDecl()`? 324 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 325 Fields.insert(FD); 326 } 327 328 /// Traverses `S` and inserts into `Fields`, `Vars` and `Funcs` any fields, 329 /// global variables and functions that are declared in or referenced from 330 /// sub-statements. 331 static void 332 getFieldsGlobalsAndFuncs(const Stmt &S, FieldSet &Fields, 333 llvm::DenseSet<const VarDecl *> &Vars, 334 llvm::DenseSet<const FunctionDecl *> &Funcs) { 335 for (auto *Child : S.children()) 336 if (Child != nullptr) 337 getFieldsGlobalsAndFuncs(*Child, Fields, Vars, Funcs); 338 if (const auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(&S)) 339 getFieldsGlobalsAndFuncs(*DefaultInit->getExpr(), Fields, Vars, Funcs); 340 341 if (auto *DS = dyn_cast<DeclStmt>(&S)) { 342 if (DS->isSingleDecl()) 343 getFieldsGlobalsAndFuncs(*DS->getSingleDecl(), Fields, Vars, Funcs); 344 else 345 for (auto *D : DS->getDeclGroup()) 346 getFieldsGlobalsAndFuncs(*D, Fields, Vars, Funcs); 347 } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) { 348 insertIfGlobal(*E->getDecl(), Vars); 349 insertIfFunction(*E->getDecl(), Funcs); 350 } else if (const auto *C = dyn_cast<CXXMemberCallExpr>(&S)) { 351 // If this is a method that returns a member variable but does nothing else, 352 // model the field of the return value. 353 if (MemberExpr *E = getMemberForAccessor(*C)) 354 if (const auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) 355 Fields.insert(FD); 356 } else if (auto *E = dyn_cast<MemberExpr>(&S)) { 357 // FIXME: should we be using `E->getFoundDecl()`? 358 const ValueDecl *VD = E->getMemberDecl(); 359 insertIfGlobal(*VD, Vars); 360 insertIfFunction(*VD, Funcs); 361 if (const auto *FD = dyn_cast<FieldDecl>(VD)) 362 Fields.insert(FD); 363 } else if (auto *InitList = dyn_cast<InitListExpr>(&S)) { 364 if (RecordDecl *RD = InitList->getType()->getAsRecordDecl()) 365 for (const auto *FD : getFieldsForInitListExpr(RD)) 366 Fields.insert(FD); 367 } 368 } 369 370 Environment::Environment(DataflowAnalysisContext &DACtx) 371 : DACtx(&DACtx), 372 FlowConditionToken(DACtx.arena().makeFlowConditionToken()) {} 373 374 Environment::Environment(DataflowAnalysisContext &DACtx, 375 const DeclContext &DeclCtx) 376 : Environment(DACtx) { 377 CallStack.push_back(&DeclCtx); 378 } 379 380 void Environment::initialize() { 381 const DeclContext *DeclCtx = getDeclCtx(); 382 if (DeclCtx == nullptr) 383 return; 384 385 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(DeclCtx)) { 386 assert(FuncDecl->getBody() != nullptr); 387 388 initFieldsGlobalsAndFuncs(FuncDecl); 389 390 for (const auto *ParamDecl : FuncDecl->parameters()) { 391 assert(ParamDecl != nullptr); 392 setStorageLocation(*ParamDecl, createObject(*ParamDecl, nullptr)); 393 } 394 } 395 396 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclCtx)) { 397 auto *Parent = MethodDecl->getParent(); 398 assert(Parent != nullptr); 399 400 if (Parent->isLambda()) { 401 for (auto Capture : Parent->captures()) { 402 if (Capture.capturesVariable()) { 403 const auto *VarDecl = Capture.getCapturedVar(); 404 assert(VarDecl != nullptr); 405 setStorageLocation(*VarDecl, createObject(*VarDecl, nullptr)); 406 } else if (Capture.capturesThis()) { 407 const auto *SurroundingMethodDecl = 408 cast<CXXMethodDecl>(DeclCtx->getNonClosureAncestor()); 409 QualType ThisPointeeType = 410 SurroundingMethodDecl->getFunctionObjectParameterType(); 411 setThisPointeeStorageLocation( 412 cast<RecordValue>(createValue(ThisPointeeType))->getLoc()); 413 } 414 } 415 } else if (MethodDecl->isImplicitObjectMemberFunction()) { 416 QualType ThisPointeeType = MethodDecl->getFunctionObjectParameterType(); 417 setThisPointeeStorageLocation( 418 cast<RecordValue>(createValue(ThisPointeeType))->getLoc()); 419 } 420 } 421 } 422 423 // FIXME: Add support for resetting globals after function calls to enable 424 // the implementation of sound analyses. 425 void Environment::initFieldsGlobalsAndFuncs(const FunctionDecl *FuncDecl) { 426 assert(FuncDecl->getBody() != nullptr); 427 428 FieldSet Fields; 429 llvm::DenseSet<const VarDecl *> Vars; 430 llvm::DenseSet<const FunctionDecl *> Funcs; 431 432 // Look for global variable and field references in the 433 // constructor-initializers. 434 if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(FuncDecl)) { 435 for (const auto *Init : CtorDecl->inits()) { 436 if (Init->isMemberInitializer()) { 437 Fields.insert(Init->getMember()); 438 } else if (Init->isIndirectMemberInitializer()) { 439 for (const auto *I : Init->getIndirectMember()->chain()) 440 Fields.insert(cast<FieldDecl>(I)); 441 } 442 const Expr *E = Init->getInit(); 443 assert(E != nullptr); 444 getFieldsGlobalsAndFuncs(*E, Fields, Vars, Funcs); 445 } 446 // Add all fields mentioned in default member initializers. 447 for (const FieldDecl *F : CtorDecl->getParent()->fields()) 448 if (const auto *I = F->getInClassInitializer()) 449 getFieldsGlobalsAndFuncs(*I, Fields, Vars, Funcs); 450 } 451 getFieldsGlobalsAndFuncs(*FuncDecl->getBody(), Fields, Vars, Funcs); 452 453 // These have to be added before the lines that follow to ensure that 454 // `create*` work correctly for structs. 455 DACtx->addModeledFields(Fields); 456 457 for (const VarDecl *D : Vars) { 458 if (getStorageLocation(*D) != nullptr) 459 continue; 460 461 setStorageLocation(*D, createObject(*D)); 462 } 463 464 for (const FunctionDecl *FD : Funcs) { 465 if (getStorageLocation(*FD) != nullptr) 466 continue; 467 auto &Loc = createStorageLocation(FD->getType()); 468 setStorageLocation(*FD, Loc); 469 } 470 } 471 472 Environment Environment::fork() const { 473 Environment Copy(*this); 474 Copy.FlowConditionToken = DACtx->forkFlowCondition(FlowConditionToken); 475 return Copy; 476 } 477 478 bool Environment::canDescend(unsigned MaxDepth, 479 const DeclContext *Callee) const { 480 return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee); 481 } 482 483 Environment Environment::pushCall(const CallExpr *Call) const { 484 Environment Env(*this); 485 486 if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) { 487 if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) { 488 if (!isa<CXXThisExpr>(Arg)) 489 Env.ThisPointeeLoc = 490 cast<RecordStorageLocation>(getStorageLocation(*Arg)); 491 // Otherwise (when the argument is `this`), retain the current 492 // environment's `ThisPointeeLoc`. 493 } 494 } 495 496 Env.pushCallInternal(Call->getDirectCallee(), 497 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs())); 498 499 return Env; 500 } 501 502 Environment Environment::pushCall(const CXXConstructExpr *Call) const { 503 Environment Env(*this); 504 505 Env.ThisPointeeLoc = &Env.getResultObjectLocation(*Call); 506 507 Env.pushCallInternal(Call->getConstructor(), 508 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs())); 509 510 return Env; 511 } 512 513 void Environment::pushCallInternal(const FunctionDecl *FuncDecl, 514 ArrayRef<const Expr *> Args) { 515 // Canonicalize to the definition of the function. This ensures that we're 516 // putting arguments into the same `ParamVarDecl`s` that the callee will later 517 // be retrieving them from. 518 assert(FuncDecl->getDefinition() != nullptr); 519 FuncDecl = FuncDecl->getDefinition(); 520 521 CallStack.push_back(FuncDecl); 522 523 initFieldsGlobalsAndFuncs(FuncDecl); 524 525 const auto *ParamIt = FuncDecl->param_begin(); 526 527 // FIXME: Parameters don't always map to arguments 1:1; examples include 528 // overloaded operators implemented as member functions, and parameter packs. 529 for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) { 530 assert(ParamIt != FuncDecl->param_end()); 531 const VarDecl *Param = *ParamIt; 532 setStorageLocation(*Param, createObject(*Param, Args[ArgIndex])); 533 } 534 } 535 536 void Environment::popCall(const CallExpr *Call, const Environment &CalleeEnv) { 537 // We ignore some entries of `CalleeEnv`: 538 // - `DACtx` because is already the same in both 539 // - We don't want the callee's `DeclCtx`, `ReturnVal`, `ReturnLoc` or 540 // `ThisPointeeLoc` because they don't apply to us. 541 // - `DeclToLoc`, `ExprToLoc`, and `ExprToVal` capture information from the 542 // callee's local scope, so when popping that scope, we do not propagate 543 // the maps. 544 this->LocToVal = std::move(CalleeEnv.LocToVal); 545 this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken); 546 547 if (Call->isGLValue()) { 548 if (CalleeEnv.ReturnLoc != nullptr) 549 setStorageLocation(*Call, *CalleeEnv.ReturnLoc); 550 } else if (!Call->getType()->isVoidType()) { 551 if (CalleeEnv.ReturnVal != nullptr) 552 setValue(*Call, *CalleeEnv.ReturnVal); 553 } 554 } 555 556 void Environment::popCall(const CXXConstructExpr *Call, 557 const Environment &CalleeEnv) { 558 // See also comment in `popCall(const CallExpr *, const Environment &)` above. 559 this->LocToVal = std::move(CalleeEnv.LocToVal); 560 this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken); 561 562 if (Value *Val = CalleeEnv.getValue(*CalleeEnv.ThisPointeeLoc)) { 563 setValue(*Call, *Val); 564 } 565 } 566 567 bool Environment::equivalentTo(const Environment &Other, 568 Environment::ValueModel &Model) const { 569 assert(DACtx == Other.DACtx); 570 571 if (ReturnVal != Other.ReturnVal) 572 return false; 573 574 if (ReturnLoc != Other.ReturnLoc) 575 return false; 576 577 if (ThisPointeeLoc != Other.ThisPointeeLoc) 578 return false; 579 580 if (DeclToLoc != Other.DeclToLoc) 581 return false; 582 583 if (ExprToLoc != Other.ExprToLoc) 584 return false; 585 586 if (!compareKeyToValueMaps(ExprToVal, Other.ExprToVal, *this, Other, Model)) 587 return false; 588 589 if (!compareKeyToValueMaps(LocToVal, Other.LocToVal, *this, Other, Model)) 590 return false; 591 592 return true; 593 } 594 595 LatticeJoinEffect Environment::widen(const Environment &PrevEnv, 596 Environment::ValueModel &Model) { 597 assert(DACtx == PrevEnv.DACtx); 598 assert(ReturnVal == PrevEnv.ReturnVal); 599 assert(ReturnLoc == PrevEnv.ReturnLoc); 600 assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc); 601 assert(CallStack == PrevEnv.CallStack); 602 603 auto Effect = LatticeJoinEffect::Unchanged; 604 605 // By the API, `PrevEnv` is a previous version of the environment for the same 606 // block, so we have some guarantees about its shape. In particular, it will 607 // be the result of a join or widen operation on previous values for this 608 // block. For `DeclToLoc`, `ExprToVal`, and `ExprToLoc`, join guarantees that 609 // these maps are subsets of the maps in `PrevEnv`. So, as long as we maintain 610 // this property here, we don't need change their current values to widen. 611 assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size()); 612 assert(ExprToVal.size() <= PrevEnv.ExprToVal.size()); 613 assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size()); 614 615 ExprToVal = widenKeyToValueMap(ExprToVal, PrevEnv.ExprToVal, *this, PrevEnv, 616 Model, Effect); 617 618 LocToVal = widenKeyToValueMap(LocToVal, PrevEnv.LocToVal, *this, PrevEnv, 619 Model, Effect); 620 if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() || 621 ExprToLoc.size() != PrevEnv.ExprToLoc.size() || 622 ExprToVal.size() != PrevEnv.ExprToVal.size() || 623 LocToVal.size() != PrevEnv.LocToVal.size()) 624 Effect = LatticeJoinEffect::Changed; 625 626 return Effect; 627 } 628 629 Environment Environment::join(const Environment &EnvA, const Environment &EnvB, 630 Environment::ValueModel &Model) { 631 assert(EnvA.DACtx == EnvB.DACtx); 632 assert(EnvA.ThisPointeeLoc == EnvB.ThisPointeeLoc); 633 assert(EnvA.CallStack == EnvB.CallStack); 634 635 Environment JoinedEnv(*EnvA.DACtx); 636 637 JoinedEnv.CallStack = EnvA.CallStack; 638 JoinedEnv.ThisPointeeLoc = EnvA.ThisPointeeLoc; 639 640 if (EnvA.ReturnVal == nullptr || EnvB.ReturnVal == nullptr) { 641 // `ReturnVal` might not always get set -- for example if we have a return 642 // statement of the form `return some_other_func()` and we decide not to 643 // analyze `some_other_func()`. 644 // In this case, we can't say anything about the joined return value -- we 645 // don't simply want to propagate the return value that we do have, because 646 // it might not be the correct one. 647 // This occurs for example in the test `ContextSensitiveMutualRecursion`. 648 JoinedEnv.ReturnVal = nullptr; 649 } else if (areEquivalentValues(*EnvA.ReturnVal, *EnvB.ReturnVal)) { 650 JoinedEnv.ReturnVal = EnvA.ReturnVal; 651 } else { 652 assert(!EnvA.CallStack.empty()); 653 // FIXME: Make `CallStack` a vector of `FunctionDecl` so we don't need this 654 // cast. 655 auto *Func = dyn_cast<FunctionDecl>(EnvA.CallStack.back()); 656 assert(Func != nullptr); 657 if (Value *MergedVal = 658 mergeDistinctValues(Func->getReturnType(), *EnvA.ReturnVal, EnvA, 659 *EnvB.ReturnVal, EnvB, JoinedEnv, Model)) 660 JoinedEnv.ReturnVal = MergedVal; 661 } 662 663 if (EnvA.ReturnLoc == EnvB.ReturnLoc) 664 JoinedEnv.ReturnLoc = EnvA.ReturnLoc; 665 else 666 JoinedEnv.ReturnLoc = nullptr; 667 668 JoinedEnv.DeclToLoc = intersectDeclToLoc(EnvA.DeclToLoc, EnvB.DeclToLoc); 669 670 // FIXME: update join to detect backedges and simplify the flow condition 671 // accordingly. 672 JoinedEnv.FlowConditionToken = EnvA.DACtx->joinFlowConditions( 673 EnvA.FlowConditionToken, EnvB.FlowConditionToken); 674 675 JoinedEnv.LocToVal = 676 joinLocToVal(EnvA.LocToVal, EnvB.LocToVal, EnvA, EnvB, JoinedEnv, Model); 677 678 // We intentionally leave `JoinedEnv.ExprToLoc` and `JoinedEnv.ExprToVal` 679 // empty, as we never need to access entries in these maps outside of the 680 // basic block that sets them. 681 682 return JoinedEnv; 683 } 684 685 StorageLocation &Environment::createStorageLocation(QualType Type) { 686 return DACtx->createStorageLocation(Type); 687 } 688 689 StorageLocation &Environment::createStorageLocation(const ValueDecl &D) { 690 // Evaluated declarations are always assigned the same storage locations to 691 // ensure that the environment stabilizes across loop iterations. Storage 692 // locations for evaluated declarations are stored in the analysis context. 693 return DACtx->getStableStorageLocation(D); 694 } 695 696 StorageLocation &Environment::createStorageLocation(const Expr &E) { 697 // Evaluated expressions are always assigned the same storage locations to 698 // ensure that the environment stabilizes across loop iterations. Storage 699 // locations for evaluated expressions are stored in the analysis context. 700 return DACtx->getStableStorageLocation(E); 701 } 702 703 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) { 704 assert(!DeclToLoc.contains(&D)); 705 DeclToLoc[&D] = &Loc; 706 } 707 708 StorageLocation *Environment::getStorageLocation(const ValueDecl &D) const { 709 auto It = DeclToLoc.find(&D); 710 if (It == DeclToLoc.end()) 711 return nullptr; 712 713 StorageLocation *Loc = It->second; 714 715 return Loc; 716 } 717 718 void Environment::removeDecl(const ValueDecl &D) { DeclToLoc.erase(&D); } 719 720 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) { 721 // `DeclRefExpr`s to builtin function types aren't glvalues, for some reason, 722 // but we still want to be able to associate a `StorageLocation` with them, 723 // so allow these as an exception. 724 assert(E.isGLValue() || 725 E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)); 726 setStorageLocationInternal(E, Loc); 727 } 728 729 StorageLocation *Environment::getStorageLocation(const Expr &E) const { 730 // See comment in `setStorageLocation()`. 731 assert(E.isGLValue() || 732 E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)); 733 return getStorageLocationInternal(E); 734 } 735 736 RecordStorageLocation & 737 Environment::getResultObjectLocation(const Expr &RecordPRValue) { 738 assert(RecordPRValue.getType()->isRecordType()); 739 assert(RecordPRValue.isPRValue()); 740 741 if (StorageLocation *ExistingLoc = getStorageLocationInternal(RecordPRValue)) 742 return *cast<RecordStorageLocation>(ExistingLoc); 743 auto &Loc = cast<RecordStorageLocation>( 744 DACtx->getStableStorageLocation(RecordPRValue)); 745 setStorageLocationInternal(RecordPRValue, Loc); 746 return Loc; 747 } 748 749 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) { 750 return DACtx->getOrCreateNullPointerValue(PointeeType); 751 } 752 753 void Environment::setValue(const StorageLocation &Loc, Value &Val) { 754 assert(!isa<RecordValue>(&Val) || &cast<RecordValue>(&Val)->getLoc() == &Loc); 755 756 LocToVal[&Loc] = &Val; 757 } 758 759 void Environment::setValue(const Expr &E, Value &Val) { 760 assert(E.isPRValue()); 761 ExprToVal[&E] = &Val; 762 } 763 764 Value *Environment::getValue(const StorageLocation &Loc) const { 765 return LocToVal.lookup(&Loc); 766 } 767 768 Value *Environment::getValue(const ValueDecl &D) const { 769 auto *Loc = getStorageLocation(D); 770 if (Loc == nullptr) 771 return nullptr; 772 return getValue(*Loc); 773 } 774 775 Value *Environment::getValue(const Expr &E) const { 776 if (E.isPRValue()) { 777 auto It = ExprToVal.find(&ignoreCFGOmittedNodes(E)); 778 return It == ExprToVal.end() ? nullptr : It->second; 779 } 780 781 auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E)); 782 if (It == ExprToLoc.end()) 783 return nullptr; 784 return getValue(*It->second); 785 } 786 787 Value *Environment::createValue(QualType Type) { 788 llvm::DenseSet<QualType> Visited; 789 int CreatedValuesCount = 0; 790 Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0, 791 CreatedValuesCount); 792 if (CreatedValuesCount > MaxCompositeValueSize) { 793 llvm::errs() << "Attempting to initialize a huge value of type: " << Type 794 << '\n'; 795 } 796 return Val; 797 } 798 799 void Environment::setStorageLocationInternal(const Expr &E, 800 StorageLocation &Loc) { 801 const Expr &CanonE = ignoreCFGOmittedNodes(E); 802 assert(!ExprToLoc.contains(&CanonE)); 803 ExprToLoc[&CanonE] = &Loc; 804 } 805 806 StorageLocation *Environment::getStorageLocationInternal(const Expr &E) const { 807 auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E)); 808 return It == ExprToLoc.end() ? nullptr : &*It->second; 809 } 810 811 Value *Environment::createValueUnlessSelfReferential( 812 QualType Type, llvm::DenseSet<QualType> &Visited, int Depth, 813 int &CreatedValuesCount) { 814 assert(!Type.isNull()); 815 assert(!Type->isReferenceType()); 816 817 // Allow unlimited fields at depth 1; only cap at deeper nesting levels. 818 if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) || 819 Depth > MaxCompositeValueDepth) 820 return nullptr; 821 822 if (Type->isBooleanType()) { 823 CreatedValuesCount++; 824 return &makeAtomicBoolValue(); 825 } 826 827 if (Type->isIntegerType()) { 828 // FIXME: consider instead `return nullptr`, given that we do nothing useful 829 // with integers, and so distinguishing them serves no purpose, but could 830 // prevent convergence. 831 CreatedValuesCount++; 832 return &arena().create<IntegerValue>(); 833 } 834 835 if (Type->isPointerType()) { 836 CreatedValuesCount++; 837 QualType PointeeType = Type->getPointeeType(); 838 StorageLocation &PointeeLoc = 839 createLocAndMaybeValue(PointeeType, Visited, Depth, CreatedValuesCount); 840 841 return &arena().create<PointerValue>(PointeeLoc); 842 } 843 844 if (Type->isRecordType()) { 845 CreatedValuesCount++; 846 llvm::DenseMap<const ValueDecl *, StorageLocation *> FieldLocs; 847 for (const FieldDecl *Field : DACtx->getModeledFields(Type)) { 848 assert(Field != nullptr); 849 850 QualType FieldType = Field->getType(); 851 852 FieldLocs.insert( 853 {Field, &createLocAndMaybeValue(FieldType, Visited, Depth + 1, 854 CreatedValuesCount)}); 855 } 856 857 RecordStorageLocation::SyntheticFieldMap SyntheticFieldLocs; 858 for (const auto &Entry : DACtx->getSyntheticFields(Type)) { 859 SyntheticFieldLocs.insert( 860 {Entry.getKey(), 861 &createLocAndMaybeValue(Entry.getValue(), Visited, Depth + 1, 862 CreatedValuesCount)}); 863 } 864 865 RecordStorageLocation &Loc = DACtx->createRecordStorageLocation( 866 Type, std::move(FieldLocs), std::move(SyntheticFieldLocs)); 867 RecordValue &RecordVal = create<RecordValue>(Loc); 868 869 // As we already have a storage location for the `RecordValue`, we can and 870 // should associate them in the environment. 871 setValue(Loc, RecordVal); 872 873 return &RecordVal; 874 } 875 876 return nullptr; 877 } 878 879 StorageLocation & 880 Environment::createLocAndMaybeValue(QualType Ty, 881 llvm::DenseSet<QualType> &Visited, 882 int Depth, int &CreatedValuesCount) { 883 if (!Visited.insert(Ty.getCanonicalType()).second) 884 return createStorageLocation(Ty.getNonReferenceType()); 885 Value *Val = createValueUnlessSelfReferential( 886 Ty.getNonReferenceType(), Visited, Depth, CreatedValuesCount); 887 Visited.erase(Ty.getCanonicalType()); 888 889 Ty = Ty.getNonReferenceType(); 890 891 if (Val == nullptr) 892 return createStorageLocation(Ty); 893 894 if (Ty->isRecordType()) 895 return cast<RecordValue>(Val)->getLoc(); 896 897 StorageLocation &Loc = createStorageLocation(Ty); 898 setValue(Loc, *Val); 899 return Loc; 900 } 901 902 StorageLocation &Environment::createObjectInternal(const ValueDecl *D, 903 QualType Ty, 904 const Expr *InitExpr) { 905 if (Ty->isReferenceType()) { 906 // Although variables of reference type always need to be initialized, it 907 // can happen that we can't see the initializer, so `InitExpr` may still 908 // be null. 909 if (InitExpr) { 910 if (auto *InitExprLoc = getStorageLocation(*InitExpr)) 911 return *InitExprLoc; 912 } 913 914 // Even though we have an initializer, we might not get an 915 // InitExprLoc, for example if the InitExpr is a CallExpr for which we 916 // don't have a function body. In this case, we just invent a storage 917 // location and value -- it's the best we can do. 918 return createObjectInternal(D, Ty.getNonReferenceType(), nullptr); 919 } 920 921 Value *Val = nullptr; 922 if (InitExpr) 923 // In the (few) cases where an expression is intentionally 924 // "uninterpreted", `InitExpr` is not associated with a value. There are 925 // two ways to handle this situation: propagate the status, so that 926 // uninterpreted initializers result in uninterpreted variables, or 927 // provide a default value. We choose the latter so that later refinements 928 // of the variable can be used for reasoning about the surrounding code. 929 // For this reason, we let this case be handled by the `createValue()` 930 // call below. 931 // 932 // FIXME. If and when we interpret all language cases, change this to 933 // assert that `InitExpr` is interpreted, rather than supplying a 934 // default value (assuming we don't update the environment API to return 935 // references). 936 Val = getValue(*InitExpr); 937 if (!Val) 938 Val = createValue(Ty); 939 940 if (Ty->isRecordType()) 941 return cast<RecordValue>(Val)->getLoc(); 942 943 StorageLocation &Loc = 944 D ? createStorageLocation(*D) : createStorageLocation(Ty); 945 946 if (Val) 947 setValue(Loc, *Val); 948 949 return Loc; 950 } 951 952 void Environment::assume(const Formula &F) { 953 DACtx->addFlowConditionConstraint(FlowConditionToken, F); 954 } 955 956 bool Environment::proves(const Formula &F) const { 957 return DACtx->flowConditionImplies(FlowConditionToken, F); 958 } 959 960 bool Environment::allows(const Formula &F) const { 961 return DACtx->flowConditionAllows(FlowConditionToken, F); 962 } 963 964 void Environment::dump(raw_ostream &OS) const { 965 // FIXME: add printing for remaining fields and allow caller to decide what 966 // fields are printed. 967 OS << "DeclToLoc:\n"; 968 for (auto [D, L] : DeclToLoc) 969 OS << " [" << D->getNameAsString() << ", " << L << "]\n"; 970 971 OS << "ExprToLoc:\n"; 972 for (auto [E, L] : ExprToLoc) 973 OS << " [" << E << ", " << L << "]\n"; 974 975 OS << "ExprToVal:\n"; 976 for (auto [E, V] : ExprToVal) 977 OS << " [" << E << ", " << V << ": " << *V << "]\n"; 978 979 OS << "LocToVal:\n"; 980 for (auto [L, V] : LocToVal) { 981 OS << " [" << L << ", " << V << ": " << *V << "]\n"; 982 } 983 984 OS << "\n"; 985 DACtx->dumpFlowCondition(FlowConditionToken, OS); 986 } 987 988 void Environment::dump() const { 989 dump(llvm::dbgs()); 990 } 991 992 RecordStorageLocation *getImplicitObjectLocation(const CXXMemberCallExpr &MCE, 993 const Environment &Env) { 994 Expr *ImplicitObject = MCE.getImplicitObjectArgument(); 995 if (ImplicitObject == nullptr) 996 return nullptr; 997 if (ImplicitObject->getType()->isPointerType()) { 998 if (auto *Val = cast_or_null<PointerValue>(Env.getValue(*ImplicitObject))) 999 return &cast<RecordStorageLocation>(Val->getPointeeLoc()); 1000 return nullptr; 1001 } 1002 return cast_or_null<RecordStorageLocation>( 1003 Env.getStorageLocation(*ImplicitObject)); 1004 } 1005 1006 RecordStorageLocation *getBaseObjectLocation(const MemberExpr &ME, 1007 const Environment &Env) { 1008 Expr *Base = ME.getBase(); 1009 if (Base == nullptr) 1010 return nullptr; 1011 if (ME.isArrow()) { 1012 if (auto *Val = cast_or_null<PointerValue>(Env.getValue(*Base))) 1013 return &cast<RecordStorageLocation>(Val->getPointeeLoc()); 1014 return nullptr; 1015 } 1016 return cast_or_null<RecordStorageLocation>(Env.getStorageLocation(*Base)); 1017 } 1018 1019 std::vector<FieldDecl *> getFieldsForInitListExpr(const RecordDecl *RD) { 1020 // Unnamed bitfields are only used for padding and do not appear in 1021 // `InitListExpr`'s inits. However, those fields do appear in `RecordDecl`'s 1022 // field list, and we thus need to remove them before mapping inits to 1023 // fields to avoid mapping inits to the wrongs fields. 1024 std::vector<FieldDecl *> Fields; 1025 llvm::copy_if( 1026 RD->fields(), std::back_inserter(Fields), 1027 [](const FieldDecl *Field) { return !Field->isUnnamedBitfield(); }); 1028 return Fields; 1029 } 1030 1031 RecordValue &refreshRecordValue(RecordStorageLocation &Loc, Environment &Env) { 1032 auto &NewVal = Env.create<RecordValue>(Loc); 1033 Env.setValue(Loc, NewVal); 1034 return NewVal; 1035 } 1036 1037 RecordValue &refreshRecordValue(const Expr &Expr, Environment &Env) { 1038 assert(Expr.getType()->isRecordType()); 1039 1040 if (Expr.isPRValue()) { 1041 if (auto *ExistingVal = cast_or_null<RecordValue>(Env.getValue(Expr))) { 1042 auto &NewVal = Env.create<RecordValue>(ExistingVal->getLoc()); 1043 Env.setValue(Expr, NewVal); 1044 return NewVal; 1045 } 1046 1047 auto &NewVal = *cast<RecordValue>(Env.createValue(Expr.getType())); 1048 Env.setValue(Expr, NewVal); 1049 return NewVal; 1050 } 1051 1052 if (auto *Loc = 1053 cast_or_null<RecordStorageLocation>(Env.getStorageLocation(Expr))) { 1054 auto &NewVal = Env.create<RecordValue>(*Loc); 1055 Env.setValue(*Loc, NewVal); 1056 return NewVal; 1057 } 1058 1059 auto &NewVal = *cast<RecordValue>(Env.createValue(Expr.getType())); 1060 Env.setStorageLocation(Expr, NewVal.getLoc()); 1061 return NewVal; 1062 } 1063 1064 } // namespace dataflow 1065 } // namespace clang 1066