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/RecursiveASTVisitor.h" 19 #include "clang/AST/Type.h" 20 #include "clang/Analysis/FlowSensitive/ASTOps.h" 21 #include "clang/Analysis/FlowSensitive/DataflowLattice.h" 22 #include "clang/Analysis/FlowSensitive/Value.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/DenseSet.h" 25 #include "llvm/ADT/MapVector.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include <cassert> 29 #include <utility> 30 31 #define DEBUG_TYPE "dataflow" 32 33 namespace clang { 34 namespace dataflow { 35 36 // FIXME: convert these to parameters of the analysis or environment. Current 37 // settings have been experimentaly validated, but only for a particular 38 // analysis. 39 static constexpr int MaxCompositeValueDepth = 3; 40 static constexpr int MaxCompositeValueSize = 1000; 41 42 /// Returns a map consisting of key-value entries that are present in both maps. 43 static llvm::DenseMap<const ValueDecl *, StorageLocation *> intersectDeclToLoc( 44 const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc1, 45 const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc2) { 46 llvm::DenseMap<const ValueDecl *, StorageLocation *> Result; 47 for (auto &Entry : DeclToLoc1) { 48 auto It = DeclToLoc2.find(Entry.first); 49 if (It != DeclToLoc2.end() && Entry.second == It->second) 50 Result.insert({Entry.first, Entry.second}); 51 } 52 return Result; 53 } 54 55 // Performs a join on either `ExprToLoc` or `ExprToVal`. 56 // The maps must be consistent in the sense that any entries for the same 57 // expression must map to the same location / value. This is the case if we are 58 // performing a join for control flow within a full-expression (which is the 59 // only case when this function should be used). 60 template <typename MapT> MapT joinExprMaps(const MapT &Map1, const MapT &Map2) { 61 MapT Result = Map1; 62 63 for (const auto &Entry : Map2) { 64 [[maybe_unused]] auto [It, Inserted] = Result.insert(Entry); 65 // If there was an existing entry, its value should be the same as for the 66 // entry we were trying to insert. 67 assert(It->second == Entry.second); 68 } 69 70 return Result; 71 } 72 73 // Whether to consider equivalent two values with an unknown relation. 74 // 75 // FIXME: this function is a hack enabling unsoundness to support 76 // convergence. Once we have widening support for the reference/pointer and 77 // struct built-in models, this should be unconditionally `false` (and inlined 78 // as such at its call sites). 79 static bool equateUnknownValues(Value::Kind K) { 80 switch (K) { 81 case Value::Kind::Integer: 82 case Value::Kind::Pointer: 83 case Value::Kind::Record: 84 return true; 85 default: 86 return false; 87 } 88 } 89 90 static bool compareDistinctValues(QualType Type, Value &Val1, 91 const Environment &Env1, Value &Val2, 92 const Environment &Env2, 93 Environment::ValueModel &Model) { 94 // Note: Potentially costly, but, for booleans, we could check whether both 95 // can be proven equivalent in their respective environments. 96 97 // FIXME: move the reference/pointers logic from `areEquivalentValues` to here 98 // and implement separate, join/widen specific handling for 99 // reference/pointers. 100 switch (Model.compare(Type, Val1, Env1, Val2, Env2)) { 101 case ComparisonResult::Same: 102 return true; 103 case ComparisonResult::Different: 104 return false; 105 case ComparisonResult::Unknown: 106 return equateUnknownValues(Val1.getKind()); 107 } 108 llvm_unreachable("All cases covered in switch"); 109 } 110 111 /// Attempts to join distinct values `Val1` and `Val2` in `Env1` and `Env2`, 112 /// respectively, of the same type `Type`. Joining generally produces a single 113 /// value that (soundly) approximates the two inputs, although the actual 114 /// meaning depends on `Model`. 115 static Value *joinDistinctValues(QualType Type, Value &Val1, 116 const Environment &Env1, Value &Val2, 117 const Environment &Env2, 118 Environment &JoinedEnv, 119 Environment::ValueModel &Model) { 120 // Join distinct boolean values preserving information about the constraints 121 // in the respective path conditions. 122 if (isa<BoolValue>(&Val1) && isa<BoolValue>(&Val2)) { 123 // FIXME: Checking both values should be unnecessary, since they should have 124 // a consistent shape. However, right now we can end up with BoolValue's in 125 // integer-typed variables due to our incorrect handling of 126 // boolean-to-integer casts (we just propagate the BoolValue to the result 127 // of the cast). So, a join can encounter an integer in one branch but a 128 // bool in the other. 129 // For example: 130 // ``` 131 // std::optional<bool> o; 132 // int x; 133 // if (o.has_value()) 134 // x = o.value(); 135 // ``` 136 auto &Expr1 = cast<BoolValue>(Val1).formula(); 137 auto &Expr2 = cast<BoolValue>(Val2).formula(); 138 auto &A = JoinedEnv.arena(); 139 auto &JoinedVal = A.makeAtomRef(A.makeAtom()); 140 JoinedEnv.assume( 141 A.makeOr(A.makeAnd(A.makeAtomRef(Env1.getFlowConditionToken()), 142 A.makeEquals(JoinedVal, Expr1)), 143 A.makeAnd(A.makeAtomRef(Env2.getFlowConditionToken()), 144 A.makeEquals(JoinedVal, Expr2)))); 145 return &A.makeBoolValue(JoinedVal); 146 } 147 148 Value *JoinedVal = nullptr; 149 if (auto *RecordVal1 = dyn_cast<RecordValue>(&Val1)) { 150 auto *RecordVal2 = cast<RecordValue>(&Val2); 151 152 if (&RecordVal1->getLoc() == &RecordVal2->getLoc()) 153 // `RecordVal1` and `RecordVal2` may have different properties associated 154 // with them. Create a new `RecordValue` with the same location but 155 // without any properties so that we soundly approximate both values. If a 156 // particular analysis needs to join properties, it should do so in 157 // `DataflowAnalysis::join()`. 158 JoinedVal = &JoinedEnv.create<RecordValue>(RecordVal1->getLoc()); 159 else 160 // If the locations for the two records are different, need to create a 161 // completely new value. 162 JoinedVal = JoinedEnv.createValue(Type); 163 } else { 164 JoinedVal = JoinedEnv.createValue(Type); 165 } 166 167 if (JoinedVal) 168 Model.join(Type, Val1, Env1, Val2, Env2, *JoinedVal, JoinedEnv); 169 170 return JoinedVal; 171 } 172 173 static WidenResult widenDistinctValues(QualType Type, Value &Prev, 174 const Environment &PrevEnv, 175 Value &Current, Environment &CurrentEnv, 176 Environment::ValueModel &Model) { 177 // Boolean-model widening. 178 if (auto *PrevBool = dyn_cast<BoolValue>(&Prev)) { 179 if (isa<TopBoolValue>(Prev)) 180 // Safe to return `Prev` here, because Top is never dependent on the 181 // environment. 182 return {&Prev, LatticeEffect::Unchanged}; 183 184 // We may need to widen to Top, but before we do so, check whether both 185 // values are implied to be either true or false in the current environment. 186 // In that case, we can simply return a literal instead. 187 auto &CurBool = cast<BoolValue>(Current); 188 bool TruePrev = PrevEnv.proves(PrevBool->formula()); 189 bool TrueCur = CurrentEnv.proves(CurBool.formula()); 190 if (TruePrev && TrueCur) 191 return {&CurrentEnv.getBoolLiteralValue(true), LatticeEffect::Unchanged}; 192 if (!TruePrev && !TrueCur && 193 PrevEnv.proves(PrevEnv.arena().makeNot(PrevBool->formula())) && 194 CurrentEnv.proves(CurrentEnv.arena().makeNot(CurBool.formula()))) 195 return {&CurrentEnv.getBoolLiteralValue(false), LatticeEffect::Unchanged}; 196 197 return {&CurrentEnv.makeTopBoolValue(), LatticeEffect::Changed}; 198 } 199 200 // FIXME: Add other built-in model widening. 201 202 // Custom-model widening. 203 if (auto Result = Model.widen(Type, Prev, PrevEnv, Current, CurrentEnv)) 204 return *Result; 205 206 return {&Current, equateUnknownValues(Prev.getKind()) 207 ? LatticeEffect::Unchanged 208 : LatticeEffect::Changed}; 209 } 210 211 // Returns whether the values in `Map1` and `Map2` compare equal for those 212 // keys that `Map1` and `Map2` have in common. 213 template <typename Key> 214 bool compareKeyToValueMaps(const llvm::MapVector<Key, Value *> &Map1, 215 const llvm::MapVector<Key, Value *> &Map2, 216 const Environment &Env1, const Environment &Env2, 217 Environment::ValueModel &Model) { 218 for (auto &Entry : Map1) { 219 Key K = Entry.first; 220 assert(K != nullptr); 221 222 Value *Val = Entry.second; 223 assert(Val != nullptr); 224 225 auto It = Map2.find(K); 226 if (It == Map2.end()) 227 continue; 228 assert(It->second != nullptr); 229 230 if (!areEquivalentValues(*Val, *It->second) && 231 !compareDistinctValues(K->getType(), *Val, Env1, *It->second, Env2, 232 Model)) 233 return false; 234 } 235 236 return true; 237 } 238 239 // Perform a join on two `LocToVal` maps. 240 static llvm::MapVector<const StorageLocation *, Value *> 241 joinLocToVal(const llvm::MapVector<const StorageLocation *, Value *> &LocToVal, 242 const llvm::MapVector<const StorageLocation *, Value *> &LocToVal2, 243 const Environment &Env1, const Environment &Env2, 244 Environment &JoinedEnv, Environment::ValueModel &Model) { 245 llvm::MapVector<const StorageLocation *, Value *> Result; 246 for (auto &Entry : LocToVal) { 247 const StorageLocation *Loc = Entry.first; 248 assert(Loc != nullptr); 249 250 Value *Val = Entry.second; 251 assert(Val != nullptr); 252 253 auto It = LocToVal2.find(Loc); 254 if (It == LocToVal2.end()) 255 continue; 256 assert(It->second != nullptr); 257 258 if (areEquivalentValues(*Val, *It->second)) { 259 Result.insert({Loc, Val}); 260 continue; 261 } 262 263 if (Value *JoinedVal = joinDistinctValues( 264 Loc->getType(), *Val, Env1, *It->second, Env2, JoinedEnv, Model)) { 265 Result.insert({Loc, JoinedVal}); 266 } 267 } 268 269 return Result; 270 } 271 272 // Perform widening on either `LocToVal` or `ExprToVal`. `Key` must be either 273 // `const StorageLocation *` or `const Expr *`. 274 template <typename Key> 275 llvm::MapVector<Key, Value *> 276 widenKeyToValueMap(const llvm::MapVector<Key, Value *> &CurMap, 277 const llvm::MapVector<Key, Value *> &PrevMap, 278 Environment &CurEnv, const Environment &PrevEnv, 279 Environment::ValueModel &Model, LatticeEffect &Effect) { 280 llvm::MapVector<Key, Value *> WidenedMap; 281 for (auto &Entry : CurMap) { 282 Key K = Entry.first; 283 assert(K != nullptr); 284 285 Value *Val = Entry.second; 286 assert(Val != nullptr); 287 288 auto PrevIt = PrevMap.find(K); 289 if (PrevIt == PrevMap.end()) 290 continue; 291 assert(PrevIt->second != nullptr); 292 293 if (areEquivalentValues(*Val, *PrevIt->second)) { 294 WidenedMap.insert({K, Val}); 295 continue; 296 } 297 298 auto [WidenedVal, ValEffect] = widenDistinctValues( 299 K->getType(), *PrevIt->second, PrevEnv, *Val, CurEnv, Model); 300 WidenedMap.insert({K, WidenedVal}); 301 if (ValEffect == LatticeEffect::Changed) 302 Effect = LatticeEffect::Changed; 303 } 304 305 return WidenedMap; 306 } 307 308 namespace { 309 310 // Visitor that builds a map from record prvalues to result objects. 311 // This traverses the body of the function to be analyzed; for each result 312 // object that it encounters, it propagates the storage location of the result 313 // object to all record prvalues that can initialize it. 314 class ResultObjectVisitor : public RecursiveASTVisitor<ResultObjectVisitor> { 315 public: 316 // `ResultObjectMap` will be filled with a map from record prvalues to result 317 // object. If the function being analyzed returns a record by value, 318 // `LocForRecordReturnVal` is the location to which this record should be 319 // written; otherwise, it is null. 320 explicit ResultObjectVisitor( 321 llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap, 322 RecordStorageLocation *LocForRecordReturnVal, 323 DataflowAnalysisContext &DACtx) 324 : ResultObjectMap(ResultObjectMap), 325 LocForRecordReturnVal(LocForRecordReturnVal), DACtx(DACtx) {} 326 327 bool shouldVisitImplicitCode() { return true; } 328 329 bool shouldVisitLambdaBody() const { return false; } 330 331 // Traverse all member and base initializers of `Ctor`. This function is not 332 // called by `RecursiveASTVisitor`; it should be called manually if we are 333 // analyzing a constructor. `ThisPointeeLoc` is the storage location that 334 // `this` points to. 335 void TraverseConstructorInits(const CXXConstructorDecl *Ctor, 336 RecordStorageLocation *ThisPointeeLoc) { 337 assert(ThisPointeeLoc != nullptr); 338 for (const CXXCtorInitializer *Init : Ctor->inits()) { 339 Expr *InitExpr = Init->getInit(); 340 if (FieldDecl *Field = Init->getMember(); 341 Field != nullptr && Field->getType()->isRecordType()) { 342 PropagateResultObject(InitExpr, cast<RecordStorageLocation>( 343 ThisPointeeLoc->getChild(*Field))); 344 } else if (Init->getBaseClass()) { 345 PropagateResultObject(InitExpr, ThisPointeeLoc); 346 } 347 348 // Ensure that any result objects within `InitExpr` (e.g. temporaries) 349 // are also propagated to the prvalues that initialize them. 350 TraverseStmt(InitExpr); 351 352 // If this is a `CXXDefaultInitExpr`, also propagate any result objects 353 // within the default expression. 354 if (auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(InitExpr)) 355 TraverseStmt(DefaultInit->getExpr()); 356 } 357 } 358 359 bool TraverseBindingDecl(BindingDecl *BD) { 360 // `RecursiveASTVisitor` doesn't traverse holding variables for 361 // `BindingDecl`s by itself, so we need to tell it to. 362 if (VarDecl *HoldingVar = BD->getHoldingVar()) 363 TraverseDecl(HoldingVar); 364 return RecursiveASTVisitor<ResultObjectVisitor>::TraverseBindingDecl(BD); 365 } 366 367 bool VisitVarDecl(VarDecl *VD) { 368 if (VD->getType()->isRecordType() && VD->hasInit()) 369 PropagateResultObject( 370 VD->getInit(), 371 &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*VD))); 372 return true; 373 } 374 375 bool VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE) { 376 if (MTE->getType()->isRecordType()) 377 PropagateResultObject( 378 MTE->getSubExpr(), 379 &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*MTE))); 380 return true; 381 } 382 383 bool VisitReturnStmt(ReturnStmt *Return) { 384 Expr *RetValue = Return->getRetValue(); 385 if (RetValue != nullptr && RetValue->getType()->isRecordType() && 386 RetValue->isPRValue()) 387 PropagateResultObject(RetValue, LocForRecordReturnVal); 388 return true; 389 } 390 391 bool VisitExpr(Expr *E) { 392 // Clang's AST can have record-type prvalues without a result object -- for 393 // example as full-expressions contained in a compound statement or as 394 // arguments of call expressions. We notice this if we get here and a 395 // storage location has not yet been associated with `E`. In this case, 396 // treat this as if it was a `MaterializeTemporaryExpr`. 397 if (E->isPRValue() && E->getType()->isRecordType() && 398 !ResultObjectMap.contains(E)) 399 PropagateResultObject( 400 E, &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*E))); 401 return true; 402 } 403 404 // Assigns `Loc` as the result object location of `E`, then propagates the 405 // location to all lower-level prvalues that initialize the same object as 406 // `E` (or one of its base classes or member variables). 407 void PropagateResultObject(Expr *E, RecordStorageLocation *Loc) { 408 if (!E->isPRValue() || !E->getType()->isRecordType()) { 409 assert(false); 410 // Ensure we don't propagate the result object if we hit this in a 411 // release build. 412 return; 413 } 414 415 ResultObjectMap[E] = Loc; 416 417 switch (E->getStmtClass()) { 418 // The following AST node kinds are "original initializers": They are the 419 // lowest-level AST node that initializes a given object, and nothing 420 // below them can initialize the same object (or part of it). 421 case Stmt::CXXConstructExprClass: 422 case Stmt::CallExprClass: 423 case Stmt::LambdaExprClass: 424 case Stmt::CXXDefaultArgExprClass: 425 case Stmt::CXXDefaultInitExprClass: 426 case Stmt::CXXStdInitializerListExprClass: 427 // We treat `BuiltinBitCastExpr` as an "original initializer" too as it may 428 // not even be casting from a record type -- and even if it is, the two 429 // objects are in general of unrelated type. 430 case Stmt::BuiltinBitCastExprClass: 431 return; 432 case Stmt::BinaryOperatorClass: { 433 auto *Op = cast<BinaryOperator>(E); 434 if (Op->getOpcode() == BO_Cmp) { 435 // Builtin `<=>` returns a `std::strong_ordering` object. We 436 // consider this to be an "original" initializer too (see above). 437 return; 438 } 439 if (Op->isCommaOp()) { 440 PropagateResultObject(Op->getRHS(), Loc); 441 return; 442 } 443 // We don't expect any other binary operators to produce a record 444 // prvalue, so if we get here, we've hit some case we don't know 445 // about. 446 assert(false); 447 return; 448 } 449 case Stmt::BinaryConditionalOperatorClass: 450 case Stmt::ConditionalOperatorClass: { 451 auto *Cond = cast<AbstractConditionalOperator>(E); 452 PropagateResultObject(Cond->getTrueExpr(), Loc); 453 PropagateResultObject(Cond->getFalseExpr(), Loc); 454 return; 455 } 456 case Stmt::StmtExprClass: { 457 auto *SE = cast<StmtExpr>(E); 458 PropagateResultObject(cast<Expr>(SE->getSubStmt()->body_back()), Loc); 459 return; 460 } 461 case Stmt::InitListExprClass: { 462 auto *InitList = cast<InitListExpr>(E); 463 if (!InitList->isSemanticForm()) 464 return; 465 if (InitList->isTransparent()) { 466 PropagateResultObject(InitList->getInit(0), Loc); 467 return; 468 } 469 470 RecordInitListHelper InitListHelper(InitList); 471 472 for (auto [Base, Init] : InitListHelper.base_inits()) { 473 assert(Base->getType().getCanonicalType() == 474 Init->getType().getCanonicalType()); 475 476 // Storage location for the base class is the same as that of the 477 // derived class because we "flatten" the object hierarchy and put all 478 // fields in `RecordStorageLocation` of the derived class. 479 PropagateResultObject(Init, Loc); 480 } 481 482 for (auto [Field, Init] : InitListHelper.field_inits()) { 483 // Fields of non-record type are handled in 484 // `TransferVisitor::VisitInitListExpr()`. 485 if (!Field->getType()->isRecordType()) 486 continue; 487 PropagateResultObject( 488 Init, cast<RecordStorageLocation>(Loc->getChild(*Field))); 489 } 490 return; 491 } 492 default: { 493 // All other expression nodes that propagate a record prvalue should 494 // have exactly one child. 495 SmallVector<Stmt *, 1> Children(E->child_begin(), E->child_end()); 496 LLVM_DEBUG({ 497 if (Children.size() != 1) 498 E->dump(); 499 }); 500 assert(Children.size() == 1); 501 for (Stmt *S : Children) 502 PropagateResultObject(cast<Expr>(S), Loc); 503 return; 504 } 505 } 506 } 507 508 private: 509 llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap; 510 RecordStorageLocation *LocForRecordReturnVal; 511 DataflowAnalysisContext &DACtx; 512 }; 513 514 } // namespace 515 516 Environment::Environment(DataflowAnalysisContext &DACtx) 517 : DACtx(&DACtx), 518 FlowConditionToken(DACtx.arena().makeFlowConditionToken()) {} 519 520 Environment::Environment(DataflowAnalysisContext &DACtx, 521 const DeclContext &DeclCtx) 522 : Environment(DACtx) { 523 CallStack.push_back(&DeclCtx); 524 } 525 526 void Environment::initialize() { 527 const DeclContext *DeclCtx = getDeclCtx(); 528 if (DeclCtx == nullptr) 529 return; 530 531 const auto *FuncDecl = dyn_cast<FunctionDecl>(DeclCtx); 532 if (FuncDecl == nullptr) 533 return; 534 535 assert(FuncDecl->doesThisDeclarationHaveABody()); 536 537 initFieldsGlobalsAndFuncs(FuncDecl); 538 539 for (const auto *ParamDecl : FuncDecl->parameters()) { 540 assert(ParamDecl != nullptr); 541 setStorageLocation(*ParamDecl, createObject(*ParamDecl, nullptr)); 542 } 543 544 if (FuncDecl->getReturnType()->isRecordType()) 545 LocForRecordReturnVal = &cast<RecordStorageLocation>( 546 createStorageLocation(FuncDecl->getReturnType())); 547 548 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclCtx)) { 549 auto *Parent = MethodDecl->getParent(); 550 assert(Parent != nullptr); 551 552 if (Parent->isLambda()) { 553 for (const auto &Capture : Parent->captures()) { 554 if (Capture.capturesVariable()) { 555 const auto *VarDecl = Capture.getCapturedVar(); 556 assert(VarDecl != nullptr); 557 setStorageLocation(*VarDecl, createObject(*VarDecl, nullptr)); 558 } else if (Capture.capturesThis()) { 559 const auto *SurroundingMethodDecl = 560 cast<CXXMethodDecl>(DeclCtx->getNonClosureAncestor()); 561 QualType ThisPointeeType = 562 SurroundingMethodDecl->getFunctionObjectParameterType(); 563 setThisPointeeStorageLocation( 564 cast<RecordStorageLocation>(createObject(ThisPointeeType))); 565 } 566 } 567 } else if (MethodDecl->isImplicitObjectMemberFunction()) { 568 QualType ThisPointeeType = MethodDecl->getFunctionObjectParameterType(); 569 auto &ThisLoc = 570 cast<RecordStorageLocation>(createStorageLocation(ThisPointeeType)); 571 setThisPointeeStorageLocation(ThisLoc); 572 refreshRecordValue(ThisLoc, *this); 573 // Initialize fields of `*this` with values, but only if we're not 574 // analyzing a constructor; after all, it's the constructor's job to do 575 // this (and we want to be able to test that). 576 if (!isa<CXXConstructorDecl>(MethodDecl)) 577 initializeFieldsWithValues(ThisLoc); 578 } 579 } 580 581 // We do this below the handling of `CXXMethodDecl` above so that we can 582 // be sure that the storage location for `this` has been set. 583 ResultObjectMap = std::make_shared<PrValueToResultObject>( 584 buildResultObjectMap(DACtx, FuncDecl, getThisPointeeStorageLocation(), 585 LocForRecordReturnVal)); 586 } 587 588 // FIXME: Add support for resetting globals after function calls to enable 589 // the implementation of sound analyses. 590 void Environment::initFieldsGlobalsAndFuncs(const FunctionDecl *FuncDecl) { 591 assert(FuncDecl->doesThisDeclarationHaveABody()); 592 593 ReferencedDecls Referenced = getReferencedDecls(*FuncDecl); 594 595 // These have to be added before the lines that follow to ensure that 596 // `create*` work correctly for structs. 597 DACtx->addModeledFields(Referenced.Fields); 598 599 for (const VarDecl *D : Referenced.Globals) { 600 if (getStorageLocation(*D) != nullptr) 601 continue; 602 603 // We don't run transfer functions on the initializers of global variables, 604 // so they won't be associated with a value or storage location. We 605 // therefore intentionally don't pass an initializer to `createObject()`; 606 // in particular, this ensures that `createObject()` will initialize the 607 // fields of record-type variables with values. 608 setStorageLocation(*D, createObject(*D, nullptr)); 609 } 610 611 for (const FunctionDecl *FD : Referenced.Functions) { 612 if (getStorageLocation(*FD) != nullptr) 613 continue; 614 auto &Loc = createStorageLocation(*FD); 615 setStorageLocation(*FD, Loc); 616 } 617 } 618 619 Environment Environment::fork() const { 620 Environment Copy(*this); 621 Copy.FlowConditionToken = DACtx->forkFlowCondition(FlowConditionToken); 622 return Copy; 623 } 624 625 bool Environment::canDescend(unsigned MaxDepth, 626 const DeclContext *Callee) const { 627 return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee); 628 } 629 630 Environment Environment::pushCall(const CallExpr *Call) const { 631 Environment Env(*this); 632 633 if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) { 634 if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) { 635 if (!isa<CXXThisExpr>(Arg)) 636 Env.ThisPointeeLoc = 637 cast<RecordStorageLocation>(getStorageLocation(*Arg)); 638 // Otherwise (when the argument is `this`), retain the current 639 // environment's `ThisPointeeLoc`. 640 } 641 } 642 643 if (Call->getType()->isRecordType() && Call->isPRValue()) 644 Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call); 645 646 Env.pushCallInternal(Call->getDirectCallee(), 647 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs())); 648 649 return Env; 650 } 651 652 Environment Environment::pushCall(const CXXConstructExpr *Call) const { 653 Environment Env(*this); 654 655 Env.ThisPointeeLoc = &Env.getResultObjectLocation(*Call); 656 Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call); 657 658 Env.pushCallInternal(Call->getConstructor(), 659 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs())); 660 661 return Env; 662 } 663 664 void Environment::pushCallInternal(const FunctionDecl *FuncDecl, 665 ArrayRef<const Expr *> Args) { 666 // Canonicalize to the definition of the function. This ensures that we're 667 // putting arguments into the same `ParamVarDecl`s` that the callee will later 668 // be retrieving them from. 669 assert(FuncDecl->getDefinition() != nullptr); 670 FuncDecl = FuncDecl->getDefinition(); 671 672 CallStack.push_back(FuncDecl); 673 674 initFieldsGlobalsAndFuncs(FuncDecl); 675 676 const auto *ParamIt = FuncDecl->param_begin(); 677 678 // FIXME: Parameters don't always map to arguments 1:1; examples include 679 // overloaded operators implemented as member functions, and parameter packs. 680 for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) { 681 assert(ParamIt != FuncDecl->param_end()); 682 const VarDecl *Param = *ParamIt; 683 setStorageLocation(*Param, createObject(*Param, Args[ArgIndex])); 684 } 685 686 ResultObjectMap = std::make_shared<PrValueToResultObject>( 687 buildResultObjectMap(DACtx, FuncDecl, getThisPointeeStorageLocation(), 688 LocForRecordReturnVal)); 689 } 690 691 void Environment::popCall(const CallExpr *Call, const Environment &CalleeEnv) { 692 // We ignore some entries of `CalleeEnv`: 693 // - `DACtx` because is already the same in both 694 // - We don't want the callee's `DeclCtx`, `ReturnVal`, `ReturnLoc` or 695 // `ThisPointeeLoc` because they don't apply to us. 696 // - `DeclToLoc`, `ExprToLoc`, and `ExprToVal` capture information from the 697 // callee's local scope, so when popping that scope, we do not propagate 698 // the maps. 699 this->LocToVal = std::move(CalleeEnv.LocToVal); 700 this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken); 701 702 if (Call->isGLValue()) { 703 if (CalleeEnv.ReturnLoc != nullptr) 704 setStorageLocation(*Call, *CalleeEnv.ReturnLoc); 705 } else if (!Call->getType()->isVoidType()) { 706 if (CalleeEnv.ReturnVal != nullptr) 707 setValue(*Call, *CalleeEnv.ReturnVal); 708 } 709 } 710 711 void Environment::popCall(const CXXConstructExpr *Call, 712 const Environment &CalleeEnv) { 713 // See also comment in `popCall(const CallExpr *, const Environment &)` above. 714 this->LocToVal = std::move(CalleeEnv.LocToVal); 715 this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken); 716 717 if (Value *Val = CalleeEnv.getValue(*CalleeEnv.ThisPointeeLoc)) { 718 setValue(*Call, *Val); 719 } 720 } 721 722 bool Environment::equivalentTo(const Environment &Other, 723 Environment::ValueModel &Model) const { 724 assert(DACtx == Other.DACtx); 725 726 if (ReturnVal != Other.ReturnVal) 727 return false; 728 729 if (ReturnLoc != Other.ReturnLoc) 730 return false; 731 732 if (LocForRecordReturnVal != Other.LocForRecordReturnVal) 733 return false; 734 735 if (ThisPointeeLoc != Other.ThisPointeeLoc) 736 return false; 737 738 if (DeclToLoc != Other.DeclToLoc) 739 return false; 740 741 if (ExprToLoc != Other.ExprToLoc) 742 return false; 743 744 if (!compareKeyToValueMaps(ExprToVal, Other.ExprToVal, *this, Other, Model)) 745 return false; 746 747 if (!compareKeyToValueMaps(LocToVal, Other.LocToVal, *this, Other, Model)) 748 return false; 749 750 return true; 751 } 752 753 LatticeEffect Environment::widen(const Environment &PrevEnv, 754 Environment::ValueModel &Model) { 755 assert(DACtx == PrevEnv.DACtx); 756 assert(ReturnVal == PrevEnv.ReturnVal); 757 assert(ReturnLoc == PrevEnv.ReturnLoc); 758 assert(LocForRecordReturnVal == PrevEnv.LocForRecordReturnVal); 759 assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc); 760 assert(CallStack == PrevEnv.CallStack); 761 assert(ResultObjectMap == PrevEnv.ResultObjectMap); 762 763 auto Effect = LatticeEffect::Unchanged; 764 765 // By the API, `PrevEnv` is a previous version of the environment for the same 766 // block, so we have some guarantees about its shape. In particular, it will 767 // be the result of a join or widen operation on previous values for this 768 // block. For `DeclToLoc`, `ExprToVal`, and `ExprToLoc`, join guarantees that 769 // these maps are subsets of the maps in `PrevEnv`. So, as long as we maintain 770 // this property here, we don't need change their current values to widen. 771 assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size()); 772 assert(ExprToVal.size() <= PrevEnv.ExprToVal.size()); 773 assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size()); 774 775 ExprToVal = widenKeyToValueMap(ExprToVal, PrevEnv.ExprToVal, *this, PrevEnv, 776 Model, Effect); 777 778 LocToVal = widenKeyToValueMap(LocToVal, PrevEnv.LocToVal, *this, PrevEnv, 779 Model, Effect); 780 if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() || 781 ExprToLoc.size() != PrevEnv.ExprToLoc.size() || 782 ExprToVal.size() != PrevEnv.ExprToVal.size() || 783 LocToVal.size() != PrevEnv.LocToVal.size()) 784 Effect = LatticeEffect::Changed; 785 786 return Effect; 787 } 788 789 Environment Environment::join(const Environment &EnvA, const Environment &EnvB, 790 Environment::ValueModel &Model, 791 ExprJoinBehavior ExprBehavior) { 792 assert(EnvA.DACtx == EnvB.DACtx); 793 assert(EnvA.LocForRecordReturnVal == EnvB.LocForRecordReturnVal); 794 assert(EnvA.ThisPointeeLoc == EnvB.ThisPointeeLoc); 795 assert(EnvA.CallStack == EnvB.CallStack); 796 assert(EnvA.ResultObjectMap == EnvB.ResultObjectMap); 797 798 Environment JoinedEnv(*EnvA.DACtx); 799 800 JoinedEnv.CallStack = EnvA.CallStack; 801 JoinedEnv.ResultObjectMap = EnvA.ResultObjectMap; 802 JoinedEnv.LocForRecordReturnVal = EnvA.LocForRecordReturnVal; 803 JoinedEnv.ThisPointeeLoc = EnvA.ThisPointeeLoc; 804 805 if (EnvA.ReturnVal == nullptr || EnvB.ReturnVal == nullptr) { 806 // `ReturnVal` might not always get set -- for example if we have a return 807 // statement of the form `return some_other_func()` and we decide not to 808 // analyze `some_other_func()`. 809 // In this case, we can't say anything about the joined return value -- we 810 // don't simply want to propagate the return value that we do have, because 811 // it might not be the correct one. 812 // This occurs for example in the test `ContextSensitiveMutualRecursion`. 813 JoinedEnv.ReturnVal = nullptr; 814 } else if (areEquivalentValues(*EnvA.ReturnVal, *EnvB.ReturnVal)) { 815 JoinedEnv.ReturnVal = EnvA.ReturnVal; 816 } else { 817 assert(!EnvA.CallStack.empty()); 818 // FIXME: Make `CallStack` a vector of `FunctionDecl` so we don't need this 819 // cast. 820 auto *Func = dyn_cast<FunctionDecl>(EnvA.CallStack.back()); 821 assert(Func != nullptr); 822 if (Value *JoinedVal = 823 joinDistinctValues(Func->getReturnType(), *EnvA.ReturnVal, EnvA, 824 *EnvB.ReturnVal, EnvB, JoinedEnv, Model)) 825 JoinedEnv.ReturnVal = JoinedVal; 826 } 827 828 if (EnvA.ReturnLoc == EnvB.ReturnLoc) 829 JoinedEnv.ReturnLoc = EnvA.ReturnLoc; 830 else 831 JoinedEnv.ReturnLoc = nullptr; 832 833 JoinedEnv.DeclToLoc = intersectDeclToLoc(EnvA.DeclToLoc, EnvB.DeclToLoc); 834 835 // FIXME: update join to detect backedges and simplify the flow condition 836 // accordingly. 837 JoinedEnv.FlowConditionToken = EnvA.DACtx->joinFlowConditions( 838 EnvA.FlowConditionToken, EnvB.FlowConditionToken); 839 840 JoinedEnv.LocToVal = 841 joinLocToVal(EnvA.LocToVal, EnvB.LocToVal, EnvA, EnvB, JoinedEnv, Model); 842 843 if (ExprBehavior == KeepExprState) { 844 JoinedEnv.ExprToVal = joinExprMaps(EnvA.ExprToVal, EnvB.ExprToVal); 845 JoinedEnv.ExprToLoc = joinExprMaps(EnvA.ExprToLoc, EnvB.ExprToLoc); 846 } 847 848 return JoinedEnv; 849 } 850 851 StorageLocation &Environment::createStorageLocation(QualType Type) { 852 return DACtx->createStorageLocation(Type); 853 } 854 855 StorageLocation &Environment::createStorageLocation(const ValueDecl &D) { 856 // Evaluated declarations are always assigned the same storage locations to 857 // ensure that the environment stabilizes across loop iterations. Storage 858 // locations for evaluated declarations are stored in the analysis context. 859 return DACtx->getStableStorageLocation(D); 860 } 861 862 StorageLocation &Environment::createStorageLocation(const Expr &E) { 863 // Evaluated expressions are always assigned the same storage locations to 864 // ensure that the environment stabilizes across loop iterations. Storage 865 // locations for evaluated expressions are stored in the analysis context. 866 return DACtx->getStableStorageLocation(E); 867 } 868 869 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) { 870 assert(!DeclToLoc.contains(&D)); 871 // The only kinds of declarations that may have a "variable" storage location 872 // are declarations of reference type and `BindingDecl`. For all other 873 // declaration, the storage location should be the stable storage location 874 // returned by `createStorageLocation()`. 875 assert(D.getType()->isReferenceType() || isa<BindingDecl>(D) || 876 &Loc == &createStorageLocation(D)); 877 DeclToLoc[&D] = &Loc; 878 } 879 880 StorageLocation *Environment::getStorageLocation(const ValueDecl &D) const { 881 auto It = DeclToLoc.find(&D); 882 if (It == DeclToLoc.end()) 883 return nullptr; 884 885 StorageLocation *Loc = It->second; 886 887 return Loc; 888 } 889 890 void Environment::removeDecl(const ValueDecl &D) { DeclToLoc.erase(&D); } 891 892 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) { 893 // `DeclRefExpr`s to builtin function types aren't glvalues, for some reason, 894 // but we still want to be able to associate a `StorageLocation` with them, 895 // so allow these as an exception. 896 assert(E.isGLValue() || 897 E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)); 898 const Expr &CanonE = ignoreCFGOmittedNodes(E); 899 assert(!ExprToLoc.contains(&CanonE)); 900 ExprToLoc[&CanonE] = &Loc; 901 } 902 903 StorageLocation *Environment::getStorageLocation(const Expr &E) const { 904 // See comment in `setStorageLocation()`. 905 assert(E.isGLValue() || 906 E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)); 907 auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E)); 908 return It == ExprToLoc.end() ? nullptr : &*It->second; 909 } 910 911 RecordStorageLocation & 912 Environment::getResultObjectLocation(const Expr &RecordPRValue) const { 913 assert(RecordPRValue.getType()->isRecordType()); 914 assert(RecordPRValue.isPRValue()); 915 916 assert(ResultObjectMap != nullptr); 917 RecordStorageLocation *Loc = ResultObjectMap->lookup(&RecordPRValue); 918 assert(Loc != nullptr); 919 // In release builds, use the "stable" storage location if the map lookup 920 // failed. 921 if (Loc == nullptr) 922 return cast<RecordStorageLocation>( 923 DACtx->getStableStorageLocation(RecordPRValue)); 924 return *Loc; 925 } 926 927 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) { 928 return DACtx->getOrCreateNullPointerValue(PointeeType); 929 } 930 931 void Environment::initializeFieldsWithValues(RecordStorageLocation &Loc, 932 QualType Type) { 933 llvm::DenseSet<QualType> Visited; 934 int CreatedValuesCount = 0; 935 initializeFieldsWithValues(Loc, Type, Visited, 0, CreatedValuesCount); 936 if (CreatedValuesCount > MaxCompositeValueSize) { 937 llvm::errs() << "Attempting to initialize a huge value of type: " << Type 938 << '\n'; 939 } 940 } 941 942 void Environment::setValue(const StorageLocation &Loc, Value &Val) { 943 assert(!isa<RecordValue>(&Val) || &cast<RecordValue>(&Val)->getLoc() == &Loc); 944 945 LocToVal[&Loc] = &Val; 946 } 947 948 void Environment::setValue(const Expr &E, Value &Val) { 949 const Expr &CanonE = ignoreCFGOmittedNodes(E); 950 951 if (auto *RecordVal = dyn_cast<RecordValue>(&Val)) { 952 assert(&RecordVal->getLoc() == &getResultObjectLocation(CanonE)); 953 (void)RecordVal; 954 } 955 956 assert(CanonE.isPRValue()); 957 ExprToVal[&CanonE] = &Val; 958 } 959 960 Value *Environment::getValue(const StorageLocation &Loc) const { 961 return LocToVal.lookup(&Loc); 962 } 963 964 Value *Environment::getValue(const ValueDecl &D) const { 965 auto *Loc = getStorageLocation(D); 966 if (Loc == nullptr) 967 return nullptr; 968 return getValue(*Loc); 969 } 970 971 Value *Environment::getValue(const Expr &E) const { 972 if (E.isPRValue()) { 973 auto It = ExprToVal.find(&ignoreCFGOmittedNodes(E)); 974 return It == ExprToVal.end() ? nullptr : It->second; 975 } 976 977 auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E)); 978 if (It == ExprToLoc.end()) 979 return nullptr; 980 return getValue(*It->second); 981 } 982 983 Value *Environment::createValue(QualType Type) { 984 llvm::DenseSet<QualType> Visited; 985 int CreatedValuesCount = 0; 986 Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0, 987 CreatedValuesCount); 988 if (CreatedValuesCount > MaxCompositeValueSize) { 989 llvm::errs() << "Attempting to initialize a huge value of type: " << Type 990 << '\n'; 991 } 992 return Val; 993 } 994 995 Value *Environment::createValueUnlessSelfReferential( 996 QualType Type, llvm::DenseSet<QualType> &Visited, int Depth, 997 int &CreatedValuesCount) { 998 assert(!Type.isNull()); 999 assert(!Type->isReferenceType()); 1000 1001 // Allow unlimited fields at depth 1; only cap at deeper nesting levels. 1002 if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) || 1003 Depth > MaxCompositeValueDepth) 1004 return nullptr; 1005 1006 if (Type->isBooleanType()) { 1007 CreatedValuesCount++; 1008 return &makeAtomicBoolValue(); 1009 } 1010 1011 if (Type->isIntegerType()) { 1012 // FIXME: consider instead `return nullptr`, given that we do nothing useful 1013 // with integers, and so distinguishing them serves no purpose, but could 1014 // prevent convergence. 1015 CreatedValuesCount++; 1016 return &arena().create<IntegerValue>(); 1017 } 1018 1019 if (Type->isPointerType()) { 1020 CreatedValuesCount++; 1021 QualType PointeeType = Type->getPointeeType(); 1022 StorageLocation &PointeeLoc = 1023 createLocAndMaybeValue(PointeeType, Visited, Depth, CreatedValuesCount); 1024 1025 return &arena().create<PointerValue>(PointeeLoc); 1026 } 1027 1028 if (Type->isRecordType()) { 1029 CreatedValuesCount++; 1030 auto &Loc = cast<RecordStorageLocation>(createStorageLocation(Type)); 1031 initializeFieldsWithValues(Loc, Loc.getType(), Visited, Depth, 1032 CreatedValuesCount); 1033 1034 return &refreshRecordValue(Loc, *this); 1035 } 1036 1037 return nullptr; 1038 } 1039 1040 StorageLocation & 1041 Environment::createLocAndMaybeValue(QualType Ty, 1042 llvm::DenseSet<QualType> &Visited, 1043 int Depth, int &CreatedValuesCount) { 1044 if (!Visited.insert(Ty.getCanonicalType()).second) 1045 return createStorageLocation(Ty.getNonReferenceType()); 1046 Value *Val = createValueUnlessSelfReferential( 1047 Ty.getNonReferenceType(), Visited, Depth, CreatedValuesCount); 1048 Visited.erase(Ty.getCanonicalType()); 1049 1050 Ty = Ty.getNonReferenceType(); 1051 1052 if (Val == nullptr) 1053 return createStorageLocation(Ty); 1054 1055 if (Ty->isRecordType()) 1056 return cast<RecordValue>(Val)->getLoc(); 1057 1058 StorageLocation &Loc = createStorageLocation(Ty); 1059 setValue(Loc, *Val); 1060 return Loc; 1061 } 1062 1063 void Environment::initializeFieldsWithValues(RecordStorageLocation &Loc, 1064 QualType Type, 1065 llvm::DenseSet<QualType> &Visited, 1066 int Depth, 1067 int &CreatedValuesCount) { 1068 auto initField = [&](QualType FieldType, StorageLocation &FieldLoc) { 1069 if (FieldType->isRecordType()) { 1070 auto &FieldRecordLoc = cast<RecordStorageLocation>(FieldLoc); 1071 setValue(FieldRecordLoc, create<RecordValue>(FieldRecordLoc)); 1072 initializeFieldsWithValues(FieldRecordLoc, FieldRecordLoc.getType(), 1073 Visited, Depth + 1, CreatedValuesCount); 1074 } else { 1075 if (!Visited.insert(FieldType.getCanonicalType()).second) 1076 return; 1077 if (Value *Val = createValueUnlessSelfReferential( 1078 FieldType, Visited, Depth + 1, CreatedValuesCount)) 1079 setValue(FieldLoc, *Val); 1080 Visited.erase(FieldType.getCanonicalType()); 1081 } 1082 }; 1083 1084 for (const FieldDecl *Field : DACtx->getModeledFields(Type)) { 1085 assert(Field != nullptr); 1086 QualType FieldType = Field->getType(); 1087 1088 if (FieldType->isReferenceType()) { 1089 Loc.setChild(*Field, 1090 &createLocAndMaybeValue(FieldType, Visited, Depth + 1, 1091 CreatedValuesCount)); 1092 } else { 1093 StorageLocation *FieldLoc = Loc.getChild(*Field); 1094 assert(FieldLoc != nullptr); 1095 initField(FieldType, *FieldLoc); 1096 } 1097 } 1098 for (const auto &[FieldName, FieldType] : DACtx->getSyntheticFields(Type)) { 1099 // Synthetic fields cannot have reference type, so we don't need to deal 1100 // with this case. 1101 assert(!FieldType->isReferenceType()); 1102 initField(FieldType, Loc.getSyntheticField(FieldName)); 1103 } 1104 } 1105 1106 StorageLocation &Environment::createObjectInternal(const ValueDecl *D, 1107 QualType Ty, 1108 const Expr *InitExpr) { 1109 if (Ty->isReferenceType()) { 1110 // Although variables of reference type always need to be initialized, it 1111 // can happen that we can't see the initializer, so `InitExpr` may still 1112 // be null. 1113 if (InitExpr) { 1114 if (auto *InitExprLoc = getStorageLocation(*InitExpr)) 1115 return *InitExprLoc; 1116 } 1117 1118 // Even though we have an initializer, we might not get an 1119 // InitExprLoc, for example if the InitExpr is a CallExpr for which we 1120 // don't have a function body. In this case, we just invent a storage 1121 // location and value -- it's the best we can do. 1122 return createObjectInternal(D, Ty.getNonReferenceType(), nullptr); 1123 } 1124 1125 StorageLocation &Loc = 1126 D ? createStorageLocation(*D) : createStorageLocation(Ty); 1127 1128 if (Ty->isRecordType()) { 1129 auto &RecordLoc = cast<RecordStorageLocation>(Loc); 1130 if (!InitExpr) 1131 initializeFieldsWithValues(RecordLoc); 1132 refreshRecordValue(RecordLoc, *this); 1133 } else { 1134 Value *Val = nullptr; 1135 if (InitExpr) 1136 // In the (few) cases where an expression is intentionally 1137 // "uninterpreted", `InitExpr` is not associated with a value. There are 1138 // two ways to handle this situation: propagate the status, so that 1139 // uninterpreted initializers result in uninterpreted variables, or 1140 // provide a default value. We choose the latter so that later refinements 1141 // of the variable can be used for reasoning about the surrounding code. 1142 // For this reason, we let this case be handled by the `createValue()` 1143 // call below. 1144 // 1145 // FIXME. If and when we interpret all language cases, change this to 1146 // assert that `InitExpr` is interpreted, rather than supplying a 1147 // default value (assuming we don't update the environment API to return 1148 // references). 1149 Val = getValue(*InitExpr); 1150 if (!Val) 1151 Val = createValue(Ty); 1152 if (Val) 1153 setValue(Loc, *Val); 1154 } 1155 1156 return Loc; 1157 } 1158 1159 void Environment::assume(const Formula &F) { 1160 DACtx->addFlowConditionConstraint(FlowConditionToken, F); 1161 } 1162 1163 bool Environment::proves(const Formula &F) const { 1164 return DACtx->flowConditionImplies(FlowConditionToken, F); 1165 } 1166 1167 bool Environment::allows(const Formula &F) const { 1168 return DACtx->flowConditionAllows(FlowConditionToken, F); 1169 } 1170 1171 void Environment::dump(raw_ostream &OS) const { 1172 llvm::DenseMap<const StorageLocation *, std::string> LocToName; 1173 if (LocForRecordReturnVal != nullptr) 1174 LocToName[LocForRecordReturnVal] = "(returned record)"; 1175 if (ThisPointeeLoc != nullptr) 1176 LocToName[ThisPointeeLoc] = "this"; 1177 1178 OS << "DeclToLoc:\n"; 1179 for (auto [D, L] : DeclToLoc) { 1180 auto Iter = LocToName.insert({L, D->getNameAsString()}).first; 1181 OS << " [" << Iter->second << ", " << L << "]\n"; 1182 } 1183 OS << "ExprToLoc:\n"; 1184 for (auto [E, L] : ExprToLoc) 1185 OS << " [" << E << ", " << L << "]\n"; 1186 1187 OS << "ExprToVal:\n"; 1188 for (auto [E, V] : ExprToVal) 1189 OS << " [" << E << ", " << V << ": " << *V << "]\n"; 1190 1191 OS << "LocToVal:\n"; 1192 for (auto [L, V] : LocToVal) { 1193 OS << " [" << L; 1194 if (auto Iter = LocToName.find(L); Iter != LocToName.end()) 1195 OS << " (" << Iter->second << ")"; 1196 OS << ", " << V << ": " << *V << "]\n"; 1197 } 1198 1199 if (const FunctionDecl *Func = getCurrentFunc()) { 1200 if (Func->getReturnType()->isReferenceType()) { 1201 OS << "ReturnLoc: " << ReturnLoc; 1202 if (auto Iter = LocToName.find(ReturnLoc); Iter != LocToName.end()) 1203 OS << " (" << Iter->second << ")"; 1204 OS << "\n"; 1205 } else if (Func->getReturnType()->isRecordType() || 1206 isa<CXXConstructorDecl>(Func)) { 1207 OS << "LocForRecordReturnVal: " << LocForRecordReturnVal << "\n"; 1208 } else if (!Func->getReturnType()->isVoidType()) { 1209 if (ReturnVal == nullptr) 1210 OS << "ReturnVal: nullptr\n"; 1211 else 1212 OS << "ReturnVal: " << *ReturnVal << "\n"; 1213 } 1214 1215 if (isa<CXXMethodDecl>(Func)) { 1216 OS << "ThisPointeeLoc: " << ThisPointeeLoc << "\n"; 1217 } 1218 } 1219 1220 OS << "\n"; 1221 DACtx->dumpFlowCondition(FlowConditionToken, OS); 1222 } 1223 1224 void Environment::dump() const { 1225 dump(llvm::dbgs()); 1226 } 1227 1228 Environment::PrValueToResultObject Environment::buildResultObjectMap( 1229 DataflowAnalysisContext *DACtx, const FunctionDecl *FuncDecl, 1230 RecordStorageLocation *ThisPointeeLoc, 1231 RecordStorageLocation *LocForRecordReturnVal) { 1232 assert(FuncDecl->doesThisDeclarationHaveABody()); 1233 1234 PrValueToResultObject Map; 1235 1236 ResultObjectVisitor Visitor(Map, LocForRecordReturnVal, *DACtx); 1237 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FuncDecl)) 1238 Visitor.TraverseConstructorInits(Ctor, ThisPointeeLoc); 1239 Visitor.TraverseStmt(FuncDecl->getBody()); 1240 1241 return Map; 1242 } 1243 1244 RecordStorageLocation *getImplicitObjectLocation(const CXXMemberCallExpr &MCE, 1245 const Environment &Env) { 1246 Expr *ImplicitObject = MCE.getImplicitObjectArgument(); 1247 if (ImplicitObject == nullptr) 1248 return nullptr; 1249 if (ImplicitObject->getType()->isPointerType()) { 1250 if (auto *Val = Env.get<PointerValue>(*ImplicitObject)) 1251 return &cast<RecordStorageLocation>(Val->getPointeeLoc()); 1252 return nullptr; 1253 } 1254 return cast_or_null<RecordStorageLocation>( 1255 Env.getStorageLocation(*ImplicitObject)); 1256 } 1257 1258 RecordStorageLocation *getBaseObjectLocation(const MemberExpr &ME, 1259 const Environment &Env) { 1260 Expr *Base = ME.getBase(); 1261 if (Base == nullptr) 1262 return nullptr; 1263 if (ME.isArrow()) { 1264 if (auto *Val = Env.get<PointerValue>(*Base)) 1265 return &cast<RecordStorageLocation>(Val->getPointeeLoc()); 1266 return nullptr; 1267 } 1268 return Env.get<RecordStorageLocation>(*Base); 1269 } 1270 1271 RecordValue &refreshRecordValue(RecordStorageLocation &Loc, Environment &Env) { 1272 auto &NewVal = Env.create<RecordValue>(Loc); 1273 Env.setValue(Loc, NewVal); 1274 return NewVal; 1275 } 1276 1277 RecordValue &refreshRecordValue(const Expr &Expr, Environment &Env) { 1278 assert(Expr.getType()->isRecordType()); 1279 1280 if (Expr.isPRValue()) 1281 refreshRecordValue(Env.getResultObjectLocation(Expr), Env); 1282 1283 if (auto *Loc = Env.get<RecordStorageLocation>(Expr)) 1284 refreshRecordValue(*Loc, Env); 1285 1286 auto &NewVal = *cast<RecordValue>(Env.createValue(Expr.getType())); 1287 Env.setStorageLocation(Expr, NewVal.getLoc()); 1288 return NewVal; 1289 } 1290 1291 } // namespace dataflow 1292 } // namespace clang 1293