ExprEngineC.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. //=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- 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 ExprEngine's support for C expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ExprCXX.h"
  13. #include "clang/AST/DeclCXX.h"
  14. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  16. using namespace clang;
  17. using namespace ento;
  18. using llvm::APSInt;
  19. /// Optionally conjure and return a symbol for offset when processing
  20. /// an expression \p Expression.
  21. /// If \p Other is a location, conjure a symbol for \p Symbol
  22. /// (offset) if it is unknown so that memory arithmetic always
  23. /// results in an ElementRegion.
  24. /// \p Count The number of times the current basic block was visited.
  25. static SVal conjureOffsetSymbolOnLocation(
  26. SVal Symbol, SVal Other, Expr* Expression, SValBuilder &svalBuilder,
  27. unsigned Count, const LocationContext *LCtx) {
  28. QualType Ty = Expression->getType();
  29. if (Other.getAs<Loc>() &&
  30. Ty->isIntegralOrEnumerationType() &&
  31. Symbol.isUnknown()) {
  32. return svalBuilder.conjureSymbolVal(Expression, LCtx, Ty, Count);
  33. }
  34. return Symbol;
  35. }
  36. void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
  37. ExplodedNode *Pred,
  38. ExplodedNodeSet &Dst) {
  39. Expr *LHS = B->getLHS()->IgnoreParens();
  40. Expr *RHS = B->getRHS()->IgnoreParens();
  41. // FIXME: Prechecks eventually go in ::Visit().
  42. ExplodedNodeSet CheckedSet;
  43. ExplodedNodeSet Tmp2;
  44. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
  45. // With both the LHS and RHS evaluated, process the operation itself.
  46. for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
  47. it != ei; ++it) {
  48. ProgramStateRef state = (*it)->getState();
  49. const LocationContext *LCtx = (*it)->getLocationContext();
  50. SVal LeftV = state->getSVal(LHS, LCtx);
  51. SVal RightV = state->getSVal(RHS, LCtx);
  52. BinaryOperator::Opcode Op = B->getOpcode();
  53. if (Op == BO_Assign) {
  54. // EXPERIMENTAL: "Conjured" symbols.
  55. // FIXME: Handle structs.
  56. if (RightV.isUnknown()) {
  57. unsigned Count = currBldrCtx->blockCount();
  58. RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx,
  59. Count);
  60. }
  61. // Simulate the effects of a "store": bind the value of the RHS
  62. // to the L-Value represented by the LHS.
  63. SVal ExprVal = B->isGLValue() ? LeftV : RightV;
  64. evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
  65. LeftV, RightV);
  66. continue;
  67. }
  68. if (!B->isAssignmentOp()) {
  69. StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
  70. if (B->isAdditiveOp()) {
  71. // TODO: This can be removed after we enable history tracking with
  72. // SymSymExpr.
  73. unsigned Count = currBldrCtx->blockCount();
  74. RightV = conjureOffsetSymbolOnLocation(
  75. RightV, LeftV, RHS, svalBuilder, Count, LCtx);
  76. LeftV = conjureOffsetSymbolOnLocation(
  77. LeftV, RightV, LHS, svalBuilder, Count, LCtx);
  78. }
  79. // Although we don't yet model pointers-to-members, we do need to make
  80. // sure that the members of temporaries have a valid 'this' pointer for
  81. // other checks.
  82. if (B->getOpcode() == BO_PtrMemD)
  83. state = createTemporaryRegionIfNeeded(state, LCtx, LHS);
  84. // Process non-assignments except commas or short-circuited
  85. // logical expressions (LAnd and LOr).
  86. SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
  87. if (!Result.isUnknown()) {
  88. state = state->BindExpr(B, LCtx, Result);
  89. } else {
  90. // If we cannot evaluate the operation escape the operands.
  91. state = escapeValues(state, LeftV, PSK_EscapeOther);
  92. state = escapeValues(state, RightV, PSK_EscapeOther);
  93. }
  94. Bldr.generateNode(B, *it, state);
  95. continue;
  96. }
  97. assert (B->isCompoundAssignmentOp());
  98. switch (Op) {
  99. default:
  100. llvm_unreachable("Invalid opcode for compound assignment.");
  101. case BO_MulAssign: Op = BO_Mul; break;
  102. case BO_DivAssign: Op = BO_Div; break;
  103. case BO_RemAssign: Op = BO_Rem; break;
  104. case BO_AddAssign: Op = BO_Add; break;
  105. case BO_SubAssign: Op = BO_Sub; break;
  106. case BO_ShlAssign: Op = BO_Shl; break;
  107. case BO_ShrAssign: Op = BO_Shr; break;
  108. case BO_AndAssign: Op = BO_And; break;
  109. case BO_XorAssign: Op = BO_Xor; break;
  110. case BO_OrAssign: Op = BO_Or; break;
  111. }
  112. // Perform a load (the LHS). This performs the checks for
  113. // null dereferences, and so on.
  114. ExplodedNodeSet Tmp;
  115. SVal location = LeftV;
  116. evalLoad(Tmp, B, LHS, *it, state, location);
  117. for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
  118. ++I) {
  119. state = (*I)->getState();
  120. const LocationContext *LCtx = (*I)->getLocationContext();
  121. SVal V = state->getSVal(LHS, LCtx);
  122. // Get the computation type.
  123. QualType CTy =
  124. cast<CompoundAssignOperator>(B)->getComputationResultType();
  125. CTy = getContext().getCanonicalType(CTy);
  126. QualType CLHSTy =
  127. cast<CompoundAssignOperator>(B)->getComputationLHSType();
  128. CLHSTy = getContext().getCanonicalType(CLHSTy);
  129. QualType LTy = getContext().getCanonicalType(LHS->getType());
  130. // Promote LHS.
  131. V = svalBuilder.evalCast(V, CLHSTy, LTy);
  132. // Compute the result of the operation.
  133. SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
  134. B->getType(), CTy);
  135. // EXPERIMENTAL: "Conjured" symbols.
  136. // FIXME: Handle structs.
  137. SVal LHSVal;
  138. if (Result.isUnknown()) {
  139. // The symbolic value is actually for the type of the left-hand side
  140. // expression, not the computation type, as this is the value the
  141. // LValue on the LHS will bind to.
  142. LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy,
  143. currBldrCtx->blockCount());
  144. // However, we need to convert the symbol to the computation type.
  145. Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
  146. }
  147. else {
  148. // The left-hand side may bind to a different value then the
  149. // computation type.
  150. LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
  151. }
  152. // In C++, assignment and compound assignment operators return an
  153. // lvalue.
  154. if (B->isGLValue())
  155. state = state->BindExpr(B, LCtx, location);
  156. else
  157. state = state->BindExpr(B, LCtx, Result);
  158. evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
  159. }
  160. }
  161. // FIXME: postvisits eventually go in ::Visit()
  162. getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
  163. }
  164. void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
  165. ExplodedNodeSet &Dst) {
  166. CanQualType T = getContext().getCanonicalType(BE->getType());
  167. const BlockDecl *BD = BE->getBlockDecl();
  168. // Get the value of the block itself.
  169. SVal V = svalBuilder.getBlockPointer(BD, T,
  170. Pred->getLocationContext(),
  171. currBldrCtx->blockCount());
  172. ProgramStateRef State = Pred->getState();
  173. // If we created a new MemRegion for the block, we should explicitly bind
  174. // the captured variables.
  175. if (const BlockDataRegion *BDR =
  176. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  177. BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
  178. E = BDR->referenced_vars_end();
  179. auto CI = BD->capture_begin();
  180. auto CE = BD->capture_end();
  181. for (; I != E; ++I) {
  182. const VarRegion *capturedR = I.getCapturedRegion();
  183. const TypedValueRegion *originalR = I.getOriginalRegion();
  184. // If the capture had a copy expression, use the result of evaluating
  185. // that expression, otherwise use the original value.
  186. // We rely on the invariant that the block declaration's capture variables
  187. // are a prefix of the BlockDataRegion's referenced vars (which may include
  188. // referenced globals, etc.) to enable fast lookup of the capture for a
  189. // given referenced var.
  190. const Expr *copyExpr = nullptr;
  191. if (CI != CE) {
  192. assert(CI->getVariable() == capturedR->getDecl());
  193. copyExpr = CI->getCopyExpr();
  194. CI++;
  195. }
  196. if (capturedR != originalR) {
  197. SVal originalV;
  198. const LocationContext *LCtx = Pred->getLocationContext();
  199. if (copyExpr) {
  200. originalV = State->getSVal(copyExpr, LCtx);
  201. } else {
  202. originalV = State->getSVal(loc::MemRegionVal(originalR));
  203. }
  204. State = State->bindLoc(loc::MemRegionVal(capturedR), originalV, LCtx);
  205. }
  206. }
  207. }
  208. ExplodedNodeSet Tmp;
  209. StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
  210. Bldr.generateNode(BE, Pred,
  211. State->BindExpr(BE, Pred->getLocationContext(), V),
  212. nullptr, ProgramPoint::PostLValueKind);
  213. // FIXME: Move all post/pre visits to ::Visit().
  214. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
  215. }
  216. ProgramStateRef ExprEngine::handleLValueBitCast(
  217. ProgramStateRef state, const Expr* Ex, const LocationContext* LCtx,
  218. QualType T, QualType ExTy, const CastExpr* CastE, StmtNodeBuilder& Bldr,
  219. ExplodedNode* Pred) {
  220. if (T->isLValueReferenceType()) {
  221. assert(!CastE->getType()->isLValueReferenceType());
  222. ExTy = getContext().getLValueReferenceType(ExTy);
  223. } else if (T->isRValueReferenceType()) {
  224. assert(!CastE->getType()->isRValueReferenceType());
  225. ExTy = getContext().getRValueReferenceType(ExTy);
  226. }
  227. // Delegate to SValBuilder to process.
  228. SVal OrigV = state->getSVal(Ex, LCtx);
  229. SVal V = svalBuilder.evalCast(OrigV, T, ExTy);
  230. // Negate the result if we're treating the boolean as a signed i1
  231. if (CastE->getCastKind() == CK_BooleanToSignedIntegral)
  232. V = evalMinus(V);
  233. state = state->BindExpr(CastE, LCtx, V);
  234. if (V.isUnknown() && !OrigV.isUnknown()) {
  235. state = escapeValues(state, OrigV, PSK_EscapeOther);
  236. }
  237. Bldr.generateNode(CastE, Pred, state);
  238. return state;
  239. }
  240. void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
  241. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  242. ExplodedNodeSet dstPreStmt;
  243. getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
  244. if (CastE->getCastKind() == CK_LValueToRValue ||
  245. CastE->getCastKind() == CK_LValueToRValueBitCast) {
  246. for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
  247. I!=E; ++I) {
  248. ExplodedNode *subExprNode = *I;
  249. ProgramStateRef state = subExprNode->getState();
  250. const LocationContext *LCtx = subExprNode->getLocationContext();
  251. evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
  252. }
  253. return;
  254. }
  255. // All other casts.
  256. QualType T = CastE->getType();
  257. QualType ExTy = Ex->getType();
  258. if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
  259. T = ExCast->getTypeAsWritten();
  260. StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
  261. for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
  262. I != E; ++I) {
  263. Pred = *I;
  264. ProgramStateRef state = Pred->getState();
  265. const LocationContext *LCtx = Pred->getLocationContext();
  266. switch (CastE->getCastKind()) {
  267. case CK_LValueToRValue:
  268. case CK_LValueToRValueBitCast:
  269. llvm_unreachable("LValueToRValue casts handled earlier.");
  270. case CK_ToVoid:
  271. continue;
  272. // The analyzer doesn't do anything special with these casts,
  273. // since it understands retain/release semantics already.
  274. case CK_ARCProduceObject:
  275. case CK_ARCConsumeObject:
  276. case CK_ARCReclaimReturnedObject:
  277. case CK_ARCExtendBlockObject: // Fall-through.
  278. case CK_CopyAndAutoreleaseBlockObject:
  279. // The analyser can ignore atomic casts for now, although some future
  280. // checkers may want to make certain that you're not modifying the same
  281. // value through atomic and nonatomic pointers.
  282. case CK_AtomicToNonAtomic:
  283. case CK_NonAtomicToAtomic:
  284. // True no-ops.
  285. case CK_NoOp:
  286. case CK_ConstructorConversion:
  287. case CK_UserDefinedConversion:
  288. case CK_FunctionToPointerDecay:
  289. case CK_BuiltinFnToFnPtr: {
  290. // Copy the SVal of Ex to CastE.
  291. ProgramStateRef state = Pred->getState();
  292. const LocationContext *LCtx = Pred->getLocationContext();
  293. SVal V = state->getSVal(Ex, LCtx);
  294. state = state->BindExpr(CastE, LCtx, V);
  295. Bldr.generateNode(CastE, Pred, state);
  296. continue;
  297. }
  298. case CK_MemberPointerToBoolean:
  299. case CK_PointerToBoolean: {
  300. SVal V = state->getSVal(Ex, LCtx);
  301. auto PTMSV = V.getAs<nonloc::PointerToMember>();
  302. if (PTMSV)
  303. V = svalBuilder.makeTruthVal(!PTMSV->isNullMemberPointer(), ExTy);
  304. if (V.isUndef() || PTMSV) {
  305. state = state->BindExpr(CastE, LCtx, V);
  306. Bldr.generateNode(CastE, Pred, state);
  307. continue;
  308. }
  309. // Explicitly proceed with default handler for this case cascade.
  310. state =
  311. handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
  312. continue;
  313. }
  314. case CK_Dependent:
  315. case CK_ArrayToPointerDecay:
  316. case CK_BitCast:
  317. case CK_AddressSpaceConversion:
  318. case CK_BooleanToSignedIntegral:
  319. case CK_IntegralToPointer:
  320. case CK_PointerToIntegral: {
  321. SVal V = state->getSVal(Ex, LCtx);
  322. if (V.getAs<nonloc::PointerToMember>()) {
  323. state = state->BindExpr(CastE, LCtx, UnknownVal());
  324. Bldr.generateNode(CastE, Pred, state);
  325. continue;
  326. }
  327. // Explicitly proceed with default handler for this case cascade.
  328. state =
  329. handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
  330. continue;
  331. }
  332. case CK_IntegralToBoolean:
  333. case CK_IntegralToFloating:
  334. case CK_FloatingToIntegral:
  335. case CK_FloatingToBoolean:
  336. case CK_FloatingCast:
  337. case CK_FloatingRealToComplex:
  338. case CK_FloatingComplexToReal:
  339. case CK_FloatingComplexToBoolean:
  340. case CK_FloatingComplexCast:
  341. case CK_FloatingComplexToIntegralComplex:
  342. case CK_IntegralRealToComplex:
  343. case CK_IntegralComplexToReal:
  344. case CK_IntegralComplexToBoolean:
  345. case CK_IntegralComplexCast:
  346. case CK_IntegralComplexToFloatingComplex:
  347. case CK_CPointerToObjCPointerCast:
  348. case CK_BlockPointerToObjCPointerCast:
  349. case CK_AnyPointerToBlockPointerCast:
  350. case CK_ObjCObjectLValueCast:
  351. case CK_ZeroToOCLOpaqueType:
  352. case CK_IntToOCLSampler:
  353. case CK_LValueBitCast:
  354. case CK_FloatingToFixedPoint:
  355. case CK_FixedPointToFloating:
  356. case CK_FixedPointCast:
  357. case CK_FixedPointToBoolean:
  358. case CK_FixedPointToIntegral:
  359. case CK_IntegralToFixedPoint: {
  360. state =
  361. handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
  362. continue;
  363. }
  364. case CK_IntegralCast: {
  365. // Delegate to SValBuilder to process.
  366. SVal V = state->getSVal(Ex, LCtx);
  367. if (AMgr.options.ShouldSupportSymbolicIntegerCasts)
  368. V = svalBuilder.evalCast(V, T, ExTy);
  369. else
  370. V = svalBuilder.evalIntegralCast(state, V, T, ExTy);
  371. state = state->BindExpr(CastE, LCtx, V);
  372. Bldr.generateNode(CastE, Pred, state);
  373. continue;
  374. }
  375. case CK_DerivedToBase:
  376. case CK_UncheckedDerivedToBase: {
  377. // For DerivedToBase cast, delegate to the store manager.
  378. SVal val = state->getSVal(Ex, LCtx);
  379. val = getStoreManager().evalDerivedToBase(val, CastE);
  380. state = state->BindExpr(CastE, LCtx, val);
  381. Bldr.generateNode(CastE, Pred, state);
  382. continue;
  383. }
  384. // Handle C++ dyn_cast.
  385. case CK_Dynamic: {
  386. SVal val = state->getSVal(Ex, LCtx);
  387. // Compute the type of the result.
  388. QualType resultType = CastE->getType();
  389. if (CastE->isGLValue())
  390. resultType = getContext().getPointerType(resultType);
  391. bool Failed = true;
  392. // Check if the value being cast does not evaluates to 0.
  393. if (!val.isZeroConstant())
  394. if (Optional<SVal> V =
  395. StateMgr.getStoreManager().evalBaseToDerived(val, T)) {
  396. val = *V;
  397. Failed = false;
  398. }
  399. if (Failed) {
  400. if (T->isReferenceType()) {
  401. // A bad_cast exception is thrown if input value is a reference.
  402. // Currently, we model this, by generating a sink.
  403. Bldr.generateSink(CastE, Pred, state);
  404. continue;
  405. } else {
  406. // If the cast fails on a pointer, bind to 0.
  407. state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
  408. }
  409. } else {
  410. // If we don't know if the cast succeeded, conjure a new symbol.
  411. if (val.isUnknown()) {
  412. DefinedOrUnknownSVal NewSym =
  413. svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
  414. currBldrCtx->blockCount());
  415. state = state->BindExpr(CastE, LCtx, NewSym);
  416. } else
  417. // Else, bind to the derived region value.
  418. state = state->BindExpr(CastE, LCtx, val);
  419. }
  420. Bldr.generateNode(CastE, Pred, state);
  421. continue;
  422. }
  423. case CK_BaseToDerived: {
  424. SVal val = state->getSVal(Ex, LCtx);
  425. QualType resultType = CastE->getType();
  426. if (CastE->isGLValue())
  427. resultType = getContext().getPointerType(resultType);
  428. if (!val.isConstant()) {
  429. Optional<SVal> V = getStoreManager().evalBaseToDerived(val, T);
  430. val = V ? *V : UnknownVal();
  431. }
  432. // Failed to cast or the result is unknown, fall back to conservative.
  433. if (val.isUnknown()) {
  434. val =
  435. svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
  436. currBldrCtx->blockCount());
  437. }
  438. state = state->BindExpr(CastE, LCtx, val);
  439. Bldr.generateNode(CastE, Pred, state);
  440. continue;
  441. }
  442. case CK_NullToPointer: {
  443. SVal V = svalBuilder.makeNull();
  444. state = state->BindExpr(CastE, LCtx, V);
  445. Bldr.generateNode(CastE, Pred, state);
  446. continue;
  447. }
  448. case CK_NullToMemberPointer: {
  449. SVal V = svalBuilder.getMemberPointer(nullptr);
  450. state = state->BindExpr(CastE, LCtx, V);
  451. Bldr.generateNode(CastE, Pred, state);
  452. continue;
  453. }
  454. case CK_DerivedToBaseMemberPointer:
  455. case CK_BaseToDerivedMemberPointer:
  456. case CK_ReinterpretMemberPointer: {
  457. SVal V = state->getSVal(Ex, LCtx);
  458. if (auto PTMSV = V.getAs<nonloc::PointerToMember>()) {
  459. SVal CastedPTMSV =
  460. svalBuilder.makePointerToMember(getBasicVals().accumCXXBase(
  461. CastE->path(), *PTMSV, CastE->getCastKind()));
  462. state = state->BindExpr(CastE, LCtx, CastedPTMSV);
  463. Bldr.generateNode(CastE, Pred, state);
  464. continue;
  465. }
  466. // Explicitly proceed with default handler for this case cascade.
  467. }
  468. LLVM_FALLTHROUGH;
  469. // Various C++ casts that are not handled yet.
  470. case CK_ToUnion:
  471. case CK_MatrixCast:
  472. case CK_VectorSplat: {
  473. QualType resultType = CastE->getType();
  474. if (CastE->isGLValue())
  475. resultType = getContext().getPointerType(resultType);
  476. SVal result = svalBuilder.conjureSymbolVal(
  477. /*symbolTag=*/nullptr, CastE, LCtx, resultType,
  478. currBldrCtx->blockCount());
  479. state = state->BindExpr(CastE, LCtx, result);
  480. Bldr.generateNode(CastE, Pred, state);
  481. continue;
  482. }
  483. }
  484. }
  485. }
  486. void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
  487. ExplodedNode *Pred,
  488. ExplodedNodeSet &Dst) {
  489. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  490. ProgramStateRef State = Pred->getState();
  491. const LocationContext *LCtx = Pred->getLocationContext();
  492. const Expr *Init = CL->getInitializer();
  493. SVal V = State->getSVal(CL->getInitializer(), LCtx);
  494. if (isa<CXXConstructExpr, CXXStdInitializerListExpr>(Init)) {
  495. // No work needed. Just pass the value up to this expression.
  496. } else {
  497. assert(isa<InitListExpr>(Init));
  498. Loc CLLoc = State->getLValue(CL, LCtx);
  499. State = State->bindLoc(CLLoc, V, LCtx);
  500. if (CL->isGLValue())
  501. V = CLLoc;
  502. }
  503. B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
  504. }
  505. void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
  506. ExplodedNodeSet &Dst) {
  507. if (isa<TypedefNameDecl>(*DS->decl_begin())) {
  508. // C99 6.7.7 "Any array size expressions associated with variable length
  509. // array declarators are evaluated each time the declaration of the typedef
  510. // name is reached in the order of execution."
  511. // The checkers should know about typedef to be able to handle VLA size
  512. // expressions.
  513. ExplodedNodeSet DstPre;
  514. getCheckerManager().runCheckersForPreStmt(DstPre, Pred, DS, *this);
  515. getCheckerManager().runCheckersForPostStmt(Dst, DstPre, DS, *this);
  516. return;
  517. }
  518. // Assumption: The CFG has one DeclStmt per Decl.
  519. const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
  520. if (!VD) {
  521. //TODO:AZ: remove explicit insertion after refactoring is done.
  522. Dst.insert(Pred);
  523. return;
  524. }
  525. // FIXME: all pre/post visits should eventually be handled by ::Visit().
  526. ExplodedNodeSet dstPreVisit;
  527. getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
  528. ExplodedNodeSet dstEvaluated;
  529. StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
  530. for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
  531. I!=E; ++I) {
  532. ExplodedNode *N = *I;
  533. ProgramStateRef state = N->getState();
  534. const LocationContext *LC = N->getLocationContext();
  535. // Decls without InitExpr are not initialized explicitly.
  536. if (const Expr *InitEx = VD->getInit()) {
  537. // Note in the state that the initialization has occurred.
  538. ExplodedNode *UpdatedN = N;
  539. SVal InitVal = state->getSVal(InitEx, LC);
  540. assert(DS->isSingleDecl());
  541. if (getObjectUnderConstruction(state, DS, LC)) {
  542. state = finishObjectConstruction(state, DS, LC);
  543. // We constructed the object directly in the variable.
  544. // No need to bind anything.
  545. B.generateNode(DS, UpdatedN, state);
  546. } else {
  547. // Recover some path-sensitivity if a scalar value evaluated to
  548. // UnknownVal.
  549. if (InitVal.isUnknown()) {
  550. QualType Ty = InitEx->getType();
  551. if (InitEx->isGLValue()) {
  552. Ty = getContext().getPointerType(Ty);
  553. }
  554. InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
  555. currBldrCtx->blockCount());
  556. }
  557. B.takeNodes(UpdatedN);
  558. ExplodedNodeSet Dst2;
  559. evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
  560. B.addNodes(Dst2);
  561. }
  562. }
  563. else {
  564. B.generateNode(DS, N, state);
  565. }
  566. }
  567. getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
  568. }
  569. void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
  570. ExplodedNodeSet &Dst) {
  571. // This method acts upon CFG elements for logical operators && and ||
  572. // and attaches the value (true or false) to them as expressions.
  573. // It doesn't produce any state splits.
  574. // If we made it that far, we're past the point when we modeled the short
  575. // circuit. It means that we should have precise knowledge about whether
  576. // we've short-circuited. If we did, we already know the value we need to
  577. // bind. If we didn't, the value of the RHS (casted to the boolean type)
  578. // is the answer.
  579. // Currently this method tries to figure out whether we've short-circuited
  580. // by looking at the ExplodedGraph. This method is imperfect because there
  581. // could inevitably have been merges that would have resulted in multiple
  582. // potential path traversal histories. We bail out when we fail.
  583. // Due to this ambiguity, a more reliable solution would have been to
  584. // track the short circuit operation history path-sensitively until
  585. // we evaluate the respective logical operator.
  586. assert(B->getOpcode() == BO_LAnd ||
  587. B->getOpcode() == BO_LOr);
  588. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  589. ProgramStateRef state = Pred->getState();
  590. if (B->getType()->isVectorType()) {
  591. // FIXME: We do not model vector arithmetic yet. When adding support for
  592. // that, note that the CFG-based reasoning below does not apply, because
  593. // logical operators on vectors are not short-circuit. Currently they are
  594. // modeled as short-circuit in Clang CFG but this is incorrect.
  595. // Do not set the value for the expression. It'd be UnknownVal by default.
  596. Bldr.generateNode(B, Pred, state);
  597. return;
  598. }
  599. ExplodedNode *N = Pred;
  600. while (!N->getLocation().getAs<BlockEntrance>()) {
  601. ProgramPoint P = N->getLocation();
  602. assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
  603. (void) P;
  604. if (N->pred_size() != 1) {
  605. // We failed to track back where we came from.
  606. Bldr.generateNode(B, Pred, state);
  607. return;
  608. }
  609. N = *N->pred_begin();
  610. }
  611. if (N->pred_size() != 1) {
  612. // We failed to track back where we came from.
  613. Bldr.generateNode(B, Pred, state);
  614. return;
  615. }
  616. N = *N->pred_begin();
  617. BlockEdge BE = N->getLocation().castAs<BlockEdge>();
  618. SVal X;
  619. // Determine the value of the expression by introspecting how we
  620. // got this location in the CFG. This requires looking at the previous
  621. // block we were in and what kind of control-flow transfer was involved.
  622. const CFGBlock *SrcBlock = BE.getSrc();
  623. // The only terminator (if there is one) that makes sense is a logical op.
  624. CFGTerminator T = SrcBlock->getTerminator();
  625. if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
  626. (void) Term;
  627. assert(Term->isLogicalOp());
  628. assert(SrcBlock->succ_size() == 2);
  629. // Did we take the true or false branch?
  630. unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
  631. X = svalBuilder.makeIntVal(constant, B->getType());
  632. }
  633. else {
  634. // If there is no terminator, by construction the last statement
  635. // in SrcBlock is the value of the enclosing expression.
  636. // However, we still need to constrain that value to be 0 or 1.
  637. assert(!SrcBlock->empty());
  638. CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
  639. const Expr *RHS = cast<Expr>(Elem.getStmt());
  640. SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
  641. if (RHSVal.isUndef()) {
  642. X = RHSVal;
  643. } else {
  644. // We evaluate "RHSVal != 0" expression which result in 0 if the value is
  645. // known to be false, 1 if the value is known to be true and a new symbol
  646. // when the assumption is unknown.
  647. nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType()));
  648. X = evalBinOp(N->getState(), BO_NE,
  649. svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()),
  650. Zero, B->getType());
  651. }
  652. }
  653. Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
  654. }
  655. void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
  656. ExplodedNode *Pred,
  657. ExplodedNodeSet &Dst) {
  658. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  659. ProgramStateRef state = Pred->getState();
  660. const LocationContext *LCtx = Pred->getLocationContext();
  661. QualType T = getContext().getCanonicalType(IE->getType());
  662. unsigned NumInitElements = IE->getNumInits();
  663. if (!IE->isGLValue() && !IE->isTransparent() &&
  664. (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
  665. T->isAnyComplexType())) {
  666. llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
  667. // Handle base case where the initializer has no elements.
  668. // e.g: static int* myArray[] = {};
  669. if (NumInitElements == 0) {
  670. SVal V = svalBuilder.makeCompoundVal(T, vals);
  671. B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
  672. return;
  673. }
  674. for (const Stmt *S : llvm::reverse(*IE)) {
  675. SVal V = state->getSVal(cast<Expr>(S), LCtx);
  676. vals = getBasicVals().prependSVal(V, vals);
  677. }
  678. B.generateNode(IE, Pred,
  679. state->BindExpr(IE, LCtx,
  680. svalBuilder.makeCompoundVal(T, vals)));
  681. return;
  682. }
  683. // Handle scalars: int{5} and int{} and GLvalues.
  684. // Note, if the InitListExpr is a GLvalue, it means that there is an address
  685. // representing it, so it must have a single init element.
  686. assert(NumInitElements <= 1);
  687. SVal V;
  688. if (NumInitElements == 0)
  689. V = getSValBuilder().makeZeroVal(T);
  690. else
  691. V = state->getSVal(IE->getInit(0), LCtx);
  692. B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
  693. }
  694. void ExprEngine::VisitGuardedExpr(const Expr *Ex,
  695. const Expr *L,
  696. const Expr *R,
  697. ExplodedNode *Pred,
  698. ExplodedNodeSet &Dst) {
  699. assert(L && R);
  700. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  701. ProgramStateRef state = Pred->getState();
  702. const LocationContext *LCtx = Pred->getLocationContext();
  703. const CFGBlock *SrcBlock = nullptr;
  704. // Find the predecessor block.
  705. ProgramStateRef SrcState = state;
  706. for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
  707. ProgramPoint PP = N->getLocation();
  708. if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
  709. // If the state N has multiple predecessors P, it means that successors
  710. // of P are all equivalent.
  711. // In turn, that means that all nodes at P are equivalent in terms
  712. // of observable behavior at N, and we can follow any of them.
  713. // FIXME: a more robust solution which does not walk up the tree.
  714. continue;
  715. }
  716. SrcBlock = PP.castAs<BlockEdge>().getSrc();
  717. SrcState = N->getState();
  718. break;
  719. }
  720. assert(SrcBlock && "missing function entry");
  721. // Find the last expression in the predecessor block. That is the
  722. // expression that is used for the value of the ternary expression.
  723. bool hasValue = false;
  724. SVal V;
  725. for (CFGElement CE : llvm::reverse(*SrcBlock)) {
  726. if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
  727. const Expr *ValEx = cast<Expr>(CS->getStmt());
  728. ValEx = ValEx->IgnoreParens();
  729. // For GNU extension '?:' operator, the left hand side will be an
  730. // OpaqueValueExpr, so get the underlying expression.
  731. if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
  732. L = OpaqueEx->getSourceExpr();
  733. // If the last expression in the predecessor block matches true or false
  734. // subexpression, get its the value.
  735. if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
  736. hasValue = true;
  737. V = SrcState->getSVal(ValEx, LCtx);
  738. }
  739. break;
  740. }
  741. }
  742. if (!hasValue)
  743. V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
  744. currBldrCtx->blockCount());
  745. // Generate a new node with the binding from the appropriate path.
  746. B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
  747. }
  748. void ExprEngine::
  749. VisitOffsetOfExpr(const OffsetOfExpr *OOE,
  750. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  751. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  752. Expr::EvalResult Result;
  753. if (OOE->EvaluateAsInt(Result, getContext())) {
  754. APSInt IV = Result.Val.getInt();
  755. assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
  756. assert(OOE->getType()->castAs<BuiltinType>()->isInteger());
  757. assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
  758. SVal X = svalBuilder.makeIntVal(IV);
  759. B.generateNode(OOE, Pred,
  760. Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
  761. X));
  762. }
  763. // FIXME: Handle the case where __builtin_offsetof is not a constant.
  764. }
  765. void ExprEngine::
  766. VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
  767. ExplodedNode *Pred,
  768. ExplodedNodeSet &Dst) {
  769. // FIXME: Prechecks eventually go in ::Visit().
  770. ExplodedNodeSet CheckedSet;
  771. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
  772. ExplodedNodeSet EvalSet;
  773. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  774. QualType T = Ex->getTypeOfArgument();
  775. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  776. I != E; ++I) {
  777. if (Ex->getKind() == UETT_SizeOf) {
  778. if (!T->isIncompleteType() && !T->isConstantSizeType()) {
  779. assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
  780. // FIXME: Add support for VLA type arguments and VLA expressions.
  781. // When that happens, we should probably refactor VLASizeChecker's code.
  782. continue;
  783. } else if (T->getAs<ObjCObjectType>()) {
  784. // Some code tries to take the sizeof an ObjCObjectType, relying that
  785. // the compiler has laid out its representation. Just report Unknown
  786. // for these.
  787. continue;
  788. }
  789. }
  790. APSInt Value = Ex->EvaluateKnownConstInt(getContext());
  791. CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
  792. ProgramStateRef state = (*I)->getState();
  793. state = state->BindExpr(Ex, (*I)->getLocationContext(),
  794. svalBuilder.makeIntVal(amt.getQuantity(),
  795. Ex->getType()));
  796. Bldr.generateNode(Ex, *I, state);
  797. }
  798. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
  799. }
  800. void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
  801. const UnaryOperator *U,
  802. StmtNodeBuilder &Bldr) {
  803. // FIXME: We can probably just have some magic in Environment::getSVal()
  804. // that propagates values, instead of creating a new node here.
  805. //
  806. // Unary "+" is a no-op, similar to a parentheses. We still have places
  807. // where it may be a block-level expression, so we need to
  808. // generate an extra node that just propagates the value of the
  809. // subexpression.
  810. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  811. ProgramStateRef state = (*I)->getState();
  812. const LocationContext *LCtx = (*I)->getLocationContext();
  813. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
  814. state->getSVal(Ex, LCtx)));
  815. }
  816. void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
  817. ExplodedNodeSet &Dst) {
  818. // FIXME: Prechecks eventually go in ::Visit().
  819. ExplodedNodeSet CheckedSet;
  820. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
  821. ExplodedNodeSet EvalSet;
  822. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  823. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  824. I != E; ++I) {
  825. switch (U->getOpcode()) {
  826. default: {
  827. Bldr.takeNodes(*I);
  828. ExplodedNodeSet Tmp;
  829. VisitIncrementDecrementOperator(U, *I, Tmp);
  830. Bldr.addNodes(Tmp);
  831. break;
  832. }
  833. case UO_Real: {
  834. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  835. // FIXME: We don't have complex SValues yet.
  836. if (Ex->getType()->isAnyComplexType()) {
  837. // Just report "Unknown."
  838. break;
  839. }
  840. // For all other types, UO_Real is an identity operation.
  841. assert (U->getType() == Ex->getType());
  842. ProgramStateRef state = (*I)->getState();
  843. const LocationContext *LCtx = (*I)->getLocationContext();
  844. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
  845. state->getSVal(Ex, LCtx)));
  846. break;
  847. }
  848. case UO_Imag: {
  849. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  850. // FIXME: We don't have complex SValues yet.
  851. if (Ex->getType()->isAnyComplexType()) {
  852. // Just report "Unknown."
  853. break;
  854. }
  855. // For all other types, UO_Imag returns 0.
  856. ProgramStateRef state = (*I)->getState();
  857. const LocationContext *LCtx = (*I)->getLocationContext();
  858. SVal X = svalBuilder.makeZeroVal(Ex->getType());
  859. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
  860. break;
  861. }
  862. case UO_AddrOf: {
  863. // Process pointer-to-member address operation.
  864. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  865. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) {
  866. const ValueDecl *VD = DRE->getDecl();
  867. if (isa<CXXMethodDecl, FieldDecl, IndirectFieldDecl>(VD)) {
  868. ProgramStateRef State = (*I)->getState();
  869. const LocationContext *LCtx = (*I)->getLocationContext();
  870. SVal SV = svalBuilder.getMemberPointer(cast<NamedDecl>(VD));
  871. Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
  872. break;
  873. }
  874. }
  875. // Explicitly proceed with default handler for this case cascade.
  876. handleUOExtension(I, U, Bldr);
  877. break;
  878. }
  879. case UO_Plus:
  880. assert(!U->isGLValue());
  881. LLVM_FALLTHROUGH;
  882. case UO_Deref:
  883. case UO_Extension: {
  884. handleUOExtension(I, U, Bldr);
  885. break;
  886. }
  887. case UO_LNot:
  888. case UO_Minus:
  889. case UO_Not: {
  890. assert (!U->isGLValue());
  891. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  892. ProgramStateRef state = (*I)->getState();
  893. const LocationContext *LCtx = (*I)->getLocationContext();
  894. // Get the value of the subexpression.
  895. SVal V = state->getSVal(Ex, LCtx);
  896. if (V.isUnknownOrUndef()) {
  897. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
  898. break;
  899. }
  900. switch (U->getOpcode()) {
  901. default:
  902. llvm_unreachable("Invalid Opcode.");
  903. case UO_Not:
  904. // FIXME: Do we need to handle promotions?
  905. state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
  906. break;
  907. case UO_Minus:
  908. // FIXME: Do we need to handle promotions?
  909. state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
  910. break;
  911. case UO_LNot:
  912. // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
  913. //
  914. // Note: technically we do "E == 0", but this is the same in the
  915. // transfer functions as "0 == E".
  916. SVal Result;
  917. if (Optional<Loc> LV = V.getAs<Loc>()) {
  918. Loc X = svalBuilder.makeNullWithType(Ex->getType());
  919. Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
  920. } else if (Ex->getType()->isFloatingType()) {
  921. // FIXME: handle floating point types.
  922. Result = UnknownVal();
  923. } else {
  924. nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
  925. Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
  926. U->getType());
  927. }
  928. state = state->BindExpr(U, LCtx, Result);
  929. break;
  930. }
  931. Bldr.generateNode(U, *I, state);
  932. break;
  933. }
  934. }
  935. }
  936. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
  937. }
  938. void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
  939. ExplodedNode *Pred,
  940. ExplodedNodeSet &Dst) {
  941. // Handle ++ and -- (both pre- and post-increment).
  942. assert (U->isIncrementDecrementOp());
  943. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  944. const LocationContext *LCtx = Pred->getLocationContext();
  945. ProgramStateRef state = Pred->getState();
  946. SVal loc = state->getSVal(Ex, LCtx);
  947. // Perform a load.
  948. ExplodedNodeSet Tmp;
  949. evalLoad(Tmp, U, Ex, Pred, state, loc);
  950. ExplodedNodeSet Dst2;
  951. StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
  952. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
  953. state = (*I)->getState();
  954. assert(LCtx == (*I)->getLocationContext());
  955. SVal V2_untested = state->getSVal(Ex, LCtx);
  956. // Propagate unknown and undefined values.
  957. if (V2_untested.isUnknownOrUndef()) {
  958. state = state->BindExpr(U, LCtx, V2_untested);
  959. // Perform the store, so that the uninitialized value detection happens.
  960. Bldr.takeNodes(*I);
  961. ExplodedNodeSet Dst3;
  962. evalStore(Dst3, U, Ex, *I, state, loc, V2_untested);
  963. Bldr.addNodes(Dst3);
  964. continue;
  965. }
  966. DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
  967. // Handle all other values.
  968. BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
  969. // If the UnaryOperator has non-location type, use its type to create the
  970. // constant value. If the UnaryOperator has location type, create the
  971. // constant with int type and pointer width.
  972. SVal RHS;
  973. SVal Result;
  974. if (U->getType()->isAnyPointerType())
  975. RHS = svalBuilder.makeArrayIndex(1);
  976. else if (U->getType()->isIntegralOrEnumerationType())
  977. RHS = svalBuilder.makeIntVal(1, U->getType());
  978. else
  979. RHS = UnknownVal();
  980. // The use of an operand of type bool with the ++ operators is deprecated
  981. // but valid until C++17. And if the operand of the ++ operator is of type
  982. // bool, it is set to true until C++17. Note that for '_Bool', it is also
  983. // set to true when it encounters ++ operator.
  984. if (U->getType()->isBooleanType() && U->isIncrementOp())
  985. Result = svalBuilder.makeTruthVal(true, U->getType());
  986. else
  987. Result = evalBinOp(state, Op, V2, RHS, U->getType());
  988. // Conjure a new symbol if necessary to recover precision.
  989. if (Result.isUnknown()){
  990. DefinedOrUnknownSVal SymVal =
  991. svalBuilder.conjureSymbolVal(nullptr, U, LCtx,
  992. currBldrCtx->blockCount());
  993. Result = SymVal;
  994. // If the value is a location, ++/-- should always preserve
  995. // non-nullness. Check if the original value was non-null, and if so
  996. // propagate that constraint.
  997. if (Loc::isLocType(U->getType())) {
  998. DefinedOrUnknownSVal Constraint =
  999. svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
  1000. if (!state->assume(Constraint, true)) {
  1001. // It isn't feasible for the original value to be null.
  1002. // Propagate this constraint.
  1003. Constraint = svalBuilder.evalEQ(state, SymVal,
  1004. svalBuilder.makeZeroVal(U->getType()));
  1005. state = state->assume(Constraint, false);
  1006. assert(state);
  1007. }
  1008. }
  1009. }
  1010. // Since the lvalue-to-rvalue conversion is explicit in the AST,
  1011. // we bind an l-value if the operator is prefix and an lvalue (in C++).
  1012. if (U->isGLValue())
  1013. state = state->BindExpr(U, LCtx, loc);
  1014. else
  1015. state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
  1016. // Perform the store.
  1017. Bldr.takeNodes(*I);
  1018. ExplodedNodeSet Dst3;
  1019. evalStore(Dst3, U, Ex, *I, state, loc, Result);
  1020. Bldr.addNodes(Dst3);
  1021. }
  1022. Dst.insert(Dst2);
  1023. }