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/ExprCXX.h" 19 #include "clang/AST/Type.h" 20 #include "clang/Analysis/FlowSensitive/DataflowLattice.h" 21 #include "clang/Analysis/FlowSensitive/StorageLocation.h" 22 #include "clang/Analysis/FlowSensitive/Value.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/DenseSet.h" 25 #include "llvm/Support/Casting.h" 26 #include "llvm/Support/ErrorHandling.h" 27 #include <cassert> 28 #include <memory> 29 #include <utility> 30 31 namespace clang { 32 namespace dataflow { 33 34 // FIXME: convert these to parameters of the analysis or environment. Current 35 // settings have been experimentaly validated, but only for a particular 36 // analysis. 37 static constexpr int MaxCompositeValueDepth = 3; 38 static constexpr int MaxCompositeValueSize = 1000; 39 40 /// Returns a map consisting of key-value entries that are present in both maps. 41 template <typename K, typename V> 42 llvm::DenseMap<K, V> intersectDenseMaps(const llvm::DenseMap<K, V> &Map1, 43 const llvm::DenseMap<K, V> &Map2) { 44 llvm::DenseMap<K, V> Result; 45 for (auto &Entry : Map1) { 46 auto It = Map2.find(Entry.first); 47 if (It != Map2.end() && Entry.second == It->second) 48 Result.insert({Entry.first, Entry.second}); 49 } 50 return Result; 51 } 52 53 static bool areEquivalentIndirectionValues(Value *Val1, Value *Val2) { 54 if (auto *IndVal1 = dyn_cast<ReferenceValue>(Val1)) { 55 auto *IndVal2 = cast<ReferenceValue>(Val2); 56 return &IndVal1->getReferentLoc() == &IndVal2->getReferentLoc(); 57 } 58 if (auto *IndVal1 = dyn_cast<PointerValue>(Val1)) { 59 auto *IndVal2 = cast<PointerValue>(Val2); 60 return &IndVal1->getPointeeLoc() == &IndVal2->getPointeeLoc(); 61 } 62 return false; 63 } 64 65 /// Returns true if and only if `Val1` is equivalent to `Val2`. 66 static bool equivalentValues(QualType Type, Value *Val1, 67 const Environment &Env1, Value *Val2, 68 const Environment &Env2, 69 Environment::ValueModel &Model) { 70 return Val1 == Val2 || areEquivalentIndirectionValues(Val1, Val2) || 71 Model.compareEquivalent(Type, *Val1, Env1, *Val2, Env2); 72 } 73 74 /// Attempts to merge distinct values `Val1` and `Val2` in `Env1` and `Env2`, 75 /// respectively, of the same type `Type`. Merging generally produces a single 76 /// value that (soundly) approximates the two inputs, although the actual 77 /// meaning depends on `Model`. 78 static Value *mergeDistinctValues(QualType Type, Value *Val1, 79 const Environment &Env1, Value *Val2, 80 const Environment &Env2, 81 Environment &MergedEnv, 82 Environment::ValueModel &Model) { 83 // Join distinct boolean values preserving information about the constraints 84 // in the respective path conditions. 85 // 86 // FIXME: Does not work for backedges, since the two (or more) paths will not 87 // have mutually exclusive conditions. 88 if (auto *Expr1 = dyn_cast<BoolValue>(Val1)) { 89 auto *Expr2 = cast<BoolValue>(Val2); 90 return &Env1.makeOr(Env1.makeAnd(Env1.getFlowConditionToken(), *Expr1), 91 Env1.makeAnd(Env2.getFlowConditionToken(), *Expr2)); 92 } 93 94 // FIXME: add unit tests that cover this statement. 95 if (areEquivalentIndirectionValues(Val1, Val2)) { 96 return Val1; 97 } 98 99 // FIXME: Consider destroying `MergedValue` immediately if `ValueModel::merge` 100 // returns false to avoid storing unneeded values in `DACtx`. 101 if (Value *MergedVal = MergedEnv.createValue(Type)) 102 if (Model.merge(Type, *Val1, Env1, *Val2, Env2, *MergedVal, MergedEnv)) 103 return MergedVal; 104 105 return nullptr; 106 } 107 108 /// Initializes a global storage value. 109 static void initGlobalVar(const VarDecl &D, Environment &Env) { 110 if (!D.hasGlobalStorage() || 111 Env.getStorageLocation(D, SkipPast::None) != nullptr) 112 return; 113 114 auto &Loc = Env.createStorageLocation(D); 115 Env.setStorageLocation(D, Loc); 116 if (auto *Val = Env.createValue(D.getType())) 117 Env.setValue(Loc, *Val); 118 } 119 120 /// Initializes a global storage value. 121 static void initGlobalVar(const Decl &D, Environment &Env) { 122 if (auto *V = dyn_cast<VarDecl>(&D)) 123 initGlobalVar(*V, Env); 124 } 125 126 /// Initializes global storage values that are declared or referenced from 127 /// sub-statements of `S`. 128 // FIXME: Add support for resetting globals after function calls to enable 129 // the implementation of sound analyses. 130 static void initGlobalVars(const Stmt &S, Environment &Env) { 131 for (auto *Child : S.children()) { 132 if (Child != nullptr) 133 initGlobalVars(*Child, Env); 134 } 135 136 if (auto *DS = dyn_cast<DeclStmt>(&S)) { 137 if (DS->isSingleDecl()) { 138 initGlobalVar(*DS->getSingleDecl(), Env); 139 } else { 140 for (auto *D : DS->getDeclGroup()) 141 initGlobalVar(*D, Env); 142 } 143 } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) { 144 initGlobalVar(*E->getDecl(), Env); 145 } else if (auto *E = dyn_cast<MemberExpr>(&S)) { 146 initGlobalVar(*E->getMemberDecl(), Env); 147 } 148 } 149 150 // FIXME: Does not precisely handle non-virtual diamond inheritance. A single 151 // field decl will be modeled for all instances of the inherited field. 152 static void 153 getFieldsFromClassHierarchy(QualType Type, 154 llvm::DenseSet<const FieldDecl *> &Fields) { 155 if (Type->isIncompleteType() || Type->isDependentType() || 156 !Type->isRecordType()) 157 return; 158 159 for (const FieldDecl *Field : Type->getAsRecordDecl()->fields()) 160 Fields.insert(Field); 161 if (auto *CXXRecord = Type->getAsCXXRecordDecl()) 162 for (const CXXBaseSpecifier &Base : CXXRecord->bases()) 163 getFieldsFromClassHierarchy(Base.getType(), Fields); 164 } 165 166 /// Gets the set of all fields in the type. 167 static llvm::DenseSet<const FieldDecl *> getObjectFields(QualType Type) { 168 llvm::DenseSet<const FieldDecl *> Fields; 169 getFieldsFromClassHierarchy(Type, Fields); 170 return Fields; 171 } 172 173 Environment::Environment(DataflowAnalysisContext &DACtx) 174 : DACtx(&DACtx), FlowConditionToken(&DACtx.makeFlowConditionToken()) {} 175 176 Environment::Environment(const Environment &Other) 177 : DACtx(Other.DACtx), DeclToLoc(Other.DeclToLoc), 178 ExprToLoc(Other.ExprToLoc), LocToVal(Other.LocToVal), 179 MemberLocToStruct(Other.MemberLocToStruct), 180 FlowConditionToken(&DACtx->forkFlowCondition(*Other.FlowConditionToken)) { 181 } 182 183 Environment &Environment::operator=(const Environment &Other) { 184 Environment Copy(Other); 185 *this = std::move(Copy); 186 return *this; 187 } 188 189 Environment::Environment(DataflowAnalysisContext &DACtx, 190 const DeclContext &DeclCtx) 191 : Environment(DACtx) { 192 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) { 193 assert(FuncDecl->getBody() != nullptr); 194 initGlobalVars(*FuncDecl->getBody(), *this); 195 for (const auto *ParamDecl : FuncDecl->parameters()) { 196 assert(ParamDecl != nullptr); 197 auto &ParamLoc = createStorageLocation(*ParamDecl); 198 setStorageLocation(*ParamDecl, ParamLoc); 199 if (Value *ParamVal = createValue(ParamDecl->getType())) 200 setValue(ParamLoc, *ParamVal); 201 } 202 } 203 204 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) { 205 auto *Parent = MethodDecl->getParent(); 206 assert(Parent != nullptr); 207 if (Parent->isLambda()) 208 MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext()); 209 210 if (MethodDecl && !MethodDecl->isStatic()) { 211 QualType ThisPointeeType = MethodDecl->getThisObjectType(); 212 // FIXME: Add support for union types. 213 if (!ThisPointeeType->isUnionType()) { 214 auto &ThisPointeeLoc = createStorageLocation(ThisPointeeType); 215 DACtx.setThisPointeeStorageLocation(ThisPointeeLoc); 216 if (Value *ThisPointeeVal = createValue(ThisPointeeType)) 217 setValue(ThisPointeeLoc, *ThisPointeeVal); 218 } 219 } 220 } 221 } 222 223 bool Environment::equivalentTo(const Environment &Other, 224 Environment::ValueModel &Model) const { 225 assert(DACtx == Other.DACtx); 226 227 if (DeclToLoc != Other.DeclToLoc) 228 return false; 229 230 if (ExprToLoc != Other.ExprToLoc) 231 return false; 232 233 // Compare the contents for the intersection of their domains. 234 for (auto &Entry : LocToVal) { 235 const StorageLocation *Loc = Entry.first; 236 assert(Loc != nullptr); 237 238 Value *Val = Entry.second; 239 assert(Val != nullptr); 240 241 auto It = Other.LocToVal.find(Loc); 242 if (It == Other.LocToVal.end()) 243 continue; 244 assert(It->second != nullptr); 245 246 if (!equivalentValues(Loc->getType(), Val, *this, It->second, Other, Model)) 247 return false; 248 } 249 250 return true; 251 } 252 253 LatticeJoinEffect Environment::join(const Environment &Other, 254 Environment::ValueModel &Model) { 255 assert(DACtx == Other.DACtx); 256 257 auto Effect = LatticeJoinEffect::Unchanged; 258 259 Environment JoinedEnv(*DACtx); 260 261 JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc); 262 if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size()) 263 Effect = LatticeJoinEffect::Changed; 264 265 JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc); 266 if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size()) 267 Effect = LatticeJoinEffect::Changed; 268 269 JoinedEnv.MemberLocToStruct = 270 intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct); 271 if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size()) 272 Effect = LatticeJoinEffect::Changed; 273 274 // FIXME: set `Effect` as needed. 275 JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions( 276 *FlowConditionToken, *Other.FlowConditionToken); 277 278 for (auto &Entry : LocToVal) { 279 const StorageLocation *Loc = Entry.first; 280 assert(Loc != nullptr); 281 282 Value *Val = Entry.second; 283 assert(Val != nullptr); 284 285 auto It = Other.LocToVal.find(Loc); 286 if (It == Other.LocToVal.end()) 287 continue; 288 assert(It->second != nullptr); 289 290 if (Val == It->second) { 291 JoinedEnv.LocToVal.insert({Loc, Val}); 292 continue; 293 } 294 295 if (Value *MergedVal = mergeDistinctValues( 296 Loc->getType(), Val, *this, It->second, Other, JoinedEnv, Model)) 297 JoinedEnv.LocToVal.insert({Loc, MergedVal}); 298 } 299 if (LocToVal.size() != JoinedEnv.LocToVal.size()) 300 Effect = LatticeJoinEffect::Changed; 301 302 *this = std::move(JoinedEnv); 303 304 return Effect; 305 } 306 307 StorageLocation &Environment::createStorageLocation(QualType Type) { 308 assert(!Type.isNull()); 309 if (Type->isStructureOrClassType() || Type->isUnionType()) { 310 // FIXME: Explore options to avoid eager initialization of fields as some of 311 // them might not be needed for a particular analysis. 312 llvm::DenseMap<const ValueDecl *, StorageLocation *> FieldLocs; 313 for (const FieldDecl *Field : getObjectFields(Type)) 314 FieldLocs.insert({Field, &createStorageLocation(Field->getType())}); 315 return takeOwnership( 316 std::make_unique<AggregateStorageLocation>(Type, std::move(FieldLocs))); 317 } 318 return takeOwnership(std::make_unique<ScalarStorageLocation>(Type)); 319 } 320 321 StorageLocation &Environment::createStorageLocation(const VarDecl &D) { 322 // Evaluated declarations are always assigned the same storage locations to 323 // ensure that the environment stabilizes across loop iterations. Storage 324 // locations for evaluated declarations are stored in the analysis context. 325 if (auto *Loc = DACtx->getStorageLocation(D)) 326 return *Loc; 327 auto &Loc = createStorageLocation(D.getType()); 328 DACtx->setStorageLocation(D, Loc); 329 return Loc; 330 } 331 332 StorageLocation &Environment::createStorageLocation(const Expr &E) { 333 // Evaluated expressions are always assigned the same storage locations to 334 // ensure that the environment stabilizes across loop iterations. Storage 335 // locations for evaluated expressions are stored in the analysis context. 336 if (auto *Loc = DACtx->getStorageLocation(E)) 337 return *Loc; 338 auto &Loc = createStorageLocation(E.getType()); 339 DACtx->setStorageLocation(E, Loc); 340 return Loc; 341 } 342 343 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) { 344 assert(DeclToLoc.find(&D) == DeclToLoc.end()); 345 DeclToLoc[&D] = &Loc; 346 } 347 348 StorageLocation *Environment::getStorageLocation(const ValueDecl &D, 349 SkipPast SP) const { 350 auto It = DeclToLoc.find(&D); 351 return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP); 352 } 353 354 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) { 355 const Expr &CanonE = ignoreCFGOmittedNodes(E); 356 assert(ExprToLoc.find(&CanonE) == ExprToLoc.end()); 357 ExprToLoc[&CanonE] = &Loc; 358 } 359 360 StorageLocation *Environment::getStorageLocation(const Expr &E, 361 SkipPast SP) const { 362 // FIXME: Add a test with parens. 363 auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E)); 364 return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP); 365 } 366 367 StorageLocation *Environment::getThisPointeeStorageLocation() const { 368 return DACtx->getThisPointeeStorageLocation(); 369 } 370 371 void Environment::setValue(const StorageLocation &Loc, Value &Val) { 372 LocToVal[&Loc] = &Val; 373 374 if (auto *StructVal = dyn_cast<StructValue>(&Val)) { 375 auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc); 376 377 const QualType Type = AggregateLoc.getType(); 378 assert(Type->isStructureOrClassType()); 379 380 for (const FieldDecl *Field : getObjectFields(Type)) { 381 assert(Field != nullptr); 382 StorageLocation &FieldLoc = AggregateLoc.getChild(*Field); 383 MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field); 384 if (auto *FieldVal = StructVal->getChild(*Field)) 385 setValue(FieldLoc, *FieldVal); 386 } 387 } 388 389 auto IT = MemberLocToStruct.find(&Loc); 390 if (IT != MemberLocToStruct.end()) { 391 // `Loc` is the location of a struct member so we need to also update the 392 // value of the member in the corresponding `StructValue`. 393 394 assert(IT->second.first != nullptr); 395 StructValue &StructVal = *IT->second.first; 396 397 assert(IT->second.second != nullptr); 398 const ValueDecl &Member = *IT->second.second; 399 400 StructVal.setChild(Member, Val); 401 } 402 } 403 404 Value *Environment::getValue(const StorageLocation &Loc) const { 405 auto It = LocToVal.find(&Loc); 406 return It == LocToVal.end() ? nullptr : It->second; 407 } 408 409 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const { 410 auto *Loc = getStorageLocation(D, SP); 411 if (Loc == nullptr) 412 return nullptr; 413 return getValue(*Loc); 414 } 415 416 Value *Environment::getValue(const Expr &E, SkipPast SP) const { 417 auto *Loc = getStorageLocation(E, SP); 418 if (Loc == nullptr) 419 return nullptr; 420 return getValue(*Loc); 421 } 422 423 Value *Environment::createValue(QualType Type) { 424 llvm::DenseSet<QualType> Visited; 425 int CreatedValuesCount = 0; 426 Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0, 427 CreatedValuesCount); 428 if (CreatedValuesCount > MaxCompositeValueSize) { 429 llvm::errs() << "Attempting to initialize a huge value of type: " << Type 430 << '\n'; 431 } 432 return Val; 433 } 434 435 Value *Environment::createValueUnlessSelfReferential( 436 QualType Type, llvm::DenseSet<QualType> &Visited, int Depth, 437 int &CreatedValuesCount) { 438 assert(!Type.isNull()); 439 440 // Allow unlimited fields at depth 1; only cap at deeper nesting levels. 441 if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) || 442 Depth > MaxCompositeValueDepth) 443 return nullptr; 444 445 if (Type->isBooleanType()) { 446 CreatedValuesCount++; 447 return &makeAtomicBoolValue(); 448 } 449 450 if (Type->isIntegerType()) { 451 CreatedValuesCount++; 452 return &takeOwnership(std::make_unique<IntegerValue>()); 453 } 454 455 if (Type->isReferenceType()) { 456 CreatedValuesCount++; 457 QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType(); 458 auto &PointeeLoc = createStorageLocation(PointeeType); 459 460 if (Visited.insert(PointeeType.getCanonicalType()).second) { 461 Value *PointeeVal = createValueUnlessSelfReferential( 462 PointeeType, Visited, Depth, CreatedValuesCount); 463 Visited.erase(PointeeType.getCanonicalType()); 464 465 if (PointeeVal != nullptr) 466 setValue(PointeeLoc, *PointeeVal); 467 } 468 469 return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc)); 470 } 471 472 if (Type->isPointerType()) { 473 CreatedValuesCount++; 474 QualType PointeeType = Type->castAs<PointerType>()->getPointeeType(); 475 auto &PointeeLoc = createStorageLocation(PointeeType); 476 477 if (Visited.insert(PointeeType.getCanonicalType()).second) { 478 Value *PointeeVal = createValueUnlessSelfReferential( 479 PointeeType, Visited, Depth, CreatedValuesCount); 480 Visited.erase(PointeeType.getCanonicalType()); 481 482 if (PointeeVal != nullptr) 483 setValue(PointeeLoc, *PointeeVal); 484 } 485 486 return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc)); 487 } 488 489 if (Type->isStructureOrClassType()) { 490 CreatedValuesCount++; 491 // FIXME: Initialize only fields that are accessed in the context that is 492 // being analyzed. 493 llvm::DenseMap<const ValueDecl *, Value *> FieldValues; 494 for (const FieldDecl *Field : getObjectFields(Type)) { 495 assert(Field != nullptr); 496 497 QualType FieldType = Field->getType(); 498 if (Visited.contains(FieldType.getCanonicalType())) 499 continue; 500 501 Visited.insert(FieldType.getCanonicalType()); 502 if (auto *FieldValue = createValueUnlessSelfReferential( 503 FieldType, Visited, Depth + 1, CreatedValuesCount)) 504 FieldValues.insert({Field, FieldValue}); 505 Visited.erase(FieldType.getCanonicalType()); 506 } 507 508 return &takeOwnership( 509 std::make_unique<StructValue>(std::move(FieldValues))); 510 } 511 512 return nullptr; 513 } 514 515 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const { 516 switch (SP) { 517 case SkipPast::None: 518 return Loc; 519 case SkipPast::Reference: 520 // References cannot be chained so we only need to skip past one level of 521 // indirection. 522 if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc))) 523 return Val->getReferentLoc(); 524 return Loc; 525 case SkipPast::ReferenceThenPointer: 526 StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference); 527 if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef))) 528 return Val->getPointeeLoc(); 529 return LocPastRef; 530 } 531 llvm_unreachable("bad SkipPast kind"); 532 } 533 534 const StorageLocation &Environment::skip(const StorageLocation &Loc, 535 SkipPast SP) const { 536 return skip(*const_cast<StorageLocation *>(&Loc), SP); 537 } 538 539 void Environment::addToFlowCondition(BoolValue &Val) { 540 DACtx->addFlowConditionConstraint(*FlowConditionToken, Val); 541 } 542 543 bool Environment::flowConditionImplies(BoolValue &Val) const { 544 return DACtx->flowConditionImplies(*FlowConditionToken, Val); 545 } 546 547 } // namespace dataflow 548 } // namespace clang 549