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 // The following AST node kinds are "original initializers": They are the 418 // lowest-level AST node that initializes a given object, and nothing 419 // below them can initialize the same object (or part of it). 420 if (isa<CXXConstructExpr>(E) || isa<CallExpr>(E) || isa<LambdaExpr>(E) || 421 isa<CXXDefaultArgExpr>(E) || isa<CXXDefaultInitExpr>(E) || 422 isa<CXXStdInitializerListExpr>(E) || 423 // We treat `BuiltinBitCastExpr` as an "original initializer" too as 424 // it may not even be casting from a record type -- and even if it is, 425 // the two objects are in general of unrelated type. 426 isa<BuiltinBitCastExpr>(E)) { 427 return; 428 } 429 if (auto *Op = dyn_cast<BinaryOperator>(E); 430 Op && Op->getOpcode() == BO_Cmp) { 431 // Builtin `<=>` returns a `std::strong_ordering` object. 432 return; 433 } 434 435 if (auto *InitList = dyn_cast<InitListExpr>(E)) { 436 if (!InitList->isSemanticForm()) 437 return; 438 if (InitList->isTransparent()) { 439 PropagateResultObject(InitList->getInit(0), Loc); 440 return; 441 } 442 443 RecordInitListHelper InitListHelper(InitList); 444 445 for (auto [Base, Init] : InitListHelper.base_inits()) { 446 assert(Base->getType().getCanonicalType() == 447 Init->getType().getCanonicalType()); 448 449 // Storage location for the base class is the same as that of the 450 // derived class because we "flatten" the object hierarchy and put all 451 // fields in `RecordStorageLocation` of the derived class. 452 PropagateResultObject(Init, Loc); 453 } 454 455 for (auto [Field, Init] : InitListHelper.field_inits()) { 456 // Fields of non-record type are handled in 457 // `TransferVisitor::VisitInitListExpr()`. 458 if (!Field->getType()->isRecordType()) 459 continue; 460 PropagateResultObject( 461 Init, cast<RecordStorageLocation>(Loc->getChild(*Field))); 462 } 463 return; 464 } 465 466 if (auto *Op = dyn_cast<BinaryOperator>(E); Op && Op->isCommaOp()) { 467 PropagateResultObject(Op->getRHS(), Loc); 468 return; 469 } 470 471 if (auto *Cond = dyn_cast<AbstractConditionalOperator>(E)) { 472 PropagateResultObject(Cond->getTrueExpr(), Loc); 473 PropagateResultObject(Cond->getFalseExpr(), Loc); 474 return; 475 } 476 477 if (auto *SE = dyn_cast<StmtExpr>(E)) { 478 PropagateResultObject(cast<Expr>(SE->getSubStmt()->body_back()), Loc); 479 return; 480 } 481 482 // All other expression nodes that propagate a record prvalue should have 483 // exactly one child. 484 SmallVector<Stmt *, 1> Children(E->child_begin(), E->child_end()); 485 LLVM_DEBUG({ 486 if (Children.size() != 1) 487 E->dump(); 488 }); 489 assert(Children.size() == 1); 490 for (Stmt *S : Children) 491 PropagateResultObject(cast<Expr>(S), Loc); 492 } 493 494 private: 495 llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap; 496 RecordStorageLocation *LocForRecordReturnVal; 497 DataflowAnalysisContext &DACtx; 498 }; 499 500 } // namespace 501 502 Environment::Environment(DataflowAnalysisContext &DACtx) 503 : DACtx(&DACtx), 504 FlowConditionToken(DACtx.arena().makeFlowConditionToken()) {} 505 506 Environment::Environment(DataflowAnalysisContext &DACtx, 507 const DeclContext &DeclCtx) 508 : Environment(DACtx) { 509 CallStack.push_back(&DeclCtx); 510 } 511 512 void Environment::initialize() { 513 const DeclContext *DeclCtx = getDeclCtx(); 514 if (DeclCtx == nullptr) 515 return; 516 517 const auto *FuncDecl = dyn_cast<FunctionDecl>(DeclCtx); 518 if (FuncDecl == nullptr) 519 return; 520 521 assert(FuncDecl->doesThisDeclarationHaveABody()); 522 523 initFieldsGlobalsAndFuncs(FuncDecl); 524 525 for (const auto *ParamDecl : FuncDecl->parameters()) { 526 assert(ParamDecl != nullptr); 527 setStorageLocation(*ParamDecl, createObject(*ParamDecl, nullptr)); 528 } 529 530 if (FuncDecl->getReturnType()->isRecordType()) 531 LocForRecordReturnVal = &cast<RecordStorageLocation>( 532 createStorageLocation(FuncDecl->getReturnType())); 533 534 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclCtx)) { 535 auto *Parent = MethodDecl->getParent(); 536 assert(Parent != nullptr); 537 538 if (Parent->isLambda()) { 539 for (const auto &Capture : Parent->captures()) { 540 if (Capture.capturesVariable()) { 541 const auto *VarDecl = Capture.getCapturedVar(); 542 assert(VarDecl != nullptr); 543 setStorageLocation(*VarDecl, createObject(*VarDecl, nullptr)); 544 } else if (Capture.capturesThis()) { 545 const auto *SurroundingMethodDecl = 546 cast<CXXMethodDecl>(DeclCtx->getNonClosureAncestor()); 547 QualType ThisPointeeType = 548 SurroundingMethodDecl->getFunctionObjectParameterType(); 549 setThisPointeeStorageLocation( 550 cast<RecordStorageLocation>(createObject(ThisPointeeType))); 551 } 552 } 553 } else if (MethodDecl->isImplicitObjectMemberFunction()) { 554 QualType ThisPointeeType = MethodDecl->getFunctionObjectParameterType(); 555 auto &ThisLoc = 556 cast<RecordStorageLocation>(createStorageLocation(ThisPointeeType)); 557 setThisPointeeStorageLocation(ThisLoc); 558 refreshRecordValue(ThisLoc, *this); 559 // Initialize fields of `*this` with values, but only if we're not 560 // analyzing a constructor; after all, it's the constructor's job to do 561 // this (and we want to be able to test that). 562 if (!isa<CXXConstructorDecl>(MethodDecl)) 563 initializeFieldsWithValues(ThisLoc); 564 } 565 } 566 567 // We do this below the handling of `CXXMethodDecl` above so that we can 568 // be sure that the storage location for `this` has been set. 569 ResultObjectMap = std::make_shared<PrValueToResultObject>( 570 buildResultObjectMap(DACtx, FuncDecl, getThisPointeeStorageLocation(), 571 LocForRecordReturnVal)); 572 } 573 574 // FIXME: Add support for resetting globals after function calls to enable 575 // the implementation of sound analyses. 576 void Environment::initFieldsGlobalsAndFuncs(const FunctionDecl *FuncDecl) { 577 assert(FuncDecl->doesThisDeclarationHaveABody()); 578 579 ReferencedDecls Referenced = getReferencedDecls(*FuncDecl); 580 581 // These have to be added before the lines that follow to ensure that 582 // `create*` work correctly for structs. 583 DACtx->addModeledFields(Referenced.Fields); 584 585 for (const VarDecl *D : Referenced.Globals) { 586 if (getStorageLocation(*D) != nullptr) 587 continue; 588 589 // We don't run transfer functions on the initializers of global variables, 590 // so they won't be associated with a value or storage location. We 591 // therefore intentionally don't pass an initializer to `createObject()`; 592 // in particular, this ensures that `createObject()` will initialize the 593 // fields of record-type variables with values. 594 setStorageLocation(*D, createObject(*D, nullptr)); 595 } 596 597 for (const FunctionDecl *FD : Referenced.Functions) { 598 if (getStorageLocation(*FD) != nullptr) 599 continue; 600 auto &Loc = createStorageLocation(*FD); 601 setStorageLocation(*FD, Loc); 602 } 603 } 604 605 Environment Environment::fork() const { 606 Environment Copy(*this); 607 Copy.FlowConditionToken = DACtx->forkFlowCondition(FlowConditionToken); 608 return Copy; 609 } 610 611 bool Environment::canDescend(unsigned MaxDepth, 612 const DeclContext *Callee) const { 613 return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee); 614 } 615 616 Environment Environment::pushCall(const CallExpr *Call) const { 617 Environment Env(*this); 618 619 if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) { 620 if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) { 621 if (!isa<CXXThisExpr>(Arg)) 622 Env.ThisPointeeLoc = 623 cast<RecordStorageLocation>(getStorageLocation(*Arg)); 624 // Otherwise (when the argument is `this`), retain the current 625 // environment's `ThisPointeeLoc`. 626 } 627 } 628 629 if (Call->getType()->isRecordType() && Call->isPRValue()) 630 Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call); 631 632 Env.pushCallInternal(Call->getDirectCallee(), 633 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs())); 634 635 return Env; 636 } 637 638 Environment Environment::pushCall(const CXXConstructExpr *Call) const { 639 Environment Env(*this); 640 641 Env.ThisPointeeLoc = &Env.getResultObjectLocation(*Call); 642 Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call); 643 644 Env.pushCallInternal(Call->getConstructor(), 645 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs())); 646 647 return Env; 648 } 649 650 void Environment::pushCallInternal(const FunctionDecl *FuncDecl, 651 ArrayRef<const Expr *> Args) { 652 // Canonicalize to the definition of the function. This ensures that we're 653 // putting arguments into the same `ParamVarDecl`s` that the callee will later 654 // be retrieving them from. 655 assert(FuncDecl->getDefinition() != nullptr); 656 FuncDecl = FuncDecl->getDefinition(); 657 658 CallStack.push_back(FuncDecl); 659 660 initFieldsGlobalsAndFuncs(FuncDecl); 661 662 const auto *ParamIt = FuncDecl->param_begin(); 663 664 // FIXME: Parameters don't always map to arguments 1:1; examples include 665 // overloaded operators implemented as member functions, and parameter packs. 666 for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) { 667 assert(ParamIt != FuncDecl->param_end()); 668 const VarDecl *Param = *ParamIt; 669 setStorageLocation(*Param, createObject(*Param, Args[ArgIndex])); 670 } 671 672 ResultObjectMap = std::make_shared<PrValueToResultObject>( 673 buildResultObjectMap(DACtx, FuncDecl, getThisPointeeStorageLocation(), 674 LocForRecordReturnVal)); 675 } 676 677 void Environment::popCall(const CallExpr *Call, const Environment &CalleeEnv) { 678 // We ignore some entries of `CalleeEnv`: 679 // - `DACtx` because is already the same in both 680 // - We don't want the callee's `DeclCtx`, `ReturnVal`, `ReturnLoc` or 681 // `ThisPointeeLoc` because they don't apply to us. 682 // - `DeclToLoc`, `ExprToLoc`, and `ExprToVal` capture information from the 683 // callee's local scope, so when popping that scope, we do not propagate 684 // the maps. 685 this->LocToVal = std::move(CalleeEnv.LocToVal); 686 this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken); 687 688 if (Call->isGLValue()) { 689 if (CalleeEnv.ReturnLoc != nullptr) 690 setStorageLocation(*Call, *CalleeEnv.ReturnLoc); 691 } else if (!Call->getType()->isVoidType()) { 692 if (CalleeEnv.ReturnVal != nullptr) 693 setValue(*Call, *CalleeEnv.ReturnVal); 694 } 695 } 696 697 void Environment::popCall(const CXXConstructExpr *Call, 698 const Environment &CalleeEnv) { 699 // See also comment in `popCall(const CallExpr *, const Environment &)` above. 700 this->LocToVal = std::move(CalleeEnv.LocToVal); 701 this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken); 702 703 if (Value *Val = CalleeEnv.getValue(*CalleeEnv.ThisPointeeLoc)) { 704 setValue(*Call, *Val); 705 } 706 } 707 708 bool Environment::equivalentTo(const Environment &Other, 709 Environment::ValueModel &Model) const { 710 assert(DACtx == Other.DACtx); 711 712 if (ReturnVal != Other.ReturnVal) 713 return false; 714 715 if (ReturnLoc != Other.ReturnLoc) 716 return false; 717 718 if (LocForRecordReturnVal != Other.LocForRecordReturnVal) 719 return false; 720 721 if (ThisPointeeLoc != Other.ThisPointeeLoc) 722 return false; 723 724 if (DeclToLoc != Other.DeclToLoc) 725 return false; 726 727 if (ExprToLoc != Other.ExprToLoc) 728 return false; 729 730 if (!compareKeyToValueMaps(ExprToVal, Other.ExprToVal, *this, Other, Model)) 731 return false; 732 733 if (!compareKeyToValueMaps(LocToVal, Other.LocToVal, *this, Other, Model)) 734 return false; 735 736 return true; 737 } 738 739 LatticeEffect Environment::widen(const Environment &PrevEnv, 740 Environment::ValueModel &Model) { 741 assert(DACtx == PrevEnv.DACtx); 742 assert(ReturnVal == PrevEnv.ReturnVal); 743 assert(ReturnLoc == PrevEnv.ReturnLoc); 744 assert(LocForRecordReturnVal == PrevEnv.LocForRecordReturnVal); 745 assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc); 746 assert(CallStack == PrevEnv.CallStack); 747 assert(ResultObjectMap == PrevEnv.ResultObjectMap); 748 749 auto Effect = LatticeEffect::Unchanged; 750 751 // By the API, `PrevEnv` is a previous version of the environment for the same 752 // block, so we have some guarantees about its shape. In particular, it will 753 // be the result of a join or widen operation on previous values for this 754 // block. For `DeclToLoc`, `ExprToVal`, and `ExprToLoc`, join guarantees that 755 // these maps are subsets of the maps in `PrevEnv`. So, as long as we maintain 756 // this property here, we don't need change their current values to widen. 757 assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size()); 758 assert(ExprToVal.size() <= PrevEnv.ExprToVal.size()); 759 assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size()); 760 761 ExprToVal = widenKeyToValueMap(ExprToVal, PrevEnv.ExprToVal, *this, PrevEnv, 762 Model, Effect); 763 764 LocToVal = widenKeyToValueMap(LocToVal, PrevEnv.LocToVal, *this, PrevEnv, 765 Model, Effect); 766 if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() || 767 ExprToLoc.size() != PrevEnv.ExprToLoc.size() || 768 ExprToVal.size() != PrevEnv.ExprToVal.size() || 769 LocToVal.size() != PrevEnv.LocToVal.size()) 770 Effect = LatticeEffect::Changed; 771 772 return Effect; 773 } 774 775 Environment Environment::join(const Environment &EnvA, const Environment &EnvB, 776 Environment::ValueModel &Model, 777 ExprJoinBehavior ExprBehavior) { 778 assert(EnvA.DACtx == EnvB.DACtx); 779 assert(EnvA.LocForRecordReturnVal == EnvB.LocForRecordReturnVal); 780 assert(EnvA.ThisPointeeLoc == EnvB.ThisPointeeLoc); 781 assert(EnvA.CallStack == EnvB.CallStack); 782 assert(EnvA.ResultObjectMap == EnvB.ResultObjectMap); 783 784 Environment JoinedEnv(*EnvA.DACtx); 785 786 JoinedEnv.CallStack = EnvA.CallStack; 787 JoinedEnv.ResultObjectMap = EnvA.ResultObjectMap; 788 JoinedEnv.LocForRecordReturnVal = EnvA.LocForRecordReturnVal; 789 JoinedEnv.ThisPointeeLoc = EnvA.ThisPointeeLoc; 790 791 if (EnvA.ReturnVal == nullptr || EnvB.ReturnVal == nullptr) { 792 // `ReturnVal` might not always get set -- for example if we have a return 793 // statement of the form `return some_other_func()` and we decide not to 794 // analyze `some_other_func()`. 795 // In this case, we can't say anything about the joined return value -- we 796 // don't simply want to propagate the return value that we do have, because 797 // it might not be the correct one. 798 // This occurs for example in the test `ContextSensitiveMutualRecursion`. 799 JoinedEnv.ReturnVal = nullptr; 800 } else if (areEquivalentValues(*EnvA.ReturnVal, *EnvB.ReturnVal)) { 801 JoinedEnv.ReturnVal = EnvA.ReturnVal; 802 } else { 803 assert(!EnvA.CallStack.empty()); 804 // FIXME: Make `CallStack` a vector of `FunctionDecl` so we don't need this 805 // cast. 806 auto *Func = dyn_cast<FunctionDecl>(EnvA.CallStack.back()); 807 assert(Func != nullptr); 808 if (Value *JoinedVal = 809 joinDistinctValues(Func->getReturnType(), *EnvA.ReturnVal, EnvA, 810 *EnvB.ReturnVal, EnvB, JoinedEnv, Model)) 811 JoinedEnv.ReturnVal = JoinedVal; 812 } 813 814 if (EnvA.ReturnLoc == EnvB.ReturnLoc) 815 JoinedEnv.ReturnLoc = EnvA.ReturnLoc; 816 else 817 JoinedEnv.ReturnLoc = nullptr; 818 819 JoinedEnv.DeclToLoc = intersectDeclToLoc(EnvA.DeclToLoc, EnvB.DeclToLoc); 820 821 // FIXME: update join to detect backedges and simplify the flow condition 822 // accordingly. 823 JoinedEnv.FlowConditionToken = EnvA.DACtx->joinFlowConditions( 824 EnvA.FlowConditionToken, EnvB.FlowConditionToken); 825 826 JoinedEnv.LocToVal = 827 joinLocToVal(EnvA.LocToVal, EnvB.LocToVal, EnvA, EnvB, JoinedEnv, Model); 828 829 if (ExprBehavior == KeepExprState) { 830 JoinedEnv.ExprToVal = joinExprMaps(EnvA.ExprToVal, EnvB.ExprToVal); 831 JoinedEnv.ExprToLoc = joinExprMaps(EnvA.ExprToLoc, EnvB.ExprToLoc); 832 } 833 834 return JoinedEnv; 835 } 836 837 StorageLocation &Environment::createStorageLocation(QualType Type) { 838 return DACtx->createStorageLocation(Type); 839 } 840 841 StorageLocation &Environment::createStorageLocation(const ValueDecl &D) { 842 // Evaluated declarations are always assigned the same storage locations to 843 // ensure that the environment stabilizes across loop iterations. Storage 844 // locations for evaluated declarations are stored in the analysis context. 845 return DACtx->getStableStorageLocation(D); 846 } 847 848 StorageLocation &Environment::createStorageLocation(const Expr &E) { 849 // Evaluated expressions are always assigned the same storage locations to 850 // ensure that the environment stabilizes across loop iterations. Storage 851 // locations for evaluated expressions are stored in the analysis context. 852 return DACtx->getStableStorageLocation(E); 853 } 854 855 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) { 856 assert(!DeclToLoc.contains(&D)); 857 // The only kinds of declarations that may have a "variable" storage location 858 // are declarations of reference type and `BindingDecl`. For all other 859 // declaration, the storage location should be the stable storage location 860 // returned by `createStorageLocation()`. 861 assert(D.getType()->isReferenceType() || isa<BindingDecl>(D) || 862 &Loc == &createStorageLocation(D)); 863 DeclToLoc[&D] = &Loc; 864 } 865 866 StorageLocation *Environment::getStorageLocation(const ValueDecl &D) const { 867 auto It = DeclToLoc.find(&D); 868 if (It == DeclToLoc.end()) 869 return nullptr; 870 871 StorageLocation *Loc = It->second; 872 873 return Loc; 874 } 875 876 void Environment::removeDecl(const ValueDecl &D) { DeclToLoc.erase(&D); } 877 878 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) { 879 // `DeclRefExpr`s to builtin function types aren't glvalues, for some reason, 880 // but we still want to be able to associate a `StorageLocation` with them, 881 // so allow these as an exception. 882 assert(E.isGLValue() || 883 E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)); 884 const Expr &CanonE = ignoreCFGOmittedNodes(E); 885 assert(!ExprToLoc.contains(&CanonE)); 886 ExprToLoc[&CanonE] = &Loc; 887 } 888 889 StorageLocation *Environment::getStorageLocation(const Expr &E) const { 890 // See comment in `setStorageLocation()`. 891 assert(E.isGLValue() || 892 E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)); 893 auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E)); 894 return It == ExprToLoc.end() ? nullptr : &*It->second; 895 } 896 897 RecordStorageLocation & 898 Environment::getResultObjectLocation(const Expr &RecordPRValue) const { 899 assert(RecordPRValue.getType()->isRecordType()); 900 assert(RecordPRValue.isPRValue()); 901 902 assert(ResultObjectMap != nullptr); 903 RecordStorageLocation *Loc = ResultObjectMap->lookup(&RecordPRValue); 904 assert(Loc != nullptr); 905 // In release builds, use the "stable" storage location if the map lookup 906 // failed. 907 if (Loc == nullptr) 908 return cast<RecordStorageLocation>( 909 DACtx->getStableStorageLocation(RecordPRValue)); 910 return *Loc; 911 } 912 913 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) { 914 return DACtx->getOrCreateNullPointerValue(PointeeType); 915 } 916 917 void Environment::initializeFieldsWithValues(RecordStorageLocation &Loc, 918 QualType Type) { 919 llvm::DenseSet<QualType> Visited; 920 int CreatedValuesCount = 0; 921 initializeFieldsWithValues(Loc, Type, Visited, 0, CreatedValuesCount); 922 if (CreatedValuesCount > MaxCompositeValueSize) { 923 llvm::errs() << "Attempting to initialize a huge value of type: " << Type 924 << '\n'; 925 } 926 } 927 928 void Environment::setValue(const StorageLocation &Loc, Value &Val) { 929 assert(!isa<RecordValue>(&Val) || &cast<RecordValue>(&Val)->getLoc() == &Loc); 930 931 LocToVal[&Loc] = &Val; 932 } 933 934 void Environment::setValue(const Expr &E, Value &Val) { 935 const Expr &CanonE = ignoreCFGOmittedNodes(E); 936 937 if (auto *RecordVal = dyn_cast<RecordValue>(&Val)) { 938 assert(&RecordVal->getLoc() == &getResultObjectLocation(CanonE)); 939 (void)RecordVal; 940 } 941 942 assert(CanonE.isPRValue()); 943 ExprToVal[&CanonE] = &Val; 944 } 945 946 Value *Environment::getValue(const StorageLocation &Loc) const { 947 return LocToVal.lookup(&Loc); 948 } 949 950 Value *Environment::getValue(const ValueDecl &D) const { 951 auto *Loc = getStorageLocation(D); 952 if (Loc == nullptr) 953 return nullptr; 954 return getValue(*Loc); 955 } 956 957 Value *Environment::getValue(const Expr &E) const { 958 if (E.isPRValue()) { 959 auto It = ExprToVal.find(&ignoreCFGOmittedNodes(E)); 960 return It == ExprToVal.end() ? nullptr : It->second; 961 } 962 963 auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E)); 964 if (It == ExprToLoc.end()) 965 return nullptr; 966 return getValue(*It->second); 967 } 968 969 Value *Environment::createValue(QualType Type) { 970 llvm::DenseSet<QualType> Visited; 971 int CreatedValuesCount = 0; 972 Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0, 973 CreatedValuesCount); 974 if (CreatedValuesCount > MaxCompositeValueSize) { 975 llvm::errs() << "Attempting to initialize a huge value of type: " << Type 976 << '\n'; 977 } 978 return Val; 979 } 980 981 Value *Environment::createValueUnlessSelfReferential( 982 QualType Type, llvm::DenseSet<QualType> &Visited, int Depth, 983 int &CreatedValuesCount) { 984 assert(!Type.isNull()); 985 assert(!Type->isReferenceType()); 986 987 // Allow unlimited fields at depth 1; only cap at deeper nesting levels. 988 if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) || 989 Depth > MaxCompositeValueDepth) 990 return nullptr; 991 992 if (Type->isBooleanType()) { 993 CreatedValuesCount++; 994 return &makeAtomicBoolValue(); 995 } 996 997 if (Type->isIntegerType()) { 998 // FIXME: consider instead `return nullptr`, given that we do nothing useful 999 // with integers, and so distinguishing them serves no purpose, but could 1000 // prevent convergence. 1001 CreatedValuesCount++; 1002 return &arena().create<IntegerValue>(); 1003 } 1004 1005 if (Type->isPointerType()) { 1006 CreatedValuesCount++; 1007 QualType PointeeType = Type->getPointeeType(); 1008 StorageLocation &PointeeLoc = 1009 createLocAndMaybeValue(PointeeType, Visited, Depth, CreatedValuesCount); 1010 1011 return &arena().create<PointerValue>(PointeeLoc); 1012 } 1013 1014 if (Type->isRecordType()) { 1015 CreatedValuesCount++; 1016 auto &Loc = cast<RecordStorageLocation>(createStorageLocation(Type)); 1017 initializeFieldsWithValues(Loc, Loc.getType(), Visited, Depth, 1018 CreatedValuesCount); 1019 1020 return &refreshRecordValue(Loc, *this); 1021 } 1022 1023 return nullptr; 1024 } 1025 1026 StorageLocation & 1027 Environment::createLocAndMaybeValue(QualType Ty, 1028 llvm::DenseSet<QualType> &Visited, 1029 int Depth, int &CreatedValuesCount) { 1030 if (!Visited.insert(Ty.getCanonicalType()).second) 1031 return createStorageLocation(Ty.getNonReferenceType()); 1032 Value *Val = createValueUnlessSelfReferential( 1033 Ty.getNonReferenceType(), Visited, Depth, CreatedValuesCount); 1034 Visited.erase(Ty.getCanonicalType()); 1035 1036 Ty = Ty.getNonReferenceType(); 1037 1038 if (Val == nullptr) 1039 return createStorageLocation(Ty); 1040 1041 if (Ty->isRecordType()) 1042 return cast<RecordValue>(Val)->getLoc(); 1043 1044 StorageLocation &Loc = createStorageLocation(Ty); 1045 setValue(Loc, *Val); 1046 return Loc; 1047 } 1048 1049 void Environment::initializeFieldsWithValues(RecordStorageLocation &Loc, 1050 QualType Type, 1051 llvm::DenseSet<QualType> &Visited, 1052 int Depth, 1053 int &CreatedValuesCount) { 1054 auto initField = [&](QualType FieldType, StorageLocation &FieldLoc) { 1055 if (FieldType->isRecordType()) { 1056 auto &FieldRecordLoc = cast<RecordStorageLocation>(FieldLoc); 1057 setValue(FieldRecordLoc, create<RecordValue>(FieldRecordLoc)); 1058 initializeFieldsWithValues(FieldRecordLoc, FieldRecordLoc.getType(), 1059 Visited, Depth + 1, CreatedValuesCount); 1060 } else { 1061 if (!Visited.insert(FieldType.getCanonicalType()).second) 1062 return; 1063 if (Value *Val = createValueUnlessSelfReferential( 1064 FieldType, Visited, Depth + 1, CreatedValuesCount)) 1065 setValue(FieldLoc, *Val); 1066 Visited.erase(FieldType.getCanonicalType()); 1067 } 1068 }; 1069 1070 for (const FieldDecl *Field : DACtx->getModeledFields(Type)) { 1071 assert(Field != nullptr); 1072 QualType FieldType = Field->getType(); 1073 1074 if (FieldType->isReferenceType()) { 1075 Loc.setChild(*Field, 1076 &createLocAndMaybeValue(FieldType, Visited, Depth + 1, 1077 CreatedValuesCount)); 1078 } else { 1079 StorageLocation *FieldLoc = Loc.getChild(*Field); 1080 assert(FieldLoc != nullptr); 1081 initField(FieldType, *FieldLoc); 1082 } 1083 } 1084 for (const auto &[FieldName, FieldType] : DACtx->getSyntheticFields(Type)) { 1085 // Synthetic fields cannot have reference type, so we don't need to deal 1086 // with this case. 1087 assert(!FieldType->isReferenceType()); 1088 initField(FieldType, Loc.getSyntheticField(FieldName)); 1089 } 1090 } 1091 1092 StorageLocation &Environment::createObjectInternal(const ValueDecl *D, 1093 QualType Ty, 1094 const Expr *InitExpr) { 1095 if (Ty->isReferenceType()) { 1096 // Although variables of reference type always need to be initialized, it 1097 // can happen that we can't see the initializer, so `InitExpr` may still 1098 // be null. 1099 if (InitExpr) { 1100 if (auto *InitExprLoc = getStorageLocation(*InitExpr)) 1101 return *InitExprLoc; 1102 } 1103 1104 // Even though we have an initializer, we might not get an 1105 // InitExprLoc, for example if the InitExpr is a CallExpr for which we 1106 // don't have a function body. In this case, we just invent a storage 1107 // location and value -- it's the best we can do. 1108 return createObjectInternal(D, Ty.getNonReferenceType(), nullptr); 1109 } 1110 1111 StorageLocation &Loc = 1112 D ? createStorageLocation(*D) : createStorageLocation(Ty); 1113 1114 if (Ty->isRecordType()) { 1115 auto &RecordLoc = cast<RecordStorageLocation>(Loc); 1116 if (!InitExpr) 1117 initializeFieldsWithValues(RecordLoc); 1118 refreshRecordValue(RecordLoc, *this); 1119 } else { 1120 Value *Val = nullptr; 1121 if (InitExpr) 1122 // In the (few) cases where an expression is intentionally 1123 // "uninterpreted", `InitExpr` is not associated with a value. There are 1124 // two ways to handle this situation: propagate the status, so that 1125 // uninterpreted initializers result in uninterpreted variables, or 1126 // provide a default value. We choose the latter so that later refinements 1127 // of the variable can be used for reasoning about the surrounding code. 1128 // For this reason, we let this case be handled by the `createValue()` 1129 // call below. 1130 // 1131 // FIXME. If and when we interpret all language cases, change this to 1132 // assert that `InitExpr` is interpreted, rather than supplying a 1133 // default value (assuming we don't update the environment API to return 1134 // references). 1135 Val = getValue(*InitExpr); 1136 if (!Val) 1137 Val = createValue(Ty); 1138 if (Val) 1139 setValue(Loc, *Val); 1140 } 1141 1142 return Loc; 1143 } 1144 1145 void Environment::assume(const Formula &F) { 1146 DACtx->addFlowConditionConstraint(FlowConditionToken, F); 1147 } 1148 1149 bool Environment::proves(const Formula &F) const { 1150 return DACtx->flowConditionImplies(FlowConditionToken, F); 1151 } 1152 1153 bool Environment::allows(const Formula &F) const { 1154 return DACtx->flowConditionAllows(FlowConditionToken, F); 1155 } 1156 1157 void Environment::dump(raw_ostream &OS) const { 1158 llvm::DenseMap<const StorageLocation *, std::string> LocToName; 1159 if (LocForRecordReturnVal != nullptr) 1160 LocToName[LocForRecordReturnVal] = "(returned record)"; 1161 if (ThisPointeeLoc != nullptr) 1162 LocToName[ThisPointeeLoc] = "this"; 1163 1164 OS << "DeclToLoc:\n"; 1165 for (auto [D, L] : DeclToLoc) { 1166 auto Iter = LocToName.insert({L, D->getNameAsString()}).first; 1167 OS << " [" << Iter->second << ", " << L << "]\n"; 1168 } 1169 OS << "ExprToLoc:\n"; 1170 for (auto [E, L] : ExprToLoc) 1171 OS << " [" << E << ", " << L << "]\n"; 1172 1173 OS << "ExprToVal:\n"; 1174 for (auto [E, V] : ExprToVal) 1175 OS << " [" << E << ", " << V << ": " << *V << "]\n"; 1176 1177 OS << "LocToVal:\n"; 1178 for (auto [L, V] : LocToVal) { 1179 OS << " [" << L; 1180 if (auto Iter = LocToName.find(L); Iter != LocToName.end()) 1181 OS << " (" << Iter->second << ")"; 1182 OS << ", " << V << ": " << *V << "]\n"; 1183 } 1184 1185 if (const FunctionDecl *Func = getCurrentFunc()) { 1186 if (Func->getReturnType()->isReferenceType()) { 1187 OS << "ReturnLoc: " << ReturnLoc; 1188 if (auto Iter = LocToName.find(ReturnLoc); Iter != LocToName.end()) 1189 OS << " (" << Iter->second << ")"; 1190 OS << "\n"; 1191 } else if (Func->getReturnType()->isRecordType() || 1192 isa<CXXConstructorDecl>(Func)) { 1193 OS << "LocForRecordReturnVal: " << LocForRecordReturnVal << "\n"; 1194 } else if (!Func->getReturnType()->isVoidType()) { 1195 if (ReturnVal == nullptr) 1196 OS << "ReturnVal: nullptr\n"; 1197 else 1198 OS << "ReturnVal: " << *ReturnVal << "\n"; 1199 } 1200 1201 if (isa<CXXMethodDecl>(Func)) { 1202 OS << "ThisPointeeLoc: " << ThisPointeeLoc << "\n"; 1203 } 1204 } 1205 1206 OS << "\n"; 1207 DACtx->dumpFlowCondition(FlowConditionToken, OS); 1208 } 1209 1210 void Environment::dump() const { 1211 dump(llvm::dbgs()); 1212 } 1213 1214 Environment::PrValueToResultObject Environment::buildResultObjectMap( 1215 DataflowAnalysisContext *DACtx, const FunctionDecl *FuncDecl, 1216 RecordStorageLocation *ThisPointeeLoc, 1217 RecordStorageLocation *LocForRecordReturnVal) { 1218 assert(FuncDecl->doesThisDeclarationHaveABody()); 1219 1220 PrValueToResultObject Map; 1221 1222 ResultObjectVisitor Visitor(Map, LocForRecordReturnVal, *DACtx); 1223 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FuncDecl)) 1224 Visitor.TraverseConstructorInits(Ctor, ThisPointeeLoc); 1225 Visitor.TraverseStmt(FuncDecl->getBody()); 1226 1227 return Map; 1228 } 1229 1230 RecordStorageLocation *getImplicitObjectLocation(const CXXMemberCallExpr &MCE, 1231 const Environment &Env) { 1232 Expr *ImplicitObject = MCE.getImplicitObjectArgument(); 1233 if (ImplicitObject == nullptr) 1234 return nullptr; 1235 if (ImplicitObject->getType()->isPointerType()) { 1236 if (auto *Val = Env.get<PointerValue>(*ImplicitObject)) 1237 return &cast<RecordStorageLocation>(Val->getPointeeLoc()); 1238 return nullptr; 1239 } 1240 return cast_or_null<RecordStorageLocation>( 1241 Env.getStorageLocation(*ImplicitObject)); 1242 } 1243 1244 RecordStorageLocation *getBaseObjectLocation(const MemberExpr &ME, 1245 const Environment &Env) { 1246 Expr *Base = ME.getBase(); 1247 if (Base == nullptr) 1248 return nullptr; 1249 if (ME.isArrow()) { 1250 if (auto *Val = Env.get<PointerValue>(*Base)) 1251 return &cast<RecordStorageLocation>(Val->getPointeeLoc()); 1252 return nullptr; 1253 } 1254 return Env.get<RecordStorageLocation>(*Base); 1255 } 1256 1257 RecordValue &refreshRecordValue(RecordStorageLocation &Loc, Environment &Env) { 1258 auto &NewVal = Env.create<RecordValue>(Loc); 1259 Env.setValue(Loc, NewVal); 1260 return NewVal; 1261 } 1262 1263 RecordValue &refreshRecordValue(const Expr &Expr, Environment &Env) { 1264 assert(Expr.getType()->isRecordType()); 1265 1266 if (Expr.isPRValue()) 1267 refreshRecordValue(Env.getResultObjectLocation(Expr), Env); 1268 1269 if (auto *Loc = Env.get<RecordStorageLocation>(Expr)) 1270 refreshRecordValue(*Loc, Env); 1271 1272 auto &NewVal = *cast<RecordValue>(Env.createValue(Expr.getType())); 1273 Env.setStorageLocation(Expr, NewVal.getLoc()); 1274 return NewVal; 1275 } 1276 1277 } // namespace dataflow 1278 } // namespace clang 1279