ExprEngineC.cpp revision 3b1df8bb941a18c4a7256d7cfcbccb9de7e39995
1//=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines ExprEngine's support for C expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/StaticAnalyzer/Core/CheckerManager.h" 15#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 16 17using namespace clang; 18using namespace ento; 19using llvm::APSInt; 20 21void ExprEngine::VisitBinaryOperator(const BinaryOperator* B, 22 ExplodedNode *Pred, 23 ExplodedNodeSet &Dst) { 24 25 Expr *LHS = B->getLHS()->IgnoreParens(); 26 Expr *RHS = B->getRHS()->IgnoreParens(); 27 28 // FIXME: Prechecks eventually go in ::Visit(). 29 ExplodedNodeSet CheckedSet; 30 ExplodedNodeSet Tmp2; 31 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this); 32 33 // With both the LHS and RHS evaluated, process the operation itself. 34 for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end(); 35 it != ei; ++it) { 36 37 ProgramStateRef state = (*it)->getState(); 38 const LocationContext *LCtx = (*it)->getLocationContext(); 39 SVal LeftV = state->getSVal(LHS, LCtx); 40 SVal RightV = state->getSVal(RHS, LCtx); 41 42 BinaryOperator::Opcode Op = B->getOpcode(); 43 44 if (Op == BO_Assign) { 45 // EXPERIMENTAL: "Conjured" symbols. 46 // FIXME: Handle structs. 47 if (RightV.isUnknown()) { 48 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 49 RightV = svalBuilder.conjureSymbolVal(0, B->getRHS(), LCtx, Count); 50 } 51 // Simulate the effects of a "store": bind the value of the RHS 52 // to the L-Value represented by the LHS. 53 SVal ExprVal = B->isGLValue() ? LeftV : RightV; 54 evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal), 55 LeftV, RightV); 56 continue; 57 } 58 59 if (!B->isAssignmentOp()) { 60 StmtNodeBuilder Bldr(*it, Tmp2, *currentBuilderContext); 61 62 if (B->isAdditiveOp()) { 63 // If one of the operands is a location, conjure a symbol for the other 64 // one (offset) if it's unknown so that memory arithmetic always 65 // results in an ElementRegion. 66 // TODO: This can be removed after we enable history tracking with 67 // SymSymExpr. 68 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 69 if (isa<Loc>(LeftV) && 70 RHS->getType()->isIntegerType() && RightV.isUnknown()) { 71 RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(), 72 Count); 73 } 74 if (isa<Loc>(RightV) && 75 LHS->getType()->isIntegerType() && LeftV.isUnknown()) { 76 LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(), 77 Count); 78 } 79 } 80 81 // Process non-assignments except commas or short-circuited 82 // logical expressions (LAnd and LOr). 83 SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType()); 84 if (Result.isUnknown()) { 85 Bldr.generateNode(B, *it, state); 86 continue; 87 } 88 89 state = state->BindExpr(B, LCtx, Result); 90 Bldr.generateNode(B, *it, state); 91 continue; 92 } 93 94 assert (B->isCompoundAssignmentOp()); 95 96 switch (Op) { 97 default: 98 llvm_unreachable("Invalid opcode for compound assignment."); 99 case BO_MulAssign: Op = BO_Mul; break; 100 case BO_DivAssign: Op = BO_Div; break; 101 case BO_RemAssign: Op = BO_Rem; break; 102 case BO_AddAssign: Op = BO_Add; break; 103 case BO_SubAssign: Op = BO_Sub; break; 104 case BO_ShlAssign: Op = BO_Shl; break; 105 case BO_ShrAssign: Op = BO_Shr; break; 106 case BO_AndAssign: Op = BO_And; break; 107 case BO_XorAssign: Op = BO_Xor; break; 108 case BO_OrAssign: Op = BO_Or; break; 109 } 110 111 // Perform a load (the LHS). This performs the checks for 112 // null dereferences, and so on. 113 ExplodedNodeSet Tmp; 114 SVal location = LeftV; 115 evalLoad(Tmp, B, LHS, *it, state, location); 116 117 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; 118 ++I) { 119 120 state = (*I)->getState(); 121 const LocationContext *LCtx = (*I)->getLocationContext(); 122 SVal V = state->getSVal(LHS, LCtx); 123 124 // Get the computation type. 125 QualType CTy = 126 cast<CompoundAssignOperator>(B)->getComputationResultType(); 127 CTy = getContext().getCanonicalType(CTy); 128 129 QualType CLHSTy = 130 cast<CompoundAssignOperator>(B)->getComputationLHSType(); 131 CLHSTy = getContext().getCanonicalType(CLHSTy); 132 133 QualType LTy = getContext().getCanonicalType(LHS->getType()); 134 135 // Promote LHS. 136 V = svalBuilder.evalCast(V, CLHSTy, LTy); 137 138 // Compute the result of the operation. 139 SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy), 140 B->getType(), CTy); 141 142 // EXPERIMENTAL: "Conjured" symbols. 143 // FIXME: Handle structs. 144 145 SVal LHSVal; 146 147 if (Result.isUnknown()) { 148 149 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 150 151 // The symbolic value is actually for the type of the left-hand side 152 // expression, not the computation type, as this is the value the 153 // LValue on the LHS will bind to. 154 LHSVal = svalBuilder.conjureSymbolVal(0, B->getRHS(), LCtx, LTy, Count); 155 // However, we need to convert the symbol to the computation type. 156 Result = svalBuilder.evalCast(LHSVal, CTy, LTy); 157 } 158 else { 159 // The left-hand side may bind to a different value then the 160 // computation type. 161 LHSVal = svalBuilder.evalCast(Result, LTy, CTy); 162 } 163 164 // In C++, assignment and compound assignment operators return an 165 // lvalue. 166 if (B->isGLValue()) 167 state = state->BindExpr(B, LCtx, location); 168 else 169 state = state->BindExpr(B, LCtx, Result); 170 171 evalStore(Tmp2, B, LHS, *I, state, location, LHSVal); 172 } 173 } 174 175 // FIXME: postvisits eventually go in ::Visit() 176 getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this); 177} 178 179void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 180 ExplodedNodeSet &Dst) { 181 182 CanQualType T = getContext().getCanonicalType(BE->getType()); 183 184 // Get the value of the block itself. 185 SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T, 186 Pred->getLocationContext()); 187 188 ProgramStateRef State = Pred->getState(); 189 190 // If we created a new MemRegion for the block, we should explicitly bind 191 // the captured variables. 192 if (const BlockDataRegion *BDR = 193 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) { 194 195 BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(), 196 E = BDR->referenced_vars_end(); 197 198 for (; I != E; ++I) { 199 const MemRegion *capturedR = I.getCapturedRegion(); 200 const MemRegion *originalR = I.getOriginalRegion(); 201 if (capturedR != originalR) { 202 SVal originalV = State->getSVal(loc::MemRegionVal(originalR)); 203 State = State->bindLoc(loc::MemRegionVal(capturedR), originalV); 204 } 205 } 206 } 207 208 ExplodedNodeSet Tmp; 209 StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext); 210 Bldr.generateNode(BE, Pred, 211 State->BindExpr(BE, Pred->getLocationContext(), V), 212 0, ProgramPoint::PostLValueKind); 213 214 // FIXME: Move all post/pre visits to ::Visit(). 215 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this); 216} 217 218void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex, 219 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 220 221 ExplodedNodeSet dstPreStmt; 222 getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this); 223 224 if (CastE->getCastKind() == CK_LValueToRValue) { 225 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 226 I!=E; ++I) { 227 ExplodedNode *subExprNode = *I; 228 ProgramStateRef state = subExprNode->getState(); 229 const LocationContext *LCtx = subExprNode->getLocationContext(); 230 evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx)); 231 } 232 return; 233 } 234 235 // All other casts. 236 QualType T = CastE->getType(); 237 QualType ExTy = Ex->getType(); 238 239 if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE)) 240 T = ExCast->getTypeAsWritten(); 241 242 StmtNodeBuilder Bldr(dstPreStmt, Dst, *currentBuilderContext); 243 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 244 I != E; ++I) { 245 246 Pred = *I; 247 248 switch (CastE->getCastKind()) { 249 case CK_LValueToRValue: 250 llvm_unreachable("LValueToRValue casts handled earlier."); 251 case CK_ToVoid: 252 continue; 253 // The analyzer doesn't do anything special with these casts, 254 // since it understands retain/release semantics already. 255 case CK_ARCProduceObject: 256 case CK_ARCConsumeObject: 257 case CK_ARCReclaimReturnedObject: 258 case CK_ARCExtendBlockObject: // Fall-through. 259 case CK_CopyAndAutoreleaseBlockObject: 260 // The analyser can ignore atomic casts for now, although some future 261 // checkers may want to make certain that you're not modifying the same 262 // value through atomic and nonatomic pointers. 263 case CK_AtomicToNonAtomic: 264 case CK_NonAtomicToAtomic: 265 // True no-ops. 266 case CK_NoOp: 267 case CK_FunctionToPointerDecay: { 268 // Copy the SVal of Ex to CastE. 269 ProgramStateRef state = Pred->getState(); 270 const LocationContext *LCtx = Pred->getLocationContext(); 271 SVal V = state->getSVal(Ex, LCtx); 272 state = state->BindExpr(CastE, LCtx, V); 273 Bldr.generateNode(CastE, Pred, state); 274 continue; 275 } 276 case CK_Dependent: 277 case CK_ArrayToPointerDecay: 278 case CK_BitCast: 279 case CK_IntegralCast: 280 case CK_NullToPointer: 281 case CK_IntegralToPointer: 282 case CK_PointerToIntegral: 283 case CK_PointerToBoolean: 284 case CK_IntegralToBoolean: 285 case CK_IntegralToFloating: 286 case CK_FloatingToIntegral: 287 case CK_FloatingToBoolean: 288 case CK_FloatingCast: 289 case CK_FloatingRealToComplex: 290 case CK_FloatingComplexToReal: 291 case CK_FloatingComplexToBoolean: 292 case CK_FloatingComplexCast: 293 case CK_FloatingComplexToIntegralComplex: 294 case CK_IntegralRealToComplex: 295 case CK_IntegralComplexToReal: 296 case CK_IntegralComplexToBoolean: 297 case CK_IntegralComplexCast: 298 case CK_IntegralComplexToFloatingComplex: 299 case CK_CPointerToObjCPointerCast: 300 case CK_BlockPointerToObjCPointerCast: 301 case CK_AnyPointerToBlockPointerCast: 302 case CK_ObjCObjectLValueCast: { 303 // Delegate to SValBuilder to process. 304 ProgramStateRef state = Pred->getState(); 305 const LocationContext *LCtx = Pred->getLocationContext(); 306 SVal V = state->getSVal(Ex, LCtx); 307 V = svalBuilder.evalCast(V, T, ExTy); 308 state = state->BindExpr(CastE, LCtx, V); 309 Bldr.generateNode(CastE, Pred, state); 310 continue; 311 } 312 case CK_DerivedToBase: 313 case CK_UncheckedDerivedToBase: { 314 // For DerivedToBase cast, delegate to the store manager. 315 ProgramStateRef state = Pred->getState(); 316 const LocationContext *LCtx = Pred->getLocationContext(); 317 SVal val = state->getSVal(Ex, LCtx); 318 val = getStoreManager().evalDerivedToBase(val, CastE); 319 state = state->BindExpr(CastE, LCtx, val); 320 Bldr.generateNode(CastE, Pred, state); 321 continue; 322 } 323 // Handle C++ dyn_cast. 324 case CK_Dynamic: { 325 ProgramStateRef state = Pred->getState(); 326 const LocationContext *LCtx = Pred->getLocationContext(); 327 SVal val = state->getSVal(Ex, LCtx); 328 329 // Compute the type of the result. 330 QualType resultType = CastE->getType(); 331 if (CastE->isGLValue()) 332 resultType = getContext().getPointerType(resultType); 333 334 bool Failed = false; 335 336 // Check if the value being cast evaluates to 0. 337 if (val.isZeroConstant()) 338 Failed = true; 339 // Else, evaluate the cast. 340 else 341 val = getStoreManager().evalDynamicCast(val, T, Failed); 342 343 if (Failed) { 344 if (T->isReferenceType()) { 345 // A bad_cast exception is thrown if input value is a reference. 346 // Currently, we model this, by generating a sink. 347 Bldr.generateSink(CastE, Pred, state); 348 continue; 349 } else { 350 // If the cast fails on a pointer, bind to 0. 351 state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull()); 352 } 353 } else { 354 // If we don't know if the cast succeeded, conjure a new symbol. 355 if (val.isUnknown()) { 356 DefinedOrUnknownSVal NewSym = 357 svalBuilder.conjureSymbolVal(0, CastE, LCtx, resultType, 358 currentBuilderContext->getCurrentBlockCount()); 359 state = state->BindExpr(CastE, LCtx, NewSym); 360 } else 361 // Else, bind to the derived region value. 362 state = state->BindExpr(CastE, LCtx, val); 363 } 364 Bldr.generateNode(CastE, Pred, state); 365 continue; 366 } 367 // Various C++ casts that are not handled yet. 368 case CK_ToUnion: 369 case CK_BaseToDerived: 370 case CK_NullToMemberPointer: 371 case CK_BaseToDerivedMemberPointer: 372 case CK_DerivedToBaseMemberPointer: 373 case CK_ReinterpretMemberPointer: 374 case CK_UserDefinedConversion: 375 case CK_ConstructorConversion: 376 case CK_VectorSplat: 377 case CK_MemberPointerToBoolean: 378 case CK_LValueBitCast: { 379 // Recover some path-sensitivty by conjuring a new value. 380 QualType resultType = CastE->getType(); 381 if (CastE->isGLValue()) 382 resultType = getContext().getPointerType(resultType); 383 const LocationContext *LCtx = Pred->getLocationContext(); 384 SVal result = svalBuilder.conjureSymbolVal(0, CastE, LCtx, 385 resultType, currentBuilderContext->getCurrentBlockCount()); 386 ProgramStateRef state = Pred->getState()->BindExpr(CastE, LCtx, 387 result); 388 Bldr.generateNode(CastE, Pred, state); 389 continue; 390 } 391 } 392 } 393} 394 395void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, 396 ExplodedNode *Pred, 397 ExplodedNodeSet &Dst) { 398 StmtNodeBuilder B(Pred, Dst, *currentBuilderContext); 399 400 const InitListExpr *ILE 401 = cast<InitListExpr>(CL->getInitializer()->IgnoreParens()); 402 403 ProgramStateRef state = Pred->getState(); 404 SVal ILV = state->getSVal(ILE, Pred->getLocationContext()); 405 const LocationContext *LC = Pred->getLocationContext(); 406 state = state->bindCompoundLiteral(CL, LC, ILV); 407 408 // Compound literal expressions are a GNU extension in C++. 409 // Unlike in C, where CLs are lvalues, in C++ CLs are prvalues, 410 // and like temporary objects created by the functional notation T() 411 // CLs are destroyed at the end of the containing full-expression. 412 // HOWEVER, an rvalue of array type is not something the analyzer can 413 // reason about, since we expect all regions to be wrapped in Locs. 414 // So we treat array CLs as lvalues as well, knowing that they will decay 415 // to pointers as soon as they are used. 416 if (CL->isGLValue() || CL->getType()->isArrayType()) 417 B.generateNode(CL, Pred, state->BindExpr(CL, LC, state->getLValue(CL, LC))); 418 else 419 B.generateNode(CL, Pred, state->BindExpr(CL, LC, ILV)); 420} 421 422void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 423 ExplodedNodeSet &Dst) { 424 425 // FIXME: static variables may have an initializer, but the second 426 // time a function is called those values may not be current. 427 // This may need to be reflected in the CFG. 428 429 // Assumption: The CFG has one DeclStmt per Decl. 430 const Decl *D = *DS->decl_begin(); 431 432 if (!D || !isa<VarDecl>(D)) { 433 //TODO:AZ: remove explicit insertion after refactoring is done. 434 Dst.insert(Pred); 435 return; 436 } 437 438 // FIXME: all pre/post visits should eventually be handled by ::Visit(). 439 ExplodedNodeSet dstPreVisit; 440 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this); 441 442 StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext); 443 const VarDecl *VD = dyn_cast<VarDecl>(D); 444 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end(); 445 I!=E; ++I) { 446 ExplodedNode *N = *I; 447 ProgramStateRef state = N->getState(); 448 449 // Decls without InitExpr are not initialized explicitly. 450 const LocationContext *LC = N->getLocationContext(); 451 452 if (const Expr *InitEx = VD->getInit()) { 453 SVal InitVal = state->getSVal(InitEx, LC); 454 455 if (InitVal == state->getLValue(VD, LC) || 456 (VD->getType()->isArrayType() && 457 isa<CXXConstructExpr>(InitEx->IgnoreImplicit()))) { 458 // We constructed the object directly in the variable. 459 // No need to bind anything. 460 B.generateNode(DS, N, state); 461 } else { 462 // We bound the temp obj region to the CXXConstructExpr. Now recover 463 // the lazy compound value when the variable is not a reference. 464 if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() && 465 !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){ 466 InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion()); 467 assert(isa<nonloc::LazyCompoundVal>(InitVal)); 468 } 469 470 // Recover some path-sensitivity if a scalar value evaluated to 471 // UnknownVal. 472 if (InitVal.isUnknown()) { 473 QualType Ty = InitEx->getType(); 474 if (InitEx->isGLValue()) { 475 Ty = getContext().getPointerType(Ty); 476 } 477 478 InitVal = svalBuilder.conjureSymbolVal(0, InitEx, LC, Ty, 479 currentBuilderContext->getCurrentBlockCount()); 480 } 481 B.takeNodes(N); 482 ExplodedNodeSet Dst2; 483 evalBind(Dst2, DS, N, state->getLValue(VD, LC), InitVal, true); 484 B.addNodes(Dst2); 485 } 486 } 487 else { 488 B.generateNode(DS, N, state); 489 } 490 } 491} 492 493void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, 494 ExplodedNodeSet &Dst) { 495 assert(B->getOpcode() == BO_LAnd || 496 B->getOpcode() == BO_LOr); 497 498 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 499 ProgramStateRef state = Pred->getState(); 500 501 ExplodedNode *N = Pred; 502 while (!isa<BlockEntrance>(N->getLocation())) { 503 ProgramPoint P = N->getLocation(); 504 assert(isa<PreStmt>(P)|| isa<PreStmtPurgeDeadSymbols>(P)); 505 (void) P; 506 assert(N->pred_size() == 1); 507 N = *N->pred_begin(); 508 } 509 assert(N->pred_size() == 1); 510 N = *N->pred_begin(); 511 BlockEdge BE = cast<BlockEdge>(N->getLocation()); 512 SVal X; 513 514 // Determine the value of the expression by introspecting how we 515 // got this location in the CFG. This requires looking at the previous 516 // block we were in and what kind of control-flow transfer was involved. 517 const CFGBlock *SrcBlock = BE.getSrc(); 518 // The only terminator (if there is one) that makes sense is a logical op. 519 CFGTerminator T = SrcBlock->getTerminator(); 520 if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) { 521 (void) Term; 522 assert(Term->isLogicalOp()); 523 assert(SrcBlock->succ_size() == 2); 524 // Did we take the true or false branch? 525 unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0; 526 X = svalBuilder.makeIntVal(constant, B->getType()); 527 } 528 else { 529 // If there is no terminator, by construction the last statement 530 // in SrcBlock is the value of the enclosing expression. 531 // However, we still need to constrain that value to be 0 or 1. 532 assert(!SrcBlock->empty()); 533 CFGStmt Elem = cast<CFGStmt>(*SrcBlock->rbegin()); 534 const Expr *RHS = cast<Expr>(Elem.getStmt()); 535 SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext()); 536 537 DefinedOrUnknownSVal DefinedRHS = cast<DefinedOrUnknownSVal>(RHSVal); 538 ProgramStateRef StTrue, StFalse; 539 llvm::tie(StTrue, StFalse) = N->getState()->assume(DefinedRHS); 540 if (StTrue) { 541 if (StFalse) { 542 // We can't constrain the value to 0 or 1; the best we can do is a cast. 543 X = getSValBuilder().evalCast(RHSVal, B->getType(), RHS->getType()); 544 } else { 545 // The value is known to be true. 546 X = getSValBuilder().makeIntVal(1, B->getType()); 547 } 548 } else { 549 // The value is known to be false. 550 assert(StFalse && "Infeasible path!"); 551 X = getSValBuilder().makeIntVal(0, B->getType()); 552 } 553 } 554 555 Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X)); 556} 557 558void ExprEngine::VisitInitListExpr(const InitListExpr *IE, 559 ExplodedNode *Pred, 560 ExplodedNodeSet &Dst) { 561 StmtNodeBuilder B(Pred, Dst, *currentBuilderContext); 562 563 ProgramStateRef state = Pred->getState(); 564 const LocationContext *LCtx = Pred->getLocationContext(); 565 QualType T = getContext().getCanonicalType(IE->getType()); 566 unsigned NumInitElements = IE->getNumInits(); 567 568 if (T->isArrayType() || T->isRecordType() || T->isVectorType()) { 569 llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList(); 570 571 // Handle base case where the initializer has no elements. 572 // e.g: static int* myArray[] = {}; 573 if (NumInitElements == 0) { 574 SVal V = svalBuilder.makeCompoundVal(T, vals); 575 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V)); 576 return; 577 } 578 579 for (InitListExpr::const_reverse_iterator it = IE->rbegin(), 580 ei = IE->rend(); it != ei; ++it) { 581 vals = getBasicVals().consVals(state->getSVal(cast<Expr>(*it), LCtx), 582 vals); 583 } 584 585 B.generateNode(IE, Pred, 586 state->BindExpr(IE, LCtx, 587 svalBuilder.makeCompoundVal(T, vals))); 588 return; 589 } 590 591 // Handle scalars: int{5} and int{}. 592 assert(NumInitElements <= 1); 593 594 SVal V; 595 if (NumInitElements == 0) 596 V = getSValBuilder().makeZeroVal(T); 597 else 598 V = state->getSVal(IE->getInit(0), LCtx); 599 600 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V)); 601} 602 603void ExprEngine::VisitGuardedExpr(const Expr *Ex, 604 const Expr *L, 605 const Expr *R, 606 ExplodedNode *Pred, 607 ExplodedNodeSet &Dst) { 608 StmtNodeBuilder B(Pred, Dst, *currentBuilderContext); 609 ProgramStateRef state = Pred->getState(); 610 const LocationContext *LCtx = Pred->getLocationContext(); 611 const CFGBlock *SrcBlock = 0; 612 613 for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) { 614 ProgramPoint PP = N->getLocation(); 615 if (isa<PreStmtPurgeDeadSymbols>(PP) || isa<BlockEntrance>(PP)) { 616 assert(N->pred_size() == 1); 617 continue; 618 } 619 SrcBlock = cast<BlockEdge>(&PP)->getSrc(); 620 break; 621 } 622 623 // Find the last expression in the predecessor block. That is the 624 // expression that is used for the value of the ternary expression. 625 bool hasValue = false; 626 SVal V; 627 628 for (CFGBlock::const_reverse_iterator I = SrcBlock->rbegin(), 629 E = SrcBlock->rend(); I != E; ++I) { 630 CFGElement CE = *I; 631 if (CFGStmt *CS = dyn_cast<CFGStmt>(&CE)) { 632 const Expr *ValEx = cast<Expr>(CS->getStmt()); 633 hasValue = true; 634 V = state->getSVal(ValEx, LCtx); 635 break; 636 } 637 } 638 639 assert(hasValue); 640 (void) hasValue; 641 642 // Generate a new node with the binding from the appropriate path. 643 B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true)); 644} 645 646void ExprEngine:: 647VisitOffsetOfExpr(const OffsetOfExpr *OOE, 648 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 649 StmtNodeBuilder B(Pred, Dst, *currentBuilderContext); 650 APSInt IV; 651 if (OOE->EvaluateAsInt(IV, getContext())) { 652 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType())); 653 assert(OOE->getType()->isIntegerType()); 654 assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType()); 655 SVal X = svalBuilder.makeIntVal(IV); 656 B.generateNode(OOE, Pred, 657 Pred->getState()->BindExpr(OOE, Pred->getLocationContext(), 658 X)); 659 } 660 // FIXME: Handle the case where __builtin_offsetof is not a constant. 661} 662 663 664void ExprEngine:: 665VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, 666 ExplodedNode *Pred, 667 ExplodedNodeSet &Dst) { 668 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 669 670 QualType T = Ex->getTypeOfArgument(); 671 672 if (Ex->getKind() == UETT_SizeOf) { 673 if (!T->isIncompleteType() && !T->isConstantSizeType()) { 674 assert(T->isVariableArrayType() && "Unknown non-constant-sized type."); 675 676 // FIXME: Add support for VLA type arguments and VLA expressions. 677 // When that happens, we should probably refactor VLASizeChecker's code. 678 return; 679 } 680 else if (T->getAs<ObjCObjectType>()) { 681 // Some code tries to take the sizeof an ObjCObjectType, relying that 682 // the compiler has laid out its representation. Just report Unknown 683 // for these. 684 return; 685 } 686 } 687 688 APSInt Value = Ex->EvaluateKnownConstInt(getContext()); 689 CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue()); 690 691 ProgramStateRef state = Pred->getState(); 692 state = state->BindExpr(Ex, Pred->getLocationContext(), 693 svalBuilder.makeIntVal(amt.getQuantity(), 694 Ex->getType())); 695 Bldr.generateNode(Ex, Pred, state); 696} 697 698void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, 699 ExplodedNode *Pred, 700 ExplodedNodeSet &Dst) { 701 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 702 switch (U->getOpcode()) { 703 default: { 704 Bldr.takeNodes(Pred); 705 ExplodedNodeSet Tmp; 706 VisitIncrementDecrementOperator(U, Pred, Tmp); 707 Bldr.addNodes(Tmp); 708 } 709 break; 710 case UO_Real: { 711 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 712 713 // FIXME: We don't have complex SValues yet. 714 if (Ex->getType()->isAnyComplexType()) { 715 // Just report "Unknown." 716 break; 717 } 718 719 // For all other types, UO_Real is an identity operation. 720 assert (U->getType() == Ex->getType()); 721 ProgramStateRef state = Pred->getState(); 722 const LocationContext *LCtx = Pred->getLocationContext(); 723 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, 724 state->getSVal(Ex, LCtx))); 725 break; 726 } 727 728 case UO_Imag: { 729 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 730 // FIXME: We don't have complex SValues yet. 731 if (Ex->getType()->isAnyComplexType()) { 732 // Just report "Unknown." 733 break; 734 } 735 // For all other types, UO_Imag returns 0. 736 ProgramStateRef state = Pred->getState(); 737 const LocationContext *LCtx = Pred->getLocationContext(); 738 SVal X = svalBuilder.makeZeroVal(Ex->getType()); 739 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, X)); 740 break; 741 } 742 743 case UO_Plus: 744 assert(!U->isGLValue()); 745 // FALL-THROUGH. 746 case UO_Deref: 747 case UO_AddrOf: 748 case UO_Extension: { 749 // FIXME: We can probably just have some magic in Environment::getSVal() 750 // that propagates values, instead of creating a new node here. 751 // 752 // Unary "+" is a no-op, similar to a parentheses. We still have places 753 // where it may be a block-level expression, so we need to 754 // generate an extra node that just propagates the value of the 755 // subexpression. 756 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 757 ProgramStateRef state = Pred->getState(); 758 const LocationContext *LCtx = Pred->getLocationContext(); 759 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, 760 state->getSVal(Ex, LCtx))); 761 break; 762 } 763 764 case UO_LNot: 765 case UO_Minus: 766 case UO_Not: { 767 assert (!U->isGLValue()); 768 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 769 ProgramStateRef state = Pred->getState(); 770 const LocationContext *LCtx = Pred->getLocationContext(); 771 772 // Get the value of the subexpression. 773 SVal V = state->getSVal(Ex, LCtx); 774 775 if (V.isUnknownOrUndef()) { 776 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, V)); 777 break; 778 } 779 780 switch (U->getOpcode()) { 781 default: 782 llvm_unreachable("Invalid Opcode."); 783 case UO_Not: 784 // FIXME: Do we need to handle promotions? 785 state = state->BindExpr(U, LCtx, evalComplement(cast<NonLoc>(V))); 786 break; 787 case UO_Minus: 788 // FIXME: Do we need to handle promotions? 789 state = state->BindExpr(U, LCtx, evalMinus(cast<NonLoc>(V))); 790 break; 791 case UO_LNot: 792 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)." 793 // 794 // Note: technically we do "E == 0", but this is the same in the 795 // transfer functions as "0 == E". 796 SVal Result; 797 if (isa<Loc>(V)) { 798 Loc X = svalBuilder.makeNull(); 799 Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X, 800 U->getType()); 801 } 802 else { 803 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); 804 Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X, 805 U->getType()); 806 } 807 808 state = state->BindExpr(U, LCtx, Result); 809 break; 810 } 811 Bldr.generateNode(U, Pred, state); 812 break; 813 } 814 } 815 816} 817 818void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U, 819 ExplodedNode *Pred, 820 ExplodedNodeSet &Dst) { 821 // Handle ++ and -- (both pre- and post-increment). 822 assert (U->isIncrementDecrementOp()); 823 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 824 825 const LocationContext *LCtx = Pred->getLocationContext(); 826 ProgramStateRef state = Pred->getState(); 827 SVal loc = state->getSVal(Ex, LCtx); 828 829 // Perform a load. 830 ExplodedNodeSet Tmp; 831 evalLoad(Tmp, U, Ex, Pred, state, loc); 832 833 ExplodedNodeSet Dst2; 834 StmtNodeBuilder Bldr(Tmp, Dst2, *currentBuilderContext); 835 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) { 836 837 state = (*I)->getState(); 838 assert(LCtx == (*I)->getLocationContext()); 839 SVal V2_untested = state->getSVal(Ex, LCtx); 840 841 // Propagate unknown and undefined values. 842 if (V2_untested.isUnknownOrUndef()) { 843 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested)); 844 continue; 845 } 846 DefinedSVal V2 = cast<DefinedSVal>(V2_untested); 847 848 // Handle all other values. 849 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub; 850 851 // If the UnaryOperator has non-location type, use its type to create the 852 // constant value. If the UnaryOperator has location type, create the 853 // constant with int type and pointer width. 854 SVal RHS; 855 856 if (U->getType()->isAnyPointerType()) 857 RHS = svalBuilder.makeArrayIndex(1); 858 else 859 RHS = svalBuilder.makeIntVal(1, U->getType()); 860 861 SVal Result = evalBinOp(state, Op, V2, RHS, U->getType()); 862 863 // Conjure a new symbol if necessary to recover precision. 864 if (Result.isUnknown()){ 865 DefinedOrUnknownSVal SymVal = 866 svalBuilder.conjureSymbolVal(0, Ex, LCtx, 867 currentBuilderContext->getCurrentBlockCount()); 868 Result = SymVal; 869 870 // If the value is a location, ++/-- should always preserve 871 // non-nullness. Check if the original value was non-null, and if so 872 // propagate that constraint. 873 if (Loc::isLocType(U->getType())) { 874 DefinedOrUnknownSVal Constraint = 875 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType())); 876 877 if (!state->assume(Constraint, true)) { 878 // It isn't feasible for the original value to be null. 879 // Propagate this constraint. 880 Constraint = svalBuilder.evalEQ(state, SymVal, 881 svalBuilder.makeZeroVal(U->getType())); 882 883 884 state = state->assume(Constraint, false); 885 assert(state); 886 } 887 } 888 } 889 890 // Since the lvalue-to-rvalue conversion is explicit in the AST, 891 // we bind an l-value if the operator is prefix and an lvalue (in C++). 892 if (U->isGLValue()) 893 state = state->BindExpr(U, LCtx, loc); 894 else 895 state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result); 896 897 // Perform the store. 898 Bldr.takeNodes(*I); 899 ExplodedNodeSet Dst3; 900 evalStore(Dst3, U, U, *I, state, loc, Result); 901 Bldr.addNodes(Dst3); 902 } 903 Dst.insert(Dst2); 904} 905