ExprEngineC.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. #include <optional>
  17. using namespace clang;
  18. using namespace ento;
  19. using llvm::APSInt;
  20. /// Optionally conjure and return a symbol for offset when processing
  21. /// an expression \p Expression.
  22. /// If \p Other is a location, conjure a symbol for \p Symbol
  23. /// (offset) if it is unknown so that memory arithmetic always
  24. /// results in an ElementRegion.
  25. /// \p Count The number of times the current basic block was visited.
  26. static SVal conjureOffsetSymbolOnLocation(
  27. SVal Symbol, SVal Other, Expr* Expression, SValBuilder &svalBuilder,
  28. unsigned Count, const LocationContext *LCtx) {
  29. QualType Ty = Expression->getType();
  30. if (isa<Loc>(Other) && 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 && V.isValid())
  232. V = svalBuilder.evalMinus(V.castAs<NonLoc>());
  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 (isa<nonloc::PointerToMember>(V)) {
  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 (std::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,
  408. svalBuilder.makeNullWithType(resultType));
  409. }
  410. } else {
  411. // If we don't know if the cast succeeded, conjure a new symbol.
  412. if (val.isUnknown()) {
  413. DefinedOrUnknownSVal NewSym =
  414. svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
  415. currBldrCtx->blockCount());
  416. state = state->BindExpr(CastE, LCtx, NewSym);
  417. } else
  418. // Else, bind to the derived region value.
  419. state = state->BindExpr(CastE, LCtx, val);
  420. }
  421. Bldr.generateNode(CastE, Pred, state);
  422. continue;
  423. }
  424. case CK_BaseToDerived: {
  425. SVal val = state->getSVal(Ex, LCtx);
  426. QualType resultType = CastE->getType();
  427. if (CastE->isGLValue())
  428. resultType = getContext().getPointerType(resultType);
  429. if (!val.isConstant()) {
  430. std::optional<SVal> V = getStoreManager().evalBaseToDerived(val, T);
  431. val = V ? *V : UnknownVal();
  432. }
  433. // Failed to cast or the result is unknown, fall back to conservative.
  434. if (val.isUnknown()) {
  435. val =
  436. svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
  437. currBldrCtx->blockCount());
  438. }
  439. state = state->BindExpr(CastE, LCtx, val);
  440. Bldr.generateNode(CastE, Pred, state);
  441. continue;
  442. }
  443. case CK_NullToPointer: {
  444. SVal V = svalBuilder.makeNullWithType(CastE->getType());
  445. state = state->BindExpr(CastE, LCtx, V);
  446. Bldr.generateNode(CastE, Pred, state);
  447. continue;
  448. }
  449. case CK_NullToMemberPointer: {
  450. SVal V = svalBuilder.getMemberPointer(nullptr);
  451. state = state->BindExpr(CastE, LCtx, V);
  452. Bldr.generateNode(CastE, Pred, state);
  453. continue;
  454. }
  455. case CK_DerivedToBaseMemberPointer:
  456. case CK_BaseToDerivedMemberPointer:
  457. case CK_ReinterpretMemberPointer: {
  458. SVal V = state->getSVal(Ex, LCtx);
  459. if (auto PTMSV = V.getAs<nonloc::PointerToMember>()) {
  460. SVal CastedPTMSV =
  461. svalBuilder.makePointerToMember(getBasicVals().accumCXXBase(
  462. CastE->path(), *PTMSV, CastE->getCastKind()));
  463. state = state->BindExpr(CastE, LCtx, CastedPTMSV);
  464. Bldr.generateNode(CastE, Pred, state);
  465. continue;
  466. }
  467. // Explicitly proceed with default handler for this case cascade.
  468. }
  469. [[fallthrough]];
  470. // Various C++ casts that are not handled yet.
  471. case CK_ToUnion:
  472. case CK_MatrixCast:
  473. case CK_VectorSplat: {
  474. QualType resultType = CastE->getType();
  475. if (CastE->isGLValue())
  476. resultType = getContext().getPointerType(resultType);
  477. SVal result = svalBuilder.conjureSymbolVal(
  478. /*symbolTag=*/nullptr, CastE, LCtx, resultType,
  479. currBldrCtx->blockCount());
  480. state = state->BindExpr(CastE, LCtx, result);
  481. Bldr.generateNode(CastE, Pred, state);
  482. continue;
  483. }
  484. }
  485. }
  486. }
  487. void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
  488. ExplodedNode *Pred,
  489. ExplodedNodeSet &Dst) {
  490. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  491. ProgramStateRef State = Pred->getState();
  492. const LocationContext *LCtx = Pred->getLocationContext();
  493. const Expr *Init = CL->getInitializer();
  494. SVal V = State->getSVal(CL->getInitializer(), LCtx);
  495. if (isa<CXXConstructExpr, CXXStdInitializerListExpr>(Init)) {
  496. // No work needed. Just pass the value up to this expression.
  497. } else {
  498. assert(isa<InitListExpr>(Init));
  499. Loc CLLoc = State->getLValue(CL, LCtx);
  500. State = State->bindLoc(CLLoc, V, LCtx);
  501. if (CL->isGLValue())
  502. V = CLLoc;
  503. }
  504. B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
  505. }
  506. void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
  507. ExplodedNodeSet &Dst) {
  508. if (isa<TypedefNameDecl>(*DS->decl_begin())) {
  509. // C99 6.7.7 "Any array size expressions associated with variable length
  510. // array declarators are evaluated each time the declaration of the typedef
  511. // name is reached in the order of execution."
  512. // The checkers should know about typedef to be able to handle VLA size
  513. // expressions.
  514. ExplodedNodeSet DstPre;
  515. getCheckerManager().runCheckersForPreStmt(DstPre, Pred, DS, *this);
  516. getCheckerManager().runCheckersForPostStmt(Dst, DstPre, DS, *this);
  517. return;
  518. }
  519. // Assumption: The CFG has one DeclStmt per Decl.
  520. const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
  521. if (!VD) {
  522. //TODO:AZ: remove explicit insertion after refactoring is done.
  523. Dst.insert(Pred);
  524. return;
  525. }
  526. // FIXME: all pre/post visits should eventually be handled by ::Visit().
  527. ExplodedNodeSet dstPreVisit;
  528. getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
  529. ExplodedNodeSet dstEvaluated;
  530. StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
  531. for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
  532. I!=E; ++I) {
  533. ExplodedNode *N = *I;
  534. ProgramStateRef state = N->getState();
  535. const LocationContext *LC = N->getLocationContext();
  536. // Decls without InitExpr are not initialized explicitly.
  537. if (const Expr *InitEx = VD->getInit()) {
  538. // Note in the state that the initialization has occurred.
  539. ExplodedNode *UpdatedN = N;
  540. SVal InitVal = state->getSVal(InitEx, LC);
  541. assert(DS->isSingleDecl());
  542. if (getObjectUnderConstruction(state, DS, LC)) {
  543. state = finishObjectConstruction(state, DS, LC);
  544. // We constructed the object directly in the variable.
  545. // No need to bind anything.
  546. B.generateNode(DS, UpdatedN, state);
  547. } else {
  548. // Recover some path-sensitivity if a scalar value evaluated to
  549. // UnknownVal.
  550. if (InitVal.isUnknown()) {
  551. QualType Ty = InitEx->getType();
  552. if (InitEx->isGLValue()) {
  553. Ty = getContext().getPointerType(Ty);
  554. }
  555. InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
  556. currBldrCtx->blockCount());
  557. }
  558. B.takeNodes(UpdatedN);
  559. ExplodedNodeSet Dst2;
  560. evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
  561. B.addNodes(Dst2);
  562. }
  563. }
  564. else {
  565. B.generateNode(DS, N, state);
  566. }
  567. }
  568. getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
  569. }
  570. void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
  571. ExplodedNodeSet &Dst) {
  572. // This method acts upon CFG elements for logical operators && and ||
  573. // and attaches the value (true or false) to them as expressions.
  574. // It doesn't produce any state splits.
  575. // If we made it that far, we're past the point when we modeled the short
  576. // circuit. It means that we should have precise knowledge about whether
  577. // we've short-circuited. If we did, we already know the value we need to
  578. // bind. If we didn't, the value of the RHS (casted to the boolean type)
  579. // is the answer.
  580. // Currently this method tries to figure out whether we've short-circuited
  581. // by looking at the ExplodedGraph. This method is imperfect because there
  582. // could inevitably have been merges that would have resulted in multiple
  583. // potential path traversal histories. We bail out when we fail.
  584. // Due to this ambiguity, a more reliable solution would have been to
  585. // track the short circuit operation history path-sensitively until
  586. // we evaluate the respective logical operator.
  587. assert(B->getOpcode() == BO_LAnd ||
  588. B->getOpcode() == BO_LOr);
  589. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  590. ProgramStateRef state = Pred->getState();
  591. if (B->getType()->isVectorType()) {
  592. // FIXME: We do not model vector arithmetic yet. When adding support for
  593. // that, note that the CFG-based reasoning below does not apply, because
  594. // logical operators on vectors are not short-circuit. Currently they are
  595. // modeled as short-circuit in Clang CFG but this is incorrect.
  596. // Do not set the value for the expression. It'd be UnknownVal by default.
  597. Bldr.generateNode(B, Pred, state);
  598. return;
  599. }
  600. ExplodedNode *N = Pred;
  601. while (!N->getLocation().getAs<BlockEntrance>()) {
  602. ProgramPoint P = N->getLocation();
  603. assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
  604. (void) P;
  605. if (N->pred_size() != 1) {
  606. // We failed to track back where we came from.
  607. Bldr.generateNode(B, Pred, state);
  608. return;
  609. }
  610. N = *N->pred_begin();
  611. }
  612. if (N->pred_size() != 1) {
  613. // We failed to track back where we came from.
  614. Bldr.generateNode(B, Pred, state);
  615. return;
  616. }
  617. N = *N->pred_begin();
  618. BlockEdge BE = N->getLocation().castAs<BlockEdge>();
  619. SVal X;
  620. // Determine the value of the expression by introspecting how we
  621. // got this location in the CFG. This requires looking at the previous
  622. // block we were in and what kind of control-flow transfer was involved.
  623. const CFGBlock *SrcBlock = BE.getSrc();
  624. // The only terminator (if there is one) that makes sense is a logical op.
  625. CFGTerminator T = SrcBlock->getTerminator();
  626. if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
  627. (void) Term;
  628. assert(Term->isLogicalOp());
  629. assert(SrcBlock->succ_size() == 2);
  630. // Did we take the true or false branch?
  631. unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
  632. X = svalBuilder.makeIntVal(constant, B->getType());
  633. }
  634. else {
  635. // If there is no terminator, by construction the last statement
  636. // in SrcBlock is the value of the enclosing expression.
  637. // However, we still need to constrain that value to be 0 or 1.
  638. assert(!SrcBlock->empty());
  639. CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
  640. const Expr *RHS = cast<Expr>(Elem.getStmt());
  641. SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
  642. if (RHSVal.isUndef()) {
  643. X = RHSVal;
  644. } else {
  645. // We evaluate "RHSVal != 0" expression which result in 0 if the value is
  646. // known to be false, 1 if the value is known to be true and a new symbol
  647. // when the assumption is unknown.
  648. nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType()));
  649. X = evalBinOp(N->getState(), BO_NE,
  650. svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()),
  651. Zero, B->getType());
  652. }
  653. }
  654. Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
  655. }
  656. void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
  657. ExplodedNode *Pred,
  658. ExplodedNodeSet &Dst) {
  659. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  660. ProgramStateRef state = Pred->getState();
  661. const LocationContext *LCtx = Pred->getLocationContext();
  662. QualType T = getContext().getCanonicalType(IE->getType());
  663. unsigned NumInitElements = IE->getNumInits();
  664. if (!IE->isGLValue() && !IE->isTransparent() &&
  665. (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
  666. T->isAnyComplexType())) {
  667. llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
  668. // Handle base case where the initializer has no elements.
  669. // e.g: static int* myArray[] = {};
  670. if (NumInitElements == 0) {
  671. SVal V = svalBuilder.makeCompoundVal(T, vals);
  672. B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
  673. return;
  674. }
  675. for (const Stmt *S : llvm::reverse(*IE)) {
  676. SVal V = state->getSVal(cast<Expr>(S), LCtx);
  677. vals = getBasicVals().prependSVal(V, vals);
  678. }
  679. B.generateNode(IE, Pred,
  680. state->BindExpr(IE, LCtx,
  681. svalBuilder.makeCompoundVal(T, vals)));
  682. return;
  683. }
  684. // Handle scalars: int{5} and int{} and GLvalues.
  685. // Note, if the InitListExpr is a GLvalue, it means that there is an address
  686. // representing it, so it must have a single init element.
  687. assert(NumInitElements <= 1);
  688. SVal V;
  689. if (NumInitElements == 0)
  690. V = getSValBuilder().makeZeroVal(T);
  691. else
  692. V = state->getSVal(IE->getInit(0), LCtx);
  693. B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
  694. }
  695. void ExprEngine::VisitGuardedExpr(const Expr *Ex,
  696. const Expr *L,
  697. const Expr *R,
  698. ExplodedNode *Pred,
  699. ExplodedNodeSet &Dst) {
  700. assert(L && R);
  701. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  702. ProgramStateRef state = Pred->getState();
  703. const LocationContext *LCtx = Pred->getLocationContext();
  704. const CFGBlock *SrcBlock = nullptr;
  705. // Find the predecessor block.
  706. ProgramStateRef SrcState = state;
  707. for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
  708. ProgramPoint PP = N->getLocation();
  709. if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
  710. // If the state N has multiple predecessors P, it means that successors
  711. // of P are all equivalent.
  712. // In turn, that means that all nodes at P are equivalent in terms
  713. // of observable behavior at N, and we can follow any of them.
  714. // FIXME: a more robust solution which does not walk up the tree.
  715. continue;
  716. }
  717. SrcBlock = PP.castAs<BlockEdge>().getSrc();
  718. SrcState = N->getState();
  719. break;
  720. }
  721. assert(SrcBlock && "missing function entry");
  722. // Find the last expression in the predecessor block. That is the
  723. // expression that is used for the value of the ternary expression.
  724. bool hasValue = false;
  725. SVal V;
  726. for (CFGElement CE : llvm::reverse(*SrcBlock)) {
  727. if (std::optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
  728. const Expr *ValEx = cast<Expr>(CS->getStmt());
  729. ValEx = ValEx->IgnoreParens();
  730. // For GNU extension '?:' operator, the left hand side will be an
  731. // OpaqueValueExpr, so get the underlying expression.
  732. if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
  733. L = OpaqueEx->getSourceExpr();
  734. // If the last expression in the predecessor block matches true or false
  735. // subexpression, get its the value.
  736. if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
  737. hasValue = true;
  738. V = SrcState->getSVal(ValEx, LCtx);
  739. }
  740. break;
  741. }
  742. }
  743. if (!hasValue)
  744. V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
  745. currBldrCtx->blockCount());
  746. // Generate a new node with the binding from the appropriate path.
  747. B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
  748. }
  749. void ExprEngine::
  750. VisitOffsetOfExpr(const OffsetOfExpr *OOE,
  751. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  752. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  753. Expr::EvalResult Result;
  754. if (OOE->EvaluateAsInt(Result, getContext())) {
  755. APSInt IV = Result.Val.getInt();
  756. assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
  757. assert(OOE->getType()->castAs<BuiltinType>()->isInteger());
  758. assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
  759. SVal X = svalBuilder.makeIntVal(IV);
  760. B.generateNode(OOE, Pred,
  761. Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
  762. X));
  763. }
  764. // FIXME: Handle the case where __builtin_offsetof is not a constant.
  765. }
  766. void ExprEngine::
  767. VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
  768. ExplodedNode *Pred,
  769. ExplodedNodeSet &Dst) {
  770. // FIXME: Prechecks eventually go in ::Visit().
  771. ExplodedNodeSet CheckedSet;
  772. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
  773. ExplodedNodeSet EvalSet;
  774. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  775. QualType T = Ex->getTypeOfArgument();
  776. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  777. I != E; ++I) {
  778. if (Ex->getKind() == UETT_SizeOf) {
  779. if (!T->isIncompleteType() && !T->isConstantSizeType()) {
  780. assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
  781. // FIXME: Add support for VLA type arguments and VLA expressions.
  782. // When that happens, we should probably refactor VLASizeChecker's code.
  783. continue;
  784. } else if (T->getAs<ObjCObjectType>()) {
  785. // Some code tries to take the sizeof an ObjCObjectType, relying that
  786. // the compiler has laid out its representation. Just report Unknown
  787. // for these.
  788. continue;
  789. }
  790. }
  791. APSInt Value = Ex->EvaluateKnownConstInt(getContext());
  792. CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
  793. ProgramStateRef state = (*I)->getState();
  794. state = state->BindExpr(Ex, (*I)->getLocationContext(),
  795. svalBuilder.makeIntVal(amt.getQuantity(),
  796. Ex->getType()));
  797. Bldr.generateNode(Ex, *I, state);
  798. }
  799. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
  800. }
  801. void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
  802. const UnaryOperator *U,
  803. StmtNodeBuilder &Bldr) {
  804. // FIXME: We can probably just have some magic in Environment::getSVal()
  805. // that propagates values, instead of creating a new node here.
  806. //
  807. // Unary "+" is a no-op, similar to a parentheses. We still have places
  808. // where it may be a block-level expression, so we need to
  809. // generate an extra node that just propagates the value of the
  810. // subexpression.
  811. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  812. ProgramStateRef state = (*I)->getState();
  813. const LocationContext *LCtx = (*I)->getLocationContext();
  814. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
  815. state->getSVal(Ex, LCtx)));
  816. }
  817. void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
  818. ExplodedNodeSet &Dst) {
  819. // FIXME: Prechecks eventually go in ::Visit().
  820. ExplodedNodeSet CheckedSet;
  821. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
  822. ExplodedNodeSet EvalSet;
  823. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  824. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  825. I != E; ++I) {
  826. switch (U->getOpcode()) {
  827. default: {
  828. Bldr.takeNodes(*I);
  829. ExplodedNodeSet Tmp;
  830. VisitIncrementDecrementOperator(U, *I, Tmp);
  831. Bldr.addNodes(Tmp);
  832. break;
  833. }
  834. case UO_Real: {
  835. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  836. // FIXME: We don't have complex SValues yet.
  837. if (Ex->getType()->isAnyComplexType()) {
  838. // Just report "Unknown."
  839. break;
  840. }
  841. // For all other types, UO_Real is an identity operation.
  842. assert (U->getType() == Ex->getType());
  843. ProgramStateRef state = (*I)->getState();
  844. const LocationContext *LCtx = (*I)->getLocationContext();
  845. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
  846. state->getSVal(Ex, LCtx)));
  847. break;
  848. }
  849. case UO_Imag: {
  850. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  851. // FIXME: We don't have complex SValues yet.
  852. if (Ex->getType()->isAnyComplexType()) {
  853. // Just report "Unknown."
  854. break;
  855. }
  856. // For all other types, UO_Imag returns 0.
  857. ProgramStateRef state = (*I)->getState();
  858. const LocationContext *LCtx = (*I)->getLocationContext();
  859. SVal X = svalBuilder.makeZeroVal(Ex->getType());
  860. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
  861. break;
  862. }
  863. case UO_AddrOf: {
  864. // Process pointer-to-member address operation.
  865. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  866. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) {
  867. const ValueDecl *VD = DRE->getDecl();
  868. if (isa<CXXMethodDecl, FieldDecl, IndirectFieldDecl>(VD)) {
  869. ProgramStateRef State = (*I)->getState();
  870. const LocationContext *LCtx = (*I)->getLocationContext();
  871. SVal SV = svalBuilder.getMemberPointer(cast<NamedDecl>(VD));
  872. Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
  873. break;
  874. }
  875. }
  876. // Explicitly proceed with default handler for this case cascade.
  877. handleUOExtension(I, U, Bldr);
  878. break;
  879. }
  880. case UO_Plus:
  881. assert(!U->isGLValue());
  882. [[fallthrough]];
  883. case UO_Deref:
  884. case UO_Extension: {
  885. handleUOExtension(I, U, Bldr);
  886. break;
  887. }
  888. case UO_LNot:
  889. case UO_Minus:
  890. case UO_Not: {
  891. assert (!U->isGLValue());
  892. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  893. ProgramStateRef state = (*I)->getState();
  894. const LocationContext *LCtx = (*I)->getLocationContext();
  895. // Get the value of the subexpression.
  896. SVal V = state->getSVal(Ex, LCtx);
  897. if (V.isUnknownOrUndef()) {
  898. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
  899. break;
  900. }
  901. switch (U->getOpcode()) {
  902. default:
  903. llvm_unreachable("Invalid Opcode.");
  904. case UO_Not:
  905. // FIXME: Do we need to handle promotions?
  906. state = state->BindExpr(
  907. U, LCtx, svalBuilder.evalComplement(V.castAs<NonLoc>()));
  908. break;
  909. case UO_Minus:
  910. // FIXME: Do we need to handle promotions?
  911. state = state->BindExpr(U, LCtx,
  912. svalBuilder.evalMinus(V.castAs<NonLoc>()));
  913. break;
  914. case UO_LNot:
  915. // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
  916. //
  917. // Note: technically we do "E == 0", but this is the same in the
  918. // transfer functions as "0 == E".
  919. SVal Result;
  920. if (std::optional<Loc> LV = V.getAs<Loc>()) {
  921. Loc X = svalBuilder.makeNullWithType(Ex->getType());
  922. Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
  923. } else if (Ex->getType()->isFloatingType()) {
  924. // FIXME: handle floating point types.
  925. Result = UnknownVal();
  926. } else {
  927. nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
  928. Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X, U->getType());
  929. }
  930. state = state->BindExpr(U, LCtx, Result);
  931. break;
  932. }
  933. Bldr.generateNode(U, *I, state);
  934. break;
  935. }
  936. }
  937. }
  938. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
  939. }
  940. void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
  941. ExplodedNode *Pred,
  942. ExplodedNodeSet &Dst) {
  943. // Handle ++ and -- (both pre- and post-increment).
  944. assert (U->isIncrementDecrementOp());
  945. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  946. const LocationContext *LCtx = Pred->getLocationContext();
  947. ProgramStateRef state = Pred->getState();
  948. SVal loc = state->getSVal(Ex, LCtx);
  949. // Perform a load.
  950. ExplodedNodeSet Tmp;
  951. evalLoad(Tmp, U, Ex, Pred, state, loc);
  952. ExplodedNodeSet Dst2;
  953. StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
  954. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
  955. state = (*I)->getState();
  956. assert(LCtx == (*I)->getLocationContext());
  957. SVal V2_untested = state->getSVal(Ex, LCtx);
  958. // Propagate unknown and undefined values.
  959. if (V2_untested.isUnknownOrUndef()) {
  960. state = state->BindExpr(U, LCtx, V2_untested);
  961. // Perform the store, so that the uninitialized value detection happens.
  962. Bldr.takeNodes(*I);
  963. ExplodedNodeSet Dst3;
  964. evalStore(Dst3, U, Ex, *I, state, loc, V2_untested);
  965. Bldr.addNodes(Dst3);
  966. continue;
  967. }
  968. DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
  969. // Handle all other values.
  970. BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
  971. // If the UnaryOperator has non-location type, use its type to create the
  972. // constant value. If the UnaryOperator has location type, create the
  973. // constant with int type and pointer width.
  974. SVal RHS;
  975. SVal Result;
  976. if (U->getType()->isAnyPointerType())
  977. RHS = svalBuilder.makeArrayIndex(1);
  978. else if (U->getType()->isIntegralOrEnumerationType())
  979. RHS = svalBuilder.makeIntVal(1, U->getType());
  980. else
  981. RHS = UnknownVal();
  982. // The use of an operand of type bool with the ++ operators is deprecated
  983. // but valid until C++17. And if the operand of the ++ operator is of type
  984. // bool, it is set to true until C++17. Note that for '_Bool', it is also
  985. // set to true when it encounters ++ operator.
  986. if (U->getType()->isBooleanType() && U->isIncrementOp())
  987. Result = svalBuilder.makeTruthVal(true, U->getType());
  988. else
  989. Result = evalBinOp(state, Op, V2, RHS, U->getType());
  990. // Conjure a new symbol if necessary to recover precision.
  991. if (Result.isUnknown()){
  992. DefinedOrUnknownSVal SymVal =
  993. svalBuilder.conjureSymbolVal(nullptr, U, LCtx,
  994. currBldrCtx->blockCount());
  995. Result = SymVal;
  996. // If the value is a location, ++/-- should always preserve
  997. // non-nullness. Check if the original value was non-null, and if so
  998. // propagate that constraint.
  999. if (Loc::isLocType(U->getType())) {
  1000. DefinedOrUnknownSVal Constraint =
  1001. svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
  1002. if (!state->assume(Constraint, true)) {
  1003. // It isn't feasible for the original value to be null.
  1004. // Propagate this constraint.
  1005. Constraint = svalBuilder.evalEQ(state, SymVal,
  1006. svalBuilder.makeZeroVal(U->getType()));
  1007. state = state->assume(Constraint, false);
  1008. assert(state);
  1009. }
  1010. }
  1011. }
  1012. // Since the lvalue-to-rvalue conversion is explicit in the AST,
  1013. // we bind an l-value if the operator is prefix and an lvalue (in C++).
  1014. if (U->isGLValue())
  1015. state = state->BindExpr(U, LCtx, loc);
  1016. else
  1017. state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
  1018. // Perform the store.
  1019. Bldr.takeNodes(*I);
  1020. ExplodedNodeSet Dst3;
  1021. evalStore(Dst3, U, Ex, *I, state, loc, Result);
  1022. Bldr.addNodes(Dst3);
  1023. }
  1024. Dst.insert(Dst2);
  1025. }