ExprEngineC.cpp 33 KB

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