ExprEngine.cpp 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446
  1. //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- 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 a meta-engine for path-sensitive dataflow analysis that
  11. // is built on GREngine, but provides the boilerplate to execute transfer
  12. // functions and build the ExplodedGraph at the expression level.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #define DEBUG_TYPE "ExprEngine"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/ParentMap.h"
  19. #include "clang/AST/StmtCXX.h"
  20. #include "clang/AST/StmtObjC.h"
  21. #include "clang/Basic/Builtins.h"
  22. #include "clang/Basic/PrettyStackTrace.h"
  23. #include "clang/Basic/SourceManager.h"
  24. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  25. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  26. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  27. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  28. #include "llvm/ADT/ImmutableList.h"
  29. #include "llvm/ADT/Statistic.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #ifndef NDEBUG
  32. #include "llvm/Support/GraphWriter.h"
  33. #endif
  34. using namespace clang;
  35. using namespace ento;
  36. using llvm::APSInt;
  37. STATISTIC(NumRemoveDeadBindings,
  38. "The # of times RemoveDeadBindings is called");
  39. STATISTIC(NumMaxBlockCountReached,
  40. "The # of aborted paths due to reaching the maximum block count in "
  41. "a top level function");
  42. STATISTIC(NumMaxBlockCountReachedInInlined,
  43. "The # of aborted paths due to reaching the maximum block count in "
  44. "an inlined function");
  45. STATISTIC(NumTimesRetriedWithoutInlining,
  46. "The # of times we re-evaluated a call without inlining");
  47. //===----------------------------------------------------------------------===//
  48. // Engine construction and deletion.
  49. //===----------------------------------------------------------------------===//
  50. ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
  51. SetOfConstDecls *VisitedCalleesIn,
  52. FunctionSummariesTy *FS,
  53. InliningModes HowToInlineIn)
  54. : AMgr(mgr),
  55. AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
  56. Engine(*this, FS),
  57. G(Engine.getGraph()),
  58. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  59. mgr.getConstraintManagerCreator(), G.getAllocator(),
  60. this),
  61. SymMgr(StateMgr.getSymbolManager()),
  62. svalBuilder(StateMgr.getSValBuilder()),
  63. currStmtIdx(0), currBldrCtx(0),
  64. ObjCNoRet(mgr.getASTContext()),
  65. ObjCGCEnabled(gcEnabled), BR(mgr, *this),
  66. VisitedCallees(VisitedCalleesIn),
  67. HowToInline(HowToInlineIn)
  68. {
  69. unsigned TrimInterval = mgr.options.getGraphTrimInterval();
  70. if (TrimInterval != 0) {
  71. // Enable eager node reclaimation when constructing the ExplodedGraph.
  72. G.enableNodeReclamation(TrimInterval);
  73. }
  74. }
  75. ExprEngine::~ExprEngine() {
  76. BR.FlushReports();
  77. }
  78. //===----------------------------------------------------------------------===//
  79. // Utility methods.
  80. //===----------------------------------------------------------------------===//
  81. ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
  82. ProgramStateRef state = StateMgr.getInitialState(InitLoc);
  83. const Decl *D = InitLoc->getDecl();
  84. // Preconditions.
  85. // FIXME: It would be nice if we had a more general mechanism to add
  86. // such preconditions. Some day.
  87. do {
  88. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  89. // Precondition: the first argument of 'main' is an integer guaranteed
  90. // to be > 0.
  91. const IdentifierInfo *II = FD->getIdentifier();
  92. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  93. break;
  94. const ParmVarDecl *PD = FD->getParamDecl(0);
  95. QualType T = PD->getType();
  96. const BuiltinType *BT = dyn_cast<BuiltinType>(T);
  97. if (!BT || !BT->isInteger())
  98. break;
  99. const MemRegion *R = state->getRegion(PD, InitLoc);
  100. if (!R)
  101. break;
  102. SVal V = state->getSVal(loc::MemRegionVal(R));
  103. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  104. svalBuilder.makeZeroVal(T),
  105. getContext().IntTy);
  106. Optional<DefinedOrUnknownSVal> Constraint =
  107. Constraint_untested.getAs<DefinedOrUnknownSVal>();
  108. if (!Constraint)
  109. break;
  110. if (ProgramStateRef newState = state->assume(*Constraint, true))
  111. state = newState;
  112. }
  113. break;
  114. }
  115. while (0);
  116. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  117. // Precondition: 'self' is always non-null upon entry to an Objective-C
  118. // method.
  119. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  120. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  121. SVal V = state->getSVal(loc::MemRegionVal(R));
  122. if (Optional<Loc> LV = V.getAs<Loc>()) {
  123. // Assume that the pointer value in 'self' is non-null.
  124. state = state->assume(*LV, true);
  125. assert(state && "'self' cannot be null");
  126. }
  127. }
  128. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  129. if (!MD->isStatic()) {
  130. // Precondition: 'this' is always non-null upon entry to the
  131. // top-level function. This is our starting assumption for
  132. // analyzing an "open" program.
  133. const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
  134. if (SFC->getParent() == 0) {
  135. loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
  136. SVal V = state->getSVal(L);
  137. if (Optional<Loc> LV = V.getAs<Loc>()) {
  138. state = state->assume(*LV, true);
  139. assert(state && "'this' cannot be null");
  140. }
  141. }
  142. }
  143. }
  144. return state;
  145. }
  146. ProgramStateRef
  147. ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
  148. const LocationContext *LC,
  149. const Expr *Ex,
  150. const Expr *Result) {
  151. SVal V = State->getSVal(Ex, LC);
  152. if (!Result) {
  153. // If we don't have an explicit result expression, we're in "if needed"
  154. // mode. Only create a region if the current value is a NonLoc.
  155. if (!V.getAs<NonLoc>())
  156. return State;
  157. Result = Ex;
  158. } else {
  159. // We need to create a region no matter what. For sanity, make sure we don't
  160. // try to stuff a Loc into a non-pointer temporary region.
  161. assert(!V.getAs<Loc>() || Loc::isLocType(Result->getType()) ||
  162. Result->getType()->isMemberPointerType());
  163. }
  164. ProgramStateManager &StateMgr = State->getStateManager();
  165. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  166. StoreManager &StoreMgr = StateMgr.getStoreManager();
  167. // We need to be careful about treating a derived type's value as
  168. // bindings for a base type. Unless we're creating a temporary pointer region,
  169. // start by stripping and recording base casts.
  170. SmallVector<const CastExpr *, 4> Casts;
  171. const Expr *Inner = Ex->IgnoreParens();
  172. if (!Loc::isLocType(Result->getType())) {
  173. while (const CastExpr *CE = dyn_cast<CastExpr>(Inner)) {
  174. if (CE->getCastKind() == CK_DerivedToBase ||
  175. CE->getCastKind() == CK_UncheckedDerivedToBase)
  176. Casts.push_back(CE);
  177. else if (CE->getCastKind() != CK_NoOp)
  178. break;
  179. Inner = CE->getSubExpr()->IgnoreParens();
  180. }
  181. }
  182. // Create a temporary object region for the inner expression (which may have
  183. // a more derived type) and bind the value into it.
  184. const TypedValueRegion *TR = MRMgr.getCXXTempObjectRegion(Inner, LC);
  185. SVal Reg = loc::MemRegionVal(TR);
  186. if (V.isUnknown())
  187. V = getSValBuilder().conjureSymbolVal(Result, LC, TR->getValueType(),
  188. currBldrCtx->blockCount());
  189. State = State->bindLoc(Reg, V);
  190. // Re-apply the casts (from innermost to outermost) for type sanity.
  191. for (SmallVectorImpl<const CastExpr *>::reverse_iterator I = Casts.rbegin(),
  192. E = Casts.rend();
  193. I != E; ++I) {
  194. Reg = StoreMgr.evalDerivedToBase(Reg, *I);
  195. }
  196. State = State->BindExpr(Result, LC, Reg);
  197. return State;
  198. }
  199. //===----------------------------------------------------------------------===//
  200. // Top-level transfer function logic (Dispatcher).
  201. //===----------------------------------------------------------------------===//
  202. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  203. /// logic for handling assumptions on symbolic values.
  204. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  205. SVal cond, bool assumption) {
  206. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  207. }
  208. bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
  209. return getCheckerManager().wantsRegionChangeUpdate(state);
  210. }
  211. ProgramStateRef
  212. ExprEngine::processRegionChanges(ProgramStateRef state,
  213. const InvalidatedSymbols *invalidated,
  214. ArrayRef<const MemRegion *> Explicits,
  215. ArrayRef<const MemRegion *> Regions,
  216. const CallEvent *Call) {
  217. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  218. Explicits, Regions, Call);
  219. }
  220. void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
  221. const char *NL, const char *Sep) {
  222. getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
  223. }
  224. void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
  225. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  226. }
  227. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  228. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  229. currStmtIdx = StmtIdx;
  230. currBldrCtx = Ctx;
  231. switch (E.getKind()) {
  232. case CFGElement::Statement:
  233. ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
  234. return;
  235. case CFGElement::Initializer:
  236. ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred);
  237. return;
  238. case CFGElement::AutomaticObjectDtor:
  239. case CFGElement::BaseDtor:
  240. case CFGElement::MemberDtor:
  241. case CFGElement::TemporaryDtor:
  242. ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
  243. return;
  244. }
  245. currBldrCtx = 0;
  246. }
  247. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  248. const CFGStmt S,
  249. const ExplodedNode *Pred,
  250. const LocationContext *LC) {
  251. // Are we never purging state values?
  252. if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
  253. return false;
  254. // Is this the beginning of a basic block?
  255. if (Pred->getLocation().getAs<BlockEntrance>())
  256. return true;
  257. // Is this on a non-expression?
  258. if (!isa<Expr>(S.getStmt()))
  259. return true;
  260. // Run before processing a call.
  261. if (CallEvent::isCallStmt(S.getStmt()))
  262. return true;
  263. // Is this an expression that is consumed by another expression? If so,
  264. // postpone cleaning out the state.
  265. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  266. return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
  267. }
  268. void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
  269. const Stmt *ReferenceStmt,
  270. const LocationContext *LC,
  271. const Stmt *DiagnosticStmt,
  272. ProgramPoint::Kind K) {
  273. assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
  274. ReferenceStmt == 0 || isa<ReturnStmt>(ReferenceStmt))
  275. && "PostStmt is not generally supported by the SymbolReaper yet");
  276. assert(LC && "Must pass the current (or expiring) LocationContext");
  277. if (!DiagnosticStmt) {
  278. DiagnosticStmt = ReferenceStmt;
  279. assert(DiagnosticStmt && "Required for clearing a LocationContext");
  280. }
  281. NumRemoveDeadBindings++;
  282. ProgramStateRef CleanedState = Pred->getState();
  283. // LC is the location context being destroyed, but SymbolReaper wants a
  284. // location context that is still live. (If this is the top-level stack
  285. // frame, this will be null.)
  286. if (!ReferenceStmt) {
  287. assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
  288. "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
  289. LC = LC->getParent();
  290. }
  291. const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : 0;
  292. SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
  293. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  294. // Create a state in which dead bindings are removed from the environment
  295. // and the store. TODO: The function should just return new env and store,
  296. // not a new state.
  297. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  298. // Process any special transfer function for dead symbols.
  299. // A tag to track convenience transitions, which can be removed at cleanup.
  300. static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
  301. if (!SymReaper.hasDeadSymbols()) {
  302. // Generate a CleanedNode that has the environment and store cleaned
  303. // up. Since no symbols are dead, we can optimize and not clean out
  304. // the constraint manager.
  305. StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
  306. Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
  307. } else {
  308. // Call checkers with the non-cleaned state so that they could query the
  309. // values of the soon to be dead symbols.
  310. ExplodedNodeSet CheckedSet;
  311. getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
  312. DiagnosticStmt, *this, K);
  313. // For each node in CheckedSet, generate CleanedNodes that have the
  314. // environment, the store, and the constraints cleaned up but have the
  315. // user-supplied states as the predecessors.
  316. StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
  317. for (ExplodedNodeSet::const_iterator
  318. I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
  319. ProgramStateRef CheckerState = (*I)->getState();
  320. // The constraint manager has not been cleaned up yet, so clean up now.
  321. CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
  322. SymReaper);
  323. assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
  324. "Checkers are not allowed to modify the Environment as a part of "
  325. "checkDeadSymbols processing.");
  326. assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
  327. "Checkers are not allowed to modify the Store as a part of "
  328. "checkDeadSymbols processing.");
  329. // Create a state based on CleanedState with CheckerState GDM and
  330. // generate a transition to that state.
  331. ProgramStateRef CleanedCheckerSt =
  332. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  333. Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
  334. }
  335. }
  336. }
  337. void ExprEngine::ProcessStmt(const CFGStmt S,
  338. ExplodedNode *Pred) {
  339. // Reclaim any unnecessary nodes in the ExplodedGraph.
  340. G.reclaimRecentlyAllocatedNodes();
  341. const Stmt *currStmt = S.getStmt();
  342. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  343. currStmt->getLocStart(),
  344. "Error evaluating statement");
  345. // Remove dead bindings and symbols.
  346. ExplodedNodeSet CleanedStates;
  347. if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
  348. removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
  349. } else
  350. CleanedStates.Add(Pred);
  351. // Visit the statement.
  352. ExplodedNodeSet Dst;
  353. for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
  354. E = CleanedStates.end(); I != E; ++I) {
  355. ExplodedNodeSet DstI;
  356. // Visit the statement.
  357. Visit(currStmt, *I, DstI);
  358. Dst.insert(DstI);
  359. }
  360. // Enqueue the new nodes onto the work list.
  361. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  362. }
  363. void ExprEngine::ProcessInitializer(const CFGInitializer Init,
  364. ExplodedNode *Pred) {
  365. const CXXCtorInitializer *BMI = Init.getInitializer();
  366. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  367. BMI->getSourceLocation(),
  368. "Error evaluating initializer");
  369. // We don't clean up dead bindings here.
  370. const StackFrameContext *stackFrame =
  371. cast<StackFrameContext>(Pred->getLocationContext());
  372. const CXXConstructorDecl *decl =
  373. cast<CXXConstructorDecl>(stackFrame->getDecl());
  374. ProgramStateRef State = Pred->getState();
  375. SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
  376. ExplodedNodeSet Tmp(Pred);
  377. SVal FieldLoc;
  378. // Evaluate the initializer, if necessary
  379. if (BMI->isAnyMemberInitializer()) {
  380. // Constructors build the object directly in the field,
  381. // but non-objects must be copied in from the initializer.
  382. const Expr *Init = BMI->getInit()->IgnoreImplicit();
  383. if (!isa<CXXConstructExpr>(Init)) {
  384. const ValueDecl *Field;
  385. if (BMI->isIndirectMemberInitializer()) {
  386. Field = BMI->getIndirectMember();
  387. FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
  388. } else {
  389. Field = BMI->getMember();
  390. FieldLoc = State->getLValue(BMI->getMember(), thisVal);
  391. }
  392. SVal InitVal;
  393. if (BMI->getNumArrayIndices() > 0) {
  394. // Handle arrays of trivial type. We can represent this with a
  395. // primitive load/copy from the base array region.
  396. const ArraySubscriptExpr *ASE;
  397. while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
  398. Init = ASE->getBase()->IgnoreImplicit();
  399. SVal LValue = State->getSVal(Init, stackFrame);
  400. if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
  401. InitVal = State->getSVal(*LValueLoc);
  402. // If we fail to get the value for some reason, use a symbolic value.
  403. if (InitVal.isUnknownOrUndef()) {
  404. SValBuilder &SVB = getSValBuilder();
  405. InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
  406. Field->getType(),
  407. currBldrCtx->blockCount());
  408. }
  409. } else {
  410. InitVal = State->getSVal(BMI->getInit(), stackFrame);
  411. }
  412. assert(Tmp.size() == 1 && "have not generated any new nodes yet");
  413. assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
  414. Tmp.clear();
  415. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  416. evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
  417. }
  418. } else {
  419. assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
  420. // We already did all the work when visiting the CXXConstructExpr.
  421. }
  422. // Construct PostInitializer nodes whether the state changed or not,
  423. // so that the diagnostics don't get confused.
  424. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  425. ExplodedNodeSet Dst;
  426. NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  427. for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
  428. ExplodedNode *N = *I;
  429. Bldr.generateNode(PP, N->getState(), N);
  430. }
  431. // Enqueue the new nodes onto the work list.
  432. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  433. }
  434. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  435. ExplodedNode *Pred) {
  436. ExplodedNodeSet Dst;
  437. switch (D.getKind()) {
  438. case CFGElement::AutomaticObjectDtor:
  439. ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
  440. break;
  441. case CFGElement::BaseDtor:
  442. ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
  443. break;
  444. case CFGElement::MemberDtor:
  445. ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
  446. break;
  447. case CFGElement::TemporaryDtor:
  448. ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
  449. break;
  450. default:
  451. llvm_unreachable("Unexpected dtor kind.");
  452. }
  453. // Enqueue the new nodes onto the work list.
  454. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  455. }
  456. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
  457. ExplodedNode *Pred,
  458. ExplodedNodeSet &Dst) {
  459. const VarDecl *varDecl = Dtor.getVarDecl();
  460. QualType varType = varDecl->getType();
  461. ProgramStateRef state = Pred->getState();
  462. SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
  463. const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
  464. if (const ReferenceType *refType = varType->getAs<ReferenceType>()) {
  465. varType = refType->getPointeeType();
  466. Region = state->getSVal(Region).getAsRegion();
  467. }
  468. VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
  469. Pred, Dst);
  470. }
  471. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  472. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  473. const LocationContext *LCtx = Pred->getLocationContext();
  474. ProgramStateRef State = Pred->getState();
  475. const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  476. Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
  477. LCtx->getCurrentStackFrame());
  478. SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
  479. // Create the base object region.
  480. const CXXBaseSpecifier *Base = D.getBaseSpecifier();
  481. QualType BaseTy = Base->getType();
  482. SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
  483. Base->isVirtual());
  484. VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
  485. CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
  486. }
  487. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  488. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  489. const FieldDecl *Member = D.getFieldDecl();
  490. ProgramStateRef State = Pred->getState();
  491. const LocationContext *LCtx = Pred->getLocationContext();
  492. const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  493. Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
  494. LCtx->getCurrentStackFrame());
  495. SVal FieldVal =
  496. State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
  497. VisitCXXDestructor(Member->getType(),
  498. FieldVal.castAs<loc::MemRegionVal>().getRegion(),
  499. CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
  500. }
  501. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  502. ExplodedNode *Pred,
  503. ExplodedNodeSet &Dst) {}
  504. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  505. ExplodedNodeSet &DstTop) {
  506. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  507. S->getLocStart(),
  508. "Error evaluating statement");
  509. ExplodedNodeSet Dst;
  510. StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
  511. assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
  512. switch (S->getStmtClass()) {
  513. // C++ and ARC stuff we don't support yet.
  514. case Expr::ObjCIndirectCopyRestoreExprClass:
  515. case Stmt::CXXDefaultInitExprClass:
  516. case Stmt::CXXDependentScopeMemberExprClass:
  517. case Stmt::CXXPseudoDestructorExprClass:
  518. case Stmt::CXXTryStmtClass:
  519. case Stmt::CXXTypeidExprClass:
  520. case Stmt::CXXUuidofExprClass:
  521. case Stmt::MSPropertyRefExprClass:
  522. case Stmt::CXXUnresolvedConstructExprClass:
  523. case Stmt::DependentScopeDeclRefExprClass:
  524. case Stmt::UnaryTypeTraitExprClass:
  525. case Stmt::BinaryTypeTraitExprClass:
  526. case Stmt::TypeTraitExprClass:
  527. case Stmt::ArrayTypeTraitExprClass:
  528. case Stmt::ExpressionTraitExprClass:
  529. case Stmt::UnresolvedLookupExprClass:
  530. case Stmt::UnresolvedMemberExprClass:
  531. case Stmt::CXXNoexceptExprClass:
  532. case Stmt::PackExpansionExprClass:
  533. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  534. case Stmt::FunctionParmPackExprClass:
  535. case Stmt::SEHTryStmtClass:
  536. case Stmt::SEHExceptStmtClass:
  537. case Stmt::LambdaExprClass:
  538. case Stmt::SEHFinallyStmtClass: {
  539. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  540. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  541. break;
  542. }
  543. case Stmt::ParenExprClass:
  544. llvm_unreachable("ParenExprs already handled.");
  545. case Stmt::GenericSelectionExprClass:
  546. llvm_unreachable("GenericSelectionExprs already handled.");
  547. // Cases that should never be evaluated simply because they shouldn't
  548. // appear in the CFG.
  549. case Stmt::BreakStmtClass:
  550. case Stmt::CaseStmtClass:
  551. case Stmt::CompoundStmtClass:
  552. case Stmt::ContinueStmtClass:
  553. case Stmt::CXXForRangeStmtClass:
  554. case Stmt::DefaultStmtClass:
  555. case Stmt::DoStmtClass:
  556. case Stmt::ForStmtClass:
  557. case Stmt::GotoStmtClass:
  558. case Stmt::IfStmtClass:
  559. case Stmt::IndirectGotoStmtClass:
  560. case Stmt::LabelStmtClass:
  561. case Stmt::AttributedStmtClass:
  562. case Stmt::NoStmtClass:
  563. case Stmt::NullStmtClass:
  564. case Stmt::SwitchStmtClass:
  565. case Stmt::WhileStmtClass:
  566. case Expr::MSDependentExistsStmtClass:
  567. case Stmt::CapturedStmtClass:
  568. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  569. case Stmt::ObjCSubscriptRefExprClass:
  570. case Stmt::ObjCPropertyRefExprClass:
  571. llvm_unreachable("These are handled by PseudoObjectExpr");
  572. case Stmt::GNUNullExprClass: {
  573. // GNU __null is a pointer-width integer, not an actual pointer.
  574. ProgramStateRef state = Pred->getState();
  575. state = state->BindExpr(S, Pred->getLocationContext(),
  576. svalBuilder.makeIntValWithPtrWidth(0, false));
  577. Bldr.generateNode(S, Pred, state);
  578. break;
  579. }
  580. case Stmt::ObjCAtSynchronizedStmtClass:
  581. Bldr.takeNodes(Pred);
  582. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  583. Bldr.addNodes(Dst);
  584. break;
  585. case Stmt::ExprWithCleanupsClass:
  586. // Handled due to fully linearised CFG.
  587. break;
  588. // Cases not handled yet; but will handle some day.
  589. case Stmt::DesignatedInitExprClass:
  590. case Stmt::ExtVectorElementExprClass:
  591. case Stmt::ImaginaryLiteralClass:
  592. case Stmt::ObjCAtCatchStmtClass:
  593. case Stmt::ObjCAtFinallyStmtClass:
  594. case Stmt::ObjCAtTryStmtClass:
  595. case Stmt::ObjCAutoreleasePoolStmtClass:
  596. case Stmt::ObjCEncodeExprClass:
  597. case Stmt::ObjCIsaExprClass:
  598. case Stmt::ObjCProtocolExprClass:
  599. case Stmt::ObjCSelectorExprClass:
  600. case Stmt::ParenListExprClass:
  601. case Stmt::PredefinedExprClass:
  602. case Stmt::ShuffleVectorExprClass:
  603. case Stmt::VAArgExprClass:
  604. case Stmt::CUDAKernelCallExprClass:
  605. case Stmt::OpaqueValueExprClass:
  606. case Stmt::AsTypeExprClass:
  607. case Stmt::AtomicExprClass:
  608. // Fall through.
  609. // Cases we intentionally don't evaluate, since they don't need
  610. // to be explicitly evaluated.
  611. case Stmt::AddrLabelExprClass:
  612. case Stmt::IntegerLiteralClass:
  613. case Stmt::CharacterLiteralClass:
  614. case Stmt::ImplicitValueInitExprClass:
  615. case Stmt::CXXScalarValueInitExprClass:
  616. case Stmt::CXXBoolLiteralExprClass:
  617. case Stmt::ObjCBoolLiteralExprClass:
  618. case Stmt::FloatingLiteralClass:
  619. case Stmt::SizeOfPackExprClass:
  620. case Stmt::StringLiteralClass:
  621. case Stmt::ObjCStringLiteralClass:
  622. case Stmt::CXXBindTemporaryExprClass:
  623. case Stmt::SubstNonTypeTemplateParmExprClass:
  624. case Stmt::CXXNullPtrLiteralExprClass: {
  625. Bldr.takeNodes(Pred);
  626. ExplodedNodeSet preVisit;
  627. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  628. getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
  629. Bldr.addNodes(Dst);
  630. break;
  631. }
  632. case Stmt::CXXDefaultArgExprClass: {
  633. Bldr.takeNodes(Pred);
  634. ExplodedNodeSet PreVisit;
  635. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  636. ExplodedNodeSet Tmp;
  637. StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
  638. const LocationContext *LCtx = Pred->getLocationContext();
  639. const CXXDefaultArgExpr *DefaultE = cast<CXXDefaultArgExpr>(S);
  640. const Expr *ArgE = DefaultE->getExpr();
  641. Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
  642. if (!ConstantVal)
  643. ConstantVal = UnknownVal();
  644. for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
  645. I != E; ++I) {
  646. ProgramStateRef State = (*I)->getState();
  647. State = State->BindExpr(DefaultE, LCtx, *ConstantVal);
  648. if (DefaultE->isGLValue())
  649. State = createTemporaryRegionIfNeeded(State, LCtx, DefaultE,
  650. DefaultE);
  651. Bldr2.generateNode(S, *I, State);
  652. }
  653. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  654. Bldr.addNodes(Dst);
  655. break;
  656. }
  657. case Expr::ObjCArrayLiteralClass:
  658. case Expr::ObjCDictionaryLiteralClass:
  659. // FIXME: explicitly model with a region and the actual contents
  660. // of the container. For now, conjure a symbol.
  661. case Expr::ObjCBoxedExprClass: {
  662. Bldr.takeNodes(Pred);
  663. ExplodedNodeSet preVisit;
  664. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  665. ExplodedNodeSet Tmp;
  666. StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
  667. const Expr *Ex = cast<Expr>(S);
  668. QualType resultType = Ex->getType();
  669. for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
  670. it != et; ++it) {
  671. ExplodedNode *N = *it;
  672. const LocationContext *LCtx = N->getLocationContext();
  673. SVal result = svalBuilder.conjureSymbolVal(0, Ex, LCtx, resultType,
  674. currBldrCtx->blockCount());
  675. ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
  676. Bldr2.generateNode(S, N, state);
  677. }
  678. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  679. Bldr.addNodes(Dst);
  680. break;
  681. }
  682. case Stmt::ArraySubscriptExprClass:
  683. Bldr.takeNodes(Pred);
  684. VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  685. Bldr.addNodes(Dst);
  686. break;
  687. case Stmt::GCCAsmStmtClass:
  688. Bldr.takeNodes(Pred);
  689. VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
  690. Bldr.addNodes(Dst);
  691. break;
  692. case Stmt::MSAsmStmtClass:
  693. Bldr.takeNodes(Pred);
  694. VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
  695. Bldr.addNodes(Dst);
  696. break;
  697. case Stmt::BlockExprClass:
  698. Bldr.takeNodes(Pred);
  699. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  700. Bldr.addNodes(Dst);
  701. break;
  702. case Stmt::BinaryOperatorClass: {
  703. const BinaryOperator* B = cast<BinaryOperator>(S);
  704. if (B->isLogicalOp()) {
  705. Bldr.takeNodes(Pred);
  706. VisitLogicalExpr(B, Pred, Dst);
  707. Bldr.addNodes(Dst);
  708. break;
  709. }
  710. else if (B->getOpcode() == BO_Comma) {
  711. ProgramStateRef state = Pred->getState();
  712. Bldr.generateNode(B, Pred,
  713. state->BindExpr(B, Pred->getLocationContext(),
  714. state->getSVal(B->getRHS(),
  715. Pred->getLocationContext())));
  716. break;
  717. }
  718. Bldr.takeNodes(Pred);
  719. if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
  720. (B->isRelationalOp() || B->isEqualityOp())) {
  721. ExplodedNodeSet Tmp;
  722. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  723. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
  724. }
  725. else
  726. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  727. Bldr.addNodes(Dst);
  728. break;
  729. }
  730. case Stmt::CXXOperatorCallExprClass: {
  731. const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
  732. // For instance method operators, make sure the 'this' argument has a
  733. // valid region.
  734. const Decl *Callee = OCE->getCalleeDecl();
  735. if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
  736. if (MD->isInstance()) {
  737. ProgramStateRef State = Pred->getState();
  738. const LocationContext *LCtx = Pred->getLocationContext();
  739. ProgramStateRef NewState =
  740. createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
  741. if (NewState != State) {
  742. Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/0,
  743. ProgramPoint::PreStmtKind);
  744. // Did we cache out?
  745. if (!Pred)
  746. break;
  747. }
  748. }
  749. }
  750. // FALLTHROUGH
  751. }
  752. case Stmt::CallExprClass:
  753. case Stmt::CXXMemberCallExprClass:
  754. case Stmt::UserDefinedLiteralClass: {
  755. Bldr.takeNodes(Pred);
  756. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  757. Bldr.addNodes(Dst);
  758. break;
  759. }
  760. case Stmt::CXXCatchStmtClass: {
  761. Bldr.takeNodes(Pred);
  762. VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
  763. Bldr.addNodes(Dst);
  764. break;
  765. }
  766. case Stmt::CXXTemporaryObjectExprClass:
  767. case Stmt::CXXConstructExprClass: {
  768. Bldr.takeNodes(Pred);
  769. VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
  770. Bldr.addNodes(Dst);
  771. break;
  772. }
  773. case Stmt::CXXNewExprClass: {
  774. Bldr.takeNodes(Pred);
  775. ExplodedNodeSet PostVisit;
  776. VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
  777. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  778. Bldr.addNodes(Dst);
  779. break;
  780. }
  781. case Stmt::CXXDeleteExprClass: {
  782. Bldr.takeNodes(Pred);
  783. ExplodedNodeSet PreVisit;
  784. const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
  785. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  786. for (ExplodedNodeSet::iterator i = PreVisit.begin(),
  787. e = PreVisit.end(); i != e ; ++i)
  788. VisitCXXDeleteExpr(CDE, *i, Dst);
  789. Bldr.addNodes(Dst);
  790. break;
  791. }
  792. // FIXME: ChooseExpr is really a constant. We need to fix
  793. // the CFG do not model them as explicit control-flow.
  794. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  795. Bldr.takeNodes(Pred);
  796. const ChooseExpr *C = cast<ChooseExpr>(S);
  797. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  798. Bldr.addNodes(Dst);
  799. break;
  800. }
  801. case Stmt::CompoundAssignOperatorClass:
  802. Bldr.takeNodes(Pred);
  803. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  804. Bldr.addNodes(Dst);
  805. break;
  806. case Stmt::CompoundLiteralExprClass:
  807. Bldr.takeNodes(Pred);
  808. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  809. Bldr.addNodes(Dst);
  810. break;
  811. case Stmt::BinaryConditionalOperatorClass:
  812. case Stmt::ConditionalOperatorClass: { // '?' operator
  813. Bldr.takeNodes(Pred);
  814. const AbstractConditionalOperator *C
  815. = cast<AbstractConditionalOperator>(S);
  816. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  817. Bldr.addNodes(Dst);
  818. break;
  819. }
  820. case Stmt::CXXThisExprClass:
  821. Bldr.takeNodes(Pred);
  822. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  823. Bldr.addNodes(Dst);
  824. break;
  825. case Stmt::DeclRefExprClass: {
  826. Bldr.takeNodes(Pred);
  827. const DeclRefExpr *DE = cast<DeclRefExpr>(S);
  828. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  829. Bldr.addNodes(Dst);
  830. break;
  831. }
  832. case Stmt::DeclStmtClass:
  833. Bldr.takeNodes(Pred);
  834. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  835. Bldr.addNodes(Dst);
  836. break;
  837. case Stmt::ImplicitCastExprClass:
  838. case Stmt::CStyleCastExprClass:
  839. case Stmt::CXXStaticCastExprClass:
  840. case Stmt::CXXDynamicCastExprClass:
  841. case Stmt::CXXReinterpretCastExprClass:
  842. case Stmt::CXXConstCastExprClass:
  843. case Stmt::CXXFunctionalCastExprClass:
  844. case Stmt::ObjCBridgedCastExprClass: {
  845. Bldr.takeNodes(Pred);
  846. const CastExpr *C = cast<CastExpr>(S);
  847. // Handle the previsit checks.
  848. ExplodedNodeSet dstPrevisit;
  849. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
  850. // Handle the expression itself.
  851. ExplodedNodeSet dstExpr;
  852. for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
  853. e = dstPrevisit.end(); i != e ; ++i) {
  854. VisitCast(C, C->getSubExpr(), *i, dstExpr);
  855. }
  856. // Handle the postvisit checks.
  857. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  858. Bldr.addNodes(Dst);
  859. break;
  860. }
  861. case Expr::MaterializeTemporaryExprClass: {
  862. Bldr.takeNodes(Pred);
  863. const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
  864. CreateCXXTemporaryObject(MTE, Pred, Dst);
  865. Bldr.addNodes(Dst);
  866. break;
  867. }
  868. case Stmt::InitListExprClass:
  869. Bldr.takeNodes(Pred);
  870. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  871. Bldr.addNodes(Dst);
  872. break;
  873. case Stmt::MemberExprClass:
  874. Bldr.takeNodes(Pred);
  875. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  876. Bldr.addNodes(Dst);
  877. break;
  878. case Stmt::ObjCIvarRefExprClass:
  879. Bldr.takeNodes(Pred);
  880. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  881. Bldr.addNodes(Dst);
  882. break;
  883. case Stmt::ObjCForCollectionStmtClass:
  884. Bldr.takeNodes(Pred);
  885. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  886. Bldr.addNodes(Dst);
  887. break;
  888. case Stmt::ObjCMessageExprClass:
  889. Bldr.takeNodes(Pred);
  890. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  891. Bldr.addNodes(Dst);
  892. break;
  893. case Stmt::ObjCAtThrowStmtClass:
  894. case Stmt::CXXThrowExprClass:
  895. // FIXME: This is not complete. We basically treat @throw as
  896. // an abort.
  897. Bldr.generateSink(S, Pred, Pred->getState());
  898. break;
  899. case Stmt::ReturnStmtClass:
  900. Bldr.takeNodes(Pred);
  901. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  902. Bldr.addNodes(Dst);
  903. break;
  904. case Stmt::OffsetOfExprClass:
  905. Bldr.takeNodes(Pred);
  906. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
  907. Bldr.addNodes(Dst);
  908. break;
  909. case Stmt::UnaryExprOrTypeTraitExprClass:
  910. Bldr.takeNodes(Pred);
  911. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  912. Pred, Dst);
  913. Bldr.addNodes(Dst);
  914. break;
  915. case Stmt::StmtExprClass: {
  916. const StmtExpr *SE = cast<StmtExpr>(S);
  917. if (SE->getSubStmt()->body_empty()) {
  918. // Empty statement expression.
  919. assert(SE->getType() == getContext().VoidTy
  920. && "Empty statement expression must have void type.");
  921. break;
  922. }
  923. if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  924. ProgramStateRef state = Pred->getState();
  925. Bldr.generateNode(SE, Pred,
  926. state->BindExpr(SE, Pred->getLocationContext(),
  927. state->getSVal(LastExpr,
  928. Pred->getLocationContext())));
  929. }
  930. break;
  931. }
  932. case Stmt::UnaryOperatorClass: {
  933. Bldr.takeNodes(Pred);
  934. const UnaryOperator *U = cast<UnaryOperator>(S);
  935. if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
  936. ExplodedNodeSet Tmp;
  937. VisitUnaryOperator(U, Pred, Tmp);
  938. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
  939. }
  940. else
  941. VisitUnaryOperator(U, Pred, Dst);
  942. Bldr.addNodes(Dst);
  943. break;
  944. }
  945. case Stmt::PseudoObjectExprClass: {
  946. Bldr.takeNodes(Pred);
  947. ProgramStateRef state = Pred->getState();
  948. const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
  949. if (const Expr *Result = PE->getResultExpr()) {
  950. SVal V = state->getSVal(Result, Pred->getLocationContext());
  951. Bldr.generateNode(S, Pred,
  952. state->BindExpr(S, Pred->getLocationContext(), V));
  953. }
  954. else
  955. Bldr.generateNode(S, Pred,
  956. state->BindExpr(S, Pred->getLocationContext(),
  957. UnknownVal()));
  958. Bldr.addNodes(Dst);
  959. break;
  960. }
  961. }
  962. }
  963. bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
  964. const LocationContext *CalleeLC) {
  965. const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  966. const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
  967. assert(CalleeSF && CallerSF);
  968. ExplodedNode *BeforeProcessingCall = 0;
  969. const Stmt *CE = CalleeSF->getCallSite();
  970. // Find the first node before we started processing the call expression.
  971. while (N) {
  972. ProgramPoint L = N->getLocation();
  973. BeforeProcessingCall = N;
  974. N = N->pred_empty() ? NULL : *(N->pred_begin());
  975. // Skip the nodes corresponding to the inlined code.
  976. if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
  977. continue;
  978. // We reached the caller. Find the node right before we started
  979. // processing the call.
  980. if (L.isPurgeKind())
  981. continue;
  982. if (L.getAs<PreImplicitCall>())
  983. continue;
  984. if (L.getAs<CallEnter>())
  985. continue;
  986. if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
  987. if (SP->getStmt() == CE)
  988. continue;
  989. break;
  990. }
  991. if (!BeforeProcessingCall)
  992. return false;
  993. // TODO: Clean up the unneeded nodes.
  994. // Build an Epsilon node from which we will restart the analyzes.
  995. // Note that CE is permitted to be NULL!
  996. ProgramPoint NewNodeLoc =
  997. EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
  998. // Add the special flag to GDM to signal retrying with no inlining.
  999. // Note, changing the state ensures that we are not going to cache out.
  1000. ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
  1001. NewNodeState =
  1002. NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
  1003. // Make the new node a successor of BeforeProcessingCall.
  1004. bool IsNew = false;
  1005. ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
  1006. // We cached out at this point. Caching out is common due to us backtracking
  1007. // from the inlined function, which might spawn several paths.
  1008. if (!IsNew)
  1009. return true;
  1010. NewNode->addPredecessor(BeforeProcessingCall, G);
  1011. // Add the new node to the work list.
  1012. Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
  1013. CalleeSF->getIndex());
  1014. NumTimesRetriedWithoutInlining++;
  1015. return true;
  1016. }
  1017. /// Block entrance. (Update counters).
  1018. void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
  1019. NodeBuilderWithSinks &nodeBuilder,
  1020. ExplodedNode *Pred) {
  1021. // FIXME: Refactor this into a checker.
  1022. if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) {
  1023. static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
  1024. const ExplodedNode *Sink =
  1025. nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
  1026. // Check if we stopped at the top level function or not.
  1027. // Root node should have the location context of the top most function.
  1028. const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
  1029. const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  1030. const LocationContext *RootLC =
  1031. (*G.roots_begin())->getLocation().getLocationContext();
  1032. if (RootLC->getCurrentStackFrame() != CalleeSF) {
  1033. Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
  1034. // Re-run the call evaluation without inlining it, by storing the
  1035. // no-inlining policy in the state and enqueuing the new work item on
  1036. // the list. Replay should almost never fail. Use the stats to catch it
  1037. // if it does.
  1038. if ((!AMgr.options.NoRetryExhausted &&
  1039. replayWithoutInlining(Pred, CalleeLC)))
  1040. return;
  1041. NumMaxBlockCountReachedInInlined++;
  1042. } else
  1043. NumMaxBlockCountReached++;
  1044. // Make sink nodes as exhausted(for stats) only if retry failed.
  1045. Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
  1046. }
  1047. }
  1048. //===----------------------------------------------------------------------===//
  1049. // Branch processing.
  1050. //===----------------------------------------------------------------------===//
  1051. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  1052. /// to try to recover some path-sensitivity for casts of symbolic
  1053. /// integers that promote their values (which are currently not tracked well).
  1054. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  1055. // cast(s) did was sign-extend the original value.
  1056. static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
  1057. ProgramStateRef state,
  1058. const Stmt *Condition,
  1059. const LocationContext *LCtx,
  1060. ASTContext &Ctx) {
  1061. const Expr *Ex = dyn_cast<Expr>(Condition);
  1062. if (!Ex)
  1063. return UnknownVal();
  1064. uint64_t bits = 0;
  1065. bool bitsInit = false;
  1066. while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
  1067. QualType T = CE->getType();
  1068. if (!T->isIntegralOrEnumerationType())
  1069. return UnknownVal();
  1070. uint64_t newBits = Ctx.getTypeSize(T);
  1071. if (!bitsInit || newBits < bits) {
  1072. bitsInit = true;
  1073. bits = newBits;
  1074. }
  1075. Ex = CE->getSubExpr();
  1076. }
  1077. // We reached a non-cast. Is it a symbolic value?
  1078. QualType T = Ex->getType();
  1079. if (!bitsInit || !T->isIntegralOrEnumerationType() ||
  1080. Ctx.getTypeSize(T) > bits)
  1081. return UnknownVal();
  1082. return state->getSVal(Ex, LCtx);
  1083. }
  1084. static const Stmt *ResolveCondition(const Stmt *Condition,
  1085. const CFGBlock *B) {
  1086. if (const Expr *Ex = dyn_cast<Expr>(Condition))
  1087. Condition = Ex->IgnoreParens();
  1088. const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
  1089. if (!BO || !BO->isLogicalOp())
  1090. return Condition;
  1091. // For logical operations, we still have the case where some branches
  1092. // use the traditional "merge" approach and others sink the branch
  1093. // directly into the basic blocks representing the logical operation.
  1094. // We need to distinguish between those two cases here.
  1095. // The invariants are still shifting, but it is possible that the
  1096. // last element in a CFGBlock is not a CFGStmt. Look for the last
  1097. // CFGStmt as the value of the condition.
  1098. CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
  1099. for (; I != E; ++I) {
  1100. CFGElement Elem = *I;
  1101. Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
  1102. if (!CS)
  1103. continue;
  1104. if (CS->getStmt() != Condition)
  1105. break;
  1106. return Condition;
  1107. }
  1108. assert(I != E);
  1109. while (Condition) {
  1110. BO = dyn_cast<BinaryOperator>(Condition);
  1111. if (!BO || !BO->isLogicalOp())
  1112. return Condition;
  1113. Condition = BO->getRHS()->IgnoreParens();
  1114. }
  1115. llvm_unreachable("could not resolve condition");
  1116. }
  1117. void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
  1118. NodeBuilderContext& BldCtx,
  1119. ExplodedNode *Pred,
  1120. ExplodedNodeSet &Dst,
  1121. const CFGBlock *DstT,
  1122. const CFGBlock *DstF) {
  1123. currBldrCtx = &BldCtx;
  1124. // Check for NULL conditions; e.g. "for(;;)"
  1125. if (!Condition) {
  1126. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  1127. NullCondBldr.markInfeasible(false);
  1128. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  1129. return;
  1130. }
  1131. // Resolve the condition in the precense of nested '||' and '&&'.
  1132. if (const Expr *Ex = dyn_cast<Expr>(Condition))
  1133. Condition = Ex->IgnoreParens();
  1134. Condition = ResolveCondition(Condition, BldCtx.getBlock());
  1135. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1136. Condition->getLocStart(),
  1137. "Error evaluating branch");
  1138. ExplodedNodeSet CheckersOutSet;
  1139. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  1140. Pred, *this);
  1141. // We generated only sinks.
  1142. if (CheckersOutSet.empty())
  1143. return;
  1144. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  1145. for (NodeBuilder::iterator I = CheckersOutSet.begin(),
  1146. E = CheckersOutSet.end(); E != I; ++I) {
  1147. ExplodedNode *PredI = *I;
  1148. if (PredI->isSink())
  1149. continue;
  1150. ProgramStateRef PrevState = PredI->getState();
  1151. SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
  1152. if (X.isUnknownOrUndef()) {
  1153. // Give it a chance to recover from unknown.
  1154. if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
  1155. if (Ex->getType()->isIntegralOrEnumerationType()) {
  1156. // Try to recover some path-sensitivity. Right now casts of symbolic
  1157. // integers that promote their values are currently not tracked well.
  1158. // If 'Condition' is such an expression, try and recover the
  1159. // underlying value and use that instead.
  1160. SVal recovered = RecoverCastedSymbol(getStateManager(),
  1161. PrevState, Condition,
  1162. PredI->getLocationContext(),
  1163. getContext());
  1164. if (!recovered.isUnknown()) {
  1165. X = recovered;
  1166. }
  1167. }
  1168. }
  1169. }
  1170. // If the condition is still unknown, give up.
  1171. if (X.isUnknownOrUndef()) {
  1172. builder.generateNode(PrevState, true, PredI);
  1173. builder.generateNode(PrevState, false, PredI);
  1174. continue;
  1175. }
  1176. DefinedSVal V = X.castAs<DefinedSVal>();
  1177. ProgramStateRef StTrue, StFalse;
  1178. tie(StTrue, StFalse) = PrevState->assume(V);
  1179. // Process the true branch.
  1180. if (builder.isFeasible(true)) {
  1181. if (StTrue)
  1182. builder.generateNode(StTrue, true, PredI);
  1183. else
  1184. builder.markInfeasible(true);
  1185. }
  1186. // Process the false branch.
  1187. if (builder.isFeasible(false)) {
  1188. if (StFalse)
  1189. builder.generateNode(StFalse, false, PredI);
  1190. else
  1191. builder.markInfeasible(false);
  1192. }
  1193. }
  1194. currBldrCtx = 0;
  1195. }
  1196. /// The GDM component containing the set of global variables which have been
  1197. /// previously initialized with explicit initializers.
  1198. REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
  1199. llvm::ImmutableSet<const VarDecl *>)
  1200. void ExprEngine::processStaticInitializer(const DeclStmt *DS,
  1201. NodeBuilderContext &BuilderCtx,
  1202. ExplodedNode *Pred,
  1203. clang::ento::ExplodedNodeSet &Dst,
  1204. const CFGBlock *DstT,
  1205. const CFGBlock *DstF) {
  1206. currBldrCtx = &BuilderCtx;
  1207. const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  1208. ProgramStateRef state = Pred->getState();
  1209. bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
  1210. BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
  1211. if (!initHasRun) {
  1212. state = state->add<InitializedGlobalsSet>(VD);
  1213. }
  1214. builder.generateNode(state, initHasRun, Pred);
  1215. builder.markInfeasible(!initHasRun);
  1216. currBldrCtx = 0;
  1217. }
  1218. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  1219. /// nodes by processing the 'effects' of a computed goto jump.
  1220. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  1221. ProgramStateRef state = builder.getState();
  1222. SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
  1223. // Three possibilities:
  1224. //
  1225. // (1) We know the computed label.
  1226. // (2) The label is NULL (or some other constant), or Undefined.
  1227. // (3) We have no clue about the label. Dispatch to all targets.
  1228. //
  1229. typedef IndirectGotoNodeBuilder::iterator iterator;
  1230. if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
  1231. const LabelDecl *L = LV->getLabel();
  1232. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  1233. if (I.getLabel() == L) {
  1234. builder.generateNode(I, state);
  1235. return;
  1236. }
  1237. }
  1238. llvm_unreachable("No block with label.");
  1239. }
  1240. if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
  1241. // Dispatch to the first target and mark it as a sink.
  1242. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  1243. // FIXME: add checker visit.
  1244. // UndefBranches.insert(N);
  1245. return;
  1246. }
  1247. // This is really a catch-all. We don't support symbolics yet.
  1248. // FIXME: Implement dispatch for symbolic pointers.
  1249. for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
  1250. builder.generateNode(I, state);
  1251. }
  1252. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  1253. /// nodes when the control reaches the end of a function.
  1254. void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
  1255. ExplodedNode *Pred) {
  1256. StateMgr.EndPath(Pred->getState());
  1257. ExplodedNodeSet Dst;
  1258. if (Pred->getLocationContext()->inTopFrame()) {
  1259. // Remove dead symbols.
  1260. ExplodedNodeSet AfterRemovedDead;
  1261. removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
  1262. // Notify checkers.
  1263. for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
  1264. E = AfterRemovedDead.end(); I != E; ++I) {
  1265. getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
  1266. }
  1267. } else {
  1268. getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
  1269. }
  1270. Engine.enqueueEndOfFunction(Dst);
  1271. }
  1272. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  1273. /// nodes by processing the 'effects' of a switch statement.
  1274. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  1275. typedef SwitchNodeBuilder::iterator iterator;
  1276. ProgramStateRef state = builder.getState();
  1277. const Expr *CondE = builder.getCondition();
  1278. SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
  1279. if (CondV_untested.isUndef()) {
  1280. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  1281. // FIXME: add checker
  1282. //UndefBranches.insert(N);
  1283. return;
  1284. }
  1285. DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
  1286. ProgramStateRef DefaultSt = state;
  1287. iterator I = builder.begin(), EI = builder.end();
  1288. bool defaultIsFeasible = I == EI;
  1289. for ( ; I != EI; ++I) {
  1290. // Successor may be pruned out during CFG construction.
  1291. if (!I.getBlock())
  1292. continue;
  1293. const CaseStmt *Case = I.getCase();
  1294. // Evaluate the LHS of the case value.
  1295. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
  1296. assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
  1297. // Get the RHS of the case, if it exists.
  1298. llvm::APSInt V2;
  1299. if (const Expr *E = Case->getRHS())
  1300. V2 = E->EvaluateKnownConstInt(getContext());
  1301. else
  1302. V2 = V1;
  1303. // FIXME: Eventually we should replace the logic below with a range
  1304. // comparison, rather than concretize the values within the range.
  1305. // This should be easy once we have "ranges" for NonLVals.
  1306. do {
  1307. nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
  1308. DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
  1309. CondV, CaseVal);
  1310. // Now "assume" that the case matches.
  1311. if (ProgramStateRef stateNew = state->assume(Res, true)) {
  1312. builder.generateCaseStmtNode(I, stateNew);
  1313. // If CondV evaluates to a constant, then we know that this
  1314. // is the *only* case that we can take, so stop evaluating the
  1315. // others.
  1316. if (CondV.getAs<nonloc::ConcreteInt>())
  1317. return;
  1318. }
  1319. // Now "assume" that the case doesn't match. Add this state
  1320. // to the default state (if it is feasible).
  1321. if (DefaultSt) {
  1322. if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
  1323. defaultIsFeasible = true;
  1324. DefaultSt = stateNew;
  1325. }
  1326. else {
  1327. defaultIsFeasible = false;
  1328. DefaultSt = NULL;
  1329. }
  1330. }
  1331. // Concretize the next value in the range.
  1332. if (V1 == V2)
  1333. break;
  1334. ++V1;
  1335. assert (V1 <= V2);
  1336. } while (true);
  1337. }
  1338. if (!defaultIsFeasible)
  1339. return;
  1340. // If we have switch(enum value), the default branch is not
  1341. // feasible if all of the enum constants not covered by 'case:' statements
  1342. // are not feasible values for the switch condition.
  1343. //
  1344. // Note that this isn't as accurate as it could be. Even if there isn't
  1345. // a case for a particular enum value as long as that enum value isn't
  1346. // feasible then it shouldn't be considered for making 'default:' reachable.
  1347. const SwitchStmt *SS = builder.getSwitch();
  1348. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  1349. if (CondExpr->getType()->getAs<EnumType>()) {
  1350. if (SS->isAllEnumCasesCovered())
  1351. return;
  1352. }
  1353. builder.generateDefaultCaseNode(DefaultSt);
  1354. }
  1355. //===----------------------------------------------------------------------===//
  1356. // Transfer functions: Loads and stores.
  1357. //===----------------------------------------------------------------------===//
  1358. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  1359. ExplodedNode *Pred,
  1360. ExplodedNodeSet &Dst) {
  1361. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  1362. ProgramStateRef state = Pred->getState();
  1363. const LocationContext *LCtx = Pred->getLocationContext();
  1364. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1365. assert(Ex->isGLValue());
  1366. SVal V = state->getLValue(VD, Pred->getLocationContext());
  1367. // For references, the 'lvalue' is the pointer address stored in the
  1368. // reference region.
  1369. if (VD->getType()->isReferenceType()) {
  1370. if (const MemRegion *R = V.getAsRegion())
  1371. V = state->getSVal(R);
  1372. else
  1373. V = UnknownVal();
  1374. }
  1375. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
  1376. ProgramPoint::PostLValueKind);
  1377. return;
  1378. }
  1379. if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  1380. assert(!Ex->isGLValue());
  1381. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  1382. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
  1383. return;
  1384. }
  1385. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1386. SVal V = svalBuilder.getFunctionPointer(FD);
  1387. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
  1388. ProgramPoint::PostLValueKind);
  1389. return;
  1390. }
  1391. if (isa<FieldDecl>(D)) {
  1392. // FIXME: Compute lvalue of field pointers-to-member.
  1393. // Right now we just use a non-null void pointer, so that it gives proper
  1394. // results in boolean contexts.
  1395. SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
  1396. currBldrCtx->blockCount());
  1397. state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
  1398. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
  1399. ProgramPoint::PostLValueKind);
  1400. return;
  1401. }
  1402. llvm_unreachable("Support for this Decl not implemented.");
  1403. }
  1404. /// VisitArraySubscriptExpr - Transfer function for array accesses
  1405. void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
  1406. ExplodedNode *Pred,
  1407. ExplodedNodeSet &Dst){
  1408. const Expr *Base = A->getBase()->IgnoreParens();
  1409. const Expr *Idx = A->getIdx()->IgnoreParens();
  1410. ExplodedNodeSet checkerPreStmt;
  1411. getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
  1412. StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
  1413. for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
  1414. ei = checkerPreStmt.end(); it != ei; ++it) {
  1415. const LocationContext *LCtx = (*it)->getLocationContext();
  1416. ProgramStateRef state = (*it)->getState();
  1417. SVal V = state->getLValue(A->getType(),
  1418. state->getSVal(Idx, LCtx),
  1419. state->getSVal(Base, LCtx));
  1420. assert(A->isGLValue());
  1421. Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), 0,
  1422. ProgramPoint::PostLValueKind);
  1423. }
  1424. }
  1425. /// VisitMemberExpr - Transfer function for member expressions.
  1426. void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
  1427. ExplodedNodeSet &TopDst) {
  1428. StmtNodeBuilder Bldr(Pred, TopDst, *currBldrCtx);
  1429. ExplodedNodeSet Dst;
  1430. ValueDecl *Member = M->getMemberDecl();
  1431. // Handle static member variables and enum constants accessed via
  1432. // member syntax.
  1433. if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
  1434. Bldr.takeNodes(Pred);
  1435. VisitCommonDeclRefExpr(M, Member, Pred, Dst);
  1436. Bldr.addNodes(Dst);
  1437. return;
  1438. }
  1439. ProgramStateRef state = Pred->getState();
  1440. const LocationContext *LCtx = Pred->getLocationContext();
  1441. Expr *BaseExpr = M->getBase();
  1442. // Handle C++ method calls.
  1443. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
  1444. if (MD->isInstance())
  1445. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  1446. SVal MDVal = svalBuilder.getFunctionPointer(MD);
  1447. state = state->BindExpr(M, LCtx, MDVal);
  1448. Bldr.generateNode(M, Pred, state);
  1449. return;
  1450. }
  1451. // Handle regular struct fields / member variables.
  1452. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  1453. SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
  1454. FieldDecl *field = cast<FieldDecl>(Member);
  1455. SVal L = state->getLValue(field, baseExprVal);
  1456. if (M->isGLValue()) {
  1457. if (field->getType()->isReferenceType()) {
  1458. if (const MemRegion *R = L.getAsRegion())
  1459. L = state->getSVal(R);
  1460. else
  1461. L = UnknownVal();
  1462. }
  1463. Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), 0,
  1464. ProgramPoint::PostLValueKind);
  1465. } else {
  1466. Bldr.takeNodes(Pred);
  1467. evalLoad(Dst, M, M, Pred, state, L);
  1468. Bldr.addNodes(Dst);
  1469. }
  1470. }
  1471. namespace {
  1472. class CollectReachableSymbolsCallback : public SymbolVisitor {
  1473. InvalidatedSymbols Symbols;
  1474. public:
  1475. CollectReachableSymbolsCallback(ProgramStateRef State) {}
  1476. const InvalidatedSymbols &getSymbols() const { return Symbols; }
  1477. bool VisitSymbol(SymbolRef Sym) {
  1478. Symbols.insert(Sym);
  1479. return true;
  1480. }
  1481. };
  1482. } // end anonymous namespace
  1483. // A value escapes in three possible cases:
  1484. // (1) We are binding to something that is not a memory region.
  1485. // (2) We are binding to a MemrRegion that does not have stack storage.
  1486. // (3) We are binding to a MemRegion with stack storage that the store
  1487. // does not understand.
  1488. ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
  1489. SVal Loc, SVal Val) {
  1490. // Are we storing to something that causes the value to "escape"?
  1491. bool escapes = true;
  1492. // TODO: Move to StoreManager.
  1493. if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
  1494. escapes = !regionLoc->getRegion()->hasStackStorage();
  1495. if (!escapes) {
  1496. // To test (3), generate a new state with the binding added. If it is
  1497. // the same state, then it escapes (since the store cannot represent
  1498. // the binding).
  1499. // Do this only if we know that the store is not supposed to generate the
  1500. // same state.
  1501. SVal StoredVal = State->getSVal(regionLoc->getRegion());
  1502. if (StoredVal != Val)
  1503. escapes = (State == (State->bindLoc(*regionLoc, Val)));
  1504. }
  1505. }
  1506. // If our store can represent the binding and we aren't storing to something
  1507. // that doesn't have local storage then just return and have the simulation
  1508. // state continue as is.
  1509. if (!escapes)
  1510. return State;
  1511. // Otherwise, find all symbols referenced by 'val' that we are tracking
  1512. // and stop tracking them.
  1513. CollectReachableSymbolsCallback Scanner =
  1514. State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
  1515. const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
  1516. State = getCheckerManager().runCheckersForPointerEscape(State,
  1517. EscapedSymbols,
  1518. /*CallEvent*/ 0,
  1519. PSK_EscapeOnBind);
  1520. return State;
  1521. }
  1522. ProgramStateRef
  1523. ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
  1524. const InvalidatedSymbols *Invalidated,
  1525. ArrayRef<const MemRegion *> ExplicitRegions,
  1526. ArrayRef<const MemRegion *> Regions,
  1527. const CallEvent *Call,
  1528. bool IsConst) {
  1529. if (!Invalidated || Invalidated->empty())
  1530. return State;
  1531. if (!Call)
  1532. return getCheckerManager().runCheckersForPointerEscape(State,
  1533. *Invalidated,
  1534. 0,
  1535. PSK_EscapeOther,
  1536. IsConst);
  1537. // Note: Due to current limitations of RegionStore, we only process the top
  1538. // level const pointers correctly. The lower level const pointers are
  1539. // currently treated as non-const.
  1540. if (IsConst)
  1541. return getCheckerManager().runCheckersForPointerEscape(State,
  1542. *Invalidated,
  1543. Call,
  1544. PSK_DirectEscapeOnCall,
  1545. true);
  1546. // If the symbols were invalidated by a call, we want to find out which ones
  1547. // were invalidated directly due to being arguments to the call.
  1548. InvalidatedSymbols SymbolsDirectlyInvalidated;
  1549. for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
  1550. E = ExplicitRegions.end(); I != E; ++I) {
  1551. if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
  1552. SymbolsDirectlyInvalidated.insert(R->getSymbol());
  1553. }
  1554. InvalidatedSymbols SymbolsIndirectlyInvalidated;
  1555. for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
  1556. E = Invalidated->end(); I!=E; ++I) {
  1557. SymbolRef sym = *I;
  1558. if (SymbolsDirectlyInvalidated.count(sym))
  1559. continue;
  1560. SymbolsIndirectlyInvalidated.insert(sym);
  1561. }
  1562. if (!SymbolsDirectlyInvalidated.empty())
  1563. State = getCheckerManager().runCheckersForPointerEscape(State,
  1564. SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall);
  1565. // Notify about the symbols that get indirectly invalidated by the call.
  1566. if (!SymbolsIndirectlyInvalidated.empty())
  1567. State = getCheckerManager().runCheckersForPointerEscape(State,
  1568. SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall);
  1569. return State;
  1570. }
  1571. /// evalBind - Handle the semantics of binding a value to a specific location.
  1572. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  1573. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  1574. ExplodedNode *Pred,
  1575. SVal location, SVal Val,
  1576. bool atDeclInit, const ProgramPoint *PP) {
  1577. const LocationContext *LC = Pred->getLocationContext();
  1578. PostStmt PS(StoreE, LC);
  1579. if (!PP)
  1580. PP = &PS;
  1581. // Do a previsit of the bind.
  1582. ExplodedNodeSet CheckedSet;
  1583. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  1584. StoreE, *this, *PP);
  1585. StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
  1586. // If the location is not a 'Loc', it will already be handled by
  1587. // the checkers. There is nothing left to do.
  1588. if (!location.getAs<Loc>()) {
  1589. const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/0, /*tag*/0);
  1590. ProgramStateRef state = Pred->getState();
  1591. state = processPointerEscapedOnBind(state, location, Val);
  1592. Bldr.generateNode(L, state, Pred);
  1593. return;
  1594. }
  1595. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1596. I!=E; ++I) {
  1597. ExplodedNode *PredI = *I;
  1598. ProgramStateRef state = PredI->getState();
  1599. state = processPointerEscapedOnBind(state, location, Val);
  1600. // When binding the value, pass on the hint that this is a initialization.
  1601. // For initializations, we do not need to inform clients of region
  1602. // changes.
  1603. state = state->bindLoc(location.castAs<Loc>(),
  1604. Val, /* notifyChanges = */ !atDeclInit);
  1605. const MemRegion *LocReg = 0;
  1606. if (Optional<loc::MemRegionVal> LocRegVal =
  1607. location.getAs<loc::MemRegionVal>()) {
  1608. LocReg = LocRegVal->getRegion();
  1609. }
  1610. const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0);
  1611. Bldr.generateNode(L, state, PredI);
  1612. }
  1613. }
  1614. /// evalStore - Handle the semantics of a store via an assignment.
  1615. /// @param Dst The node set to store generated state nodes
  1616. /// @param AssignE The assignment expression if the store happens in an
  1617. /// assignment.
  1618. /// @param LocationE The location expression that is stored to.
  1619. /// @param state The current simulation state
  1620. /// @param location The location to store the value
  1621. /// @param Val The value to be stored
  1622. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  1623. const Expr *LocationE,
  1624. ExplodedNode *Pred,
  1625. ProgramStateRef state, SVal location, SVal Val,
  1626. const ProgramPointTag *tag) {
  1627. // Proceed with the store. We use AssignE as the anchor for the PostStore
  1628. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  1629. const Expr *StoreE = AssignE ? AssignE : LocationE;
  1630. // Evaluate the location (checks for bad dereferences).
  1631. ExplodedNodeSet Tmp;
  1632. evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
  1633. if (Tmp.empty())
  1634. return;
  1635. if (location.isUndef())
  1636. return;
  1637. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
  1638. evalBind(Dst, StoreE, *NI, location, Val, false);
  1639. }
  1640. void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
  1641. const Expr *NodeEx,
  1642. const Expr *BoundEx,
  1643. ExplodedNode *Pred,
  1644. ProgramStateRef state,
  1645. SVal location,
  1646. const ProgramPointTag *tag,
  1647. QualType LoadTy)
  1648. {
  1649. assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
  1650. // Are we loading from a region? This actually results in two loads; one
  1651. // to fetch the address of the referenced value and one to fetch the
  1652. // referenced value.
  1653. if (const TypedValueRegion *TR =
  1654. dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
  1655. QualType ValTy = TR->getValueType();
  1656. if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
  1657. static SimpleProgramPointTag
  1658. loadReferenceTag("ExprEngine : Load Reference");
  1659. ExplodedNodeSet Tmp;
  1660. evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
  1661. location, &loadReferenceTag,
  1662. getContext().getPointerType(RT->getPointeeType()));
  1663. // Perform the load from the referenced value.
  1664. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
  1665. state = (*I)->getState();
  1666. location = state->getSVal(BoundEx, (*I)->getLocationContext());
  1667. evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
  1668. }
  1669. return;
  1670. }
  1671. }
  1672. evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
  1673. }
  1674. void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
  1675. const Expr *NodeEx,
  1676. const Expr *BoundEx,
  1677. ExplodedNode *Pred,
  1678. ProgramStateRef state,
  1679. SVal location,
  1680. const ProgramPointTag *tag,
  1681. QualType LoadTy) {
  1682. assert(NodeEx);
  1683. assert(BoundEx);
  1684. // Evaluate the location (checks for bad dereferences).
  1685. ExplodedNodeSet Tmp;
  1686. evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
  1687. if (Tmp.empty())
  1688. return;
  1689. StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  1690. if (location.isUndef())
  1691. return;
  1692. // Proceed with the load.
  1693. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
  1694. state = (*NI)->getState();
  1695. const LocationContext *LCtx = (*NI)->getLocationContext();
  1696. SVal V = UnknownVal();
  1697. if (location.isValid()) {
  1698. if (LoadTy.isNull())
  1699. LoadTy = BoundEx->getType();
  1700. V = state->getSVal(location.castAs<Loc>(), LoadTy);
  1701. }
  1702. Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
  1703. ProgramPoint::PostLoadKind);
  1704. }
  1705. }
  1706. void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
  1707. const Stmt *NodeEx,
  1708. const Stmt *BoundEx,
  1709. ExplodedNode *Pred,
  1710. ProgramStateRef state,
  1711. SVal location,
  1712. const ProgramPointTag *tag,
  1713. bool isLoad) {
  1714. StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
  1715. // Early checks for performance reason.
  1716. if (location.isUnknown()) {
  1717. return;
  1718. }
  1719. ExplodedNodeSet Src;
  1720. BldrTop.takeNodes(Pred);
  1721. StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
  1722. if (Pred->getState() != state) {
  1723. // Associate this new state with an ExplodedNode.
  1724. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  1725. // int *p;
  1726. // p = 0;
  1727. // *p = 0xDEADBEEF;
  1728. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  1729. // instead "int *p" is noted as
  1730. // "Variable 'p' initialized to a null pointer value"
  1731. static SimpleProgramPointTag tag("ExprEngine: Location");
  1732. Bldr.generateNode(NodeEx, Pred, state, &tag);
  1733. }
  1734. ExplodedNodeSet Tmp;
  1735. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
  1736. NodeEx, BoundEx, *this);
  1737. BldrTop.addNodes(Tmp);
  1738. }
  1739. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  1740. ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
  1741. static SimpleProgramPointTag
  1742. eagerlyAssumeBinOpBifurcationTrue("ExprEngine : Eagerly Assume True"),
  1743. eagerlyAssumeBinOpBifurcationFalse("ExprEngine : Eagerly Assume False");
  1744. return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
  1745. &eagerlyAssumeBinOpBifurcationFalse);
  1746. }
  1747. void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
  1748. ExplodedNodeSet &Src,
  1749. const Expr *Ex) {
  1750. StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
  1751. for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
  1752. ExplodedNode *Pred = *I;
  1753. // Test if the previous node was as the same expression. This can happen
  1754. // when the expression fails to evaluate to anything meaningful and
  1755. // (as an optimization) we don't generate a node.
  1756. ProgramPoint P = Pred->getLocation();
  1757. if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
  1758. continue;
  1759. }
  1760. ProgramStateRef state = Pred->getState();
  1761. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  1762. Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
  1763. if (SEV && SEV->isExpression()) {
  1764. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  1765. geteagerlyAssumeBinOpBifurcationTags();
  1766. ProgramStateRef StateTrue, StateFalse;
  1767. tie(StateTrue, StateFalse) = state->assume(*SEV);
  1768. // First assume that the condition is true.
  1769. if (StateTrue) {
  1770. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  1771. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  1772. Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
  1773. }
  1774. // Next, assume that the condition is false.
  1775. if (StateFalse) {
  1776. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  1777. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  1778. Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
  1779. }
  1780. }
  1781. }
  1782. }
  1783. void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
  1784. ExplodedNodeSet &Dst) {
  1785. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  1786. // We have processed both the inputs and the outputs. All of the outputs
  1787. // should evaluate to Locs. Nuke all of their values.
  1788. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  1789. // which interprets the inline asm and stores proper results in the
  1790. // outputs.
  1791. ProgramStateRef state = Pred->getState();
  1792. for (GCCAsmStmt::const_outputs_iterator OI = A->begin_outputs(),
  1793. OE = A->end_outputs(); OI != OE; ++OI) {
  1794. SVal X = state->getSVal(*OI, Pred->getLocationContext());
  1795. assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
  1796. if (Optional<Loc> LV = X.getAs<Loc>())
  1797. state = state->bindLoc(*LV, UnknownVal());
  1798. }
  1799. Bldr.generateNode(A, Pred, state);
  1800. }
  1801. void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
  1802. ExplodedNodeSet &Dst) {
  1803. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  1804. Bldr.generateNode(A, Pred, Pred->getState());
  1805. }
  1806. //===----------------------------------------------------------------------===//
  1807. // Visualization.
  1808. //===----------------------------------------------------------------------===//
  1809. #ifndef NDEBUG
  1810. static ExprEngine* GraphPrintCheckerState;
  1811. static SourceManager* GraphPrintSourceManager;
  1812. namespace llvm {
  1813. template<>
  1814. struct DOTGraphTraits<ExplodedNode*> :
  1815. public DefaultDOTGraphTraits {
  1816. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  1817. // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
  1818. // work.
  1819. static std::string getNodeAttributes(const ExplodedNode *N, void*) {
  1820. #if 0
  1821. // FIXME: Replace with a general scheme to tell if the node is
  1822. // an error node.
  1823. if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
  1824. GraphPrintCheckerState->isExplicitNullDeref(N) ||
  1825. GraphPrintCheckerState->isUndefDeref(N) ||
  1826. GraphPrintCheckerState->isUndefStore(N) ||
  1827. GraphPrintCheckerState->isUndefControlFlow(N) ||
  1828. GraphPrintCheckerState->isUndefResult(N) ||
  1829. GraphPrintCheckerState->isBadCall(N) ||
  1830. GraphPrintCheckerState->isUndefArg(N))
  1831. return "color=\"red\",style=\"filled\"";
  1832. if (GraphPrintCheckerState->isNoReturnCall(N))
  1833. return "color=\"blue\",style=\"filled\"";
  1834. #endif
  1835. return "";
  1836. }
  1837. static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
  1838. if (SLoc.isFileID()) {
  1839. Out << "\\lline="
  1840. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  1841. << " col="
  1842. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
  1843. << "\\l";
  1844. }
  1845. }
  1846. static std::string getNodeLabel(const ExplodedNode *N, void*){
  1847. std::string sbuf;
  1848. llvm::raw_string_ostream Out(sbuf);
  1849. // Program Location.
  1850. ProgramPoint Loc = N->getLocation();
  1851. switch (Loc.getKind()) {
  1852. case ProgramPoint::BlockEntranceKind: {
  1853. Out << "Block Entrance: B"
  1854. << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
  1855. if (const NamedDecl *ND =
  1856. dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
  1857. Out << " (";
  1858. ND->printName(Out);
  1859. Out << ")";
  1860. }
  1861. break;
  1862. }
  1863. case ProgramPoint::BlockExitKind:
  1864. assert (false);
  1865. break;
  1866. case ProgramPoint::CallEnterKind:
  1867. Out << "CallEnter";
  1868. break;
  1869. case ProgramPoint::CallExitBeginKind:
  1870. Out << "CallExitBegin";
  1871. break;
  1872. case ProgramPoint::CallExitEndKind:
  1873. Out << "CallExitEnd";
  1874. break;
  1875. case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
  1876. Out << "PostStmtPurgeDeadSymbols";
  1877. break;
  1878. case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
  1879. Out << "PreStmtPurgeDeadSymbols";
  1880. break;
  1881. case ProgramPoint::EpsilonKind:
  1882. Out << "Epsilon Point";
  1883. break;
  1884. case ProgramPoint::PreImplicitCallKind: {
  1885. ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
  1886. Out << "PreCall: ";
  1887. // FIXME: Get proper printing options.
  1888. PC.getDecl()->print(Out, LangOptions());
  1889. printLocation(Out, PC.getLocation());
  1890. break;
  1891. }
  1892. case ProgramPoint::PostImplicitCallKind: {
  1893. ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
  1894. Out << "PostCall: ";
  1895. // FIXME: Get proper printing options.
  1896. PC.getDecl()->print(Out, LangOptions());
  1897. printLocation(Out, PC.getLocation());
  1898. break;
  1899. }
  1900. case ProgramPoint::PostInitializerKind: {
  1901. Out << "PostInitializer: ";
  1902. const CXXCtorInitializer *Init =
  1903. Loc.castAs<PostInitializer>().getInitializer();
  1904. if (const FieldDecl *FD = Init->getAnyMember())
  1905. Out << *FD;
  1906. else {
  1907. QualType Ty = Init->getTypeSourceInfo()->getType();
  1908. Ty = Ty.getLocalUnqualifiedType();
  1909. LangOptions LO; // FIXME.
  1910. Ty.print(Out, LO);
  1911. }
  1912. break;
  1913. }
  1914. case ProgramPoint::BlockEdgeKind: {
  1915. const BlockEdge &E = Loc.castAs<BlockEdge>();
  1916. Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
  1917. << E.getDst()->getBlockID() << ')';
  1918. if (const Stmt *T = E.getSrc()->getTerminator()) {
  1919. SourceLocation SLoc = T->getLocStart();
  1920. Out << "\\|Terminator: ";
  1921. LangOptions LO; // FIXME.
  1922. E.getSrc()->printTerminator(Out, LO);
  1923. if (SLoc.isFileID()) {
  1924. Out << "\\lline="
  1925. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  1926. << " col="
  1927. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
  1928. }
  1929. if (isa<SwitchStmt>(T)) {
  1930. const Stmt *Label = E.getDst()->getLabel();
  1931. if (Label) {
  1932. if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
  1933. Out << "\\lcase ";
  1934. LangOptions LO; // FIXME.
  1935. C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
  1936. if (const Stmt *RHS = C->getRHS()) {
  1937. Out << " .. ";
  1938. RHS->printPretty(Out, 0, PrintingPolicy(LO));
  1939. }
  1940. Out << ":";
  1941. }
  1942. else {
  1943. assert (isa<DefaultStmt>(Label));
  1944. Out << "\\ldefault:";
  1945. }
  1946. }
  1947. else
  1948. Out << "\\l(implicit) default:";
  1949. }
  1950. else if (isa<IndirectGotoStmt>(T)) {
  1951. // FIXME
  1952. }
  1953. else {
  1954. Out << "\\lCondition: ";
  1955. if (*E.getSrc()->succ_begin() == E.getDst())
  1956. Out << "true";
  1957. else
  1958. Out << "false";
  1959. }
  1960. Out << "\\l";
  1961. }
  1962. #if 0
  1963. // FIXME: Replace with a general scheme to determine
  1964. // the name of the check.
  1965. if (GraphPrintCheckerState->isUndefControlFlow(N)) {
  1966. Out << "\\|Control-flow based on\\lUndefined value.\\l";
  1967. }
  1968. #endif
  1969. break;
  1970. }
  1971. default: {
  1972. const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
  1973. Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
  1974. LangOptions LO; // FIXME.
  1975. S->printPretty(Out, 0, PrintingPolicy(LO));
  1976. printLocation(Out, S->getLocStart());
  1977. if (Loc.getAs<PreStmt>())
  1978. Out << "\\lPreStmt\\l;";
  1979. else if (Loc.getAs<PostLoad>())
  1980. Out << "\\lPostLoad\\l;";
  1981. else if (Loc.getAs<PostStore>())
  1982. Out << "\\lPostStore\\l";
  1983. else if (Loc.getAs<PostLValue>())
  1984. Out << "\\lPostLValue\\l";
  1985. #if 0
  1986. // FIXME: Replace with a general scheme to determine
  1987. // the name of the check.
  1988. if (GraphPrintCheckerState->isImplicitNullDeref(N))
  1989. Out << "\\|Implicit-Null Dereference.\\l";
  1990. else if (GraphPrintCheckerState->isExplicitNullDeref(N))
  1991. Out << "\\|Explicit-Null Dereference.\\l";
  1992. else if (GraphPrintCheckerState->isUndefDeref(N))
  1993. Out << "\\|Dereference of undefialied value.\\l";
  1994. else if (GraphPrintCheckerState->isUndefStore(N))
  1995. Out << "\\|Store to Undefined Loc.";
  1996. else if (GraphPrintCheckerState->isUndefResult(N))
  1997. Out << "\\|Result of operation is undefined.";
  1998. else if (GraphPrintCheckerState->isNoReturnCall(N))
  1999. Out << "\\|Call to function marked \"noreturn\".";
  2000. else if (GraphPrintCheckerState->isBadCall(N))
  2001. Out << "\\|Call to NULL/Undefined.";
  2002. else if (GraphPrintCheckerState->isUndefArg(N))
  2003. Out << "\\|Argument in call is undefined";
  2004. #endif
  2005. break;
  2006. }
  2007. }
  2008. ProgramStateRef state = N->getState();
  2009. Out << "\\|StateID: " << (const void*) state.getPtr()
  2010. << " NodeID: " << (const void*) N << "\\|";
  2011. state->printDOT(Out);
  2012. Out << "\\l";
  2013. if (const ProgramPointTag *tag = Loc.getTag()) {
  2014. Out << "\\|Tag: " << tag->getTagDescription();
  2015. Out << "\\l";
  2016. }
  2017. return Out.str();
  2018. }
  2019. };
  2020. } // end llvm namespace
  2021. #endif
  2022. #ifndef NDEBUG
  2023. template <typename ITERATOR>
  2024. ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
  2025. template <> ExplodedNode*
  2026. GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
  2027. (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
  2028. return I->first;
  2029. }
  2030. #endif
  2031. void ExprEngine::ViewGraph(bool trim) {
  2032. #ifndef NDEBUG
  2033. if (trim) {
  2034. std::vector<const ExplodedNode*> Src;
  2035. // Flush any outstanding reports to make sure we cover all the nodes.
  2036. // This does not cause them to get displayed.
  2037. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
  2038. const_cast<BugType*>(*I)->FlushReports(BR);
  2039. // Iterate through the reports and get their nodes.
  2040. for (BugReporter::EQClasses_iterator
  2041. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  2042. ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
  2043. if (N) Src.push_back(N);
  2044. }
  2045. ViewGraph(Src);
  2046. }
  2047. else {
  2048. GraphPrintCheckerState = this;
  2049. GraphPrintSourceManager = &getContext().getSourceManager();
  2050. llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
  2051. GraphPrintCheckerState = NULL;
  2052. GraphPrintSourceManager = NULL;
  2053. }
  2054. #endif
  2055. }
  2056. void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
  2057. #ifndef NDEBUG
  2058. GraphPrintCheckerState = this;
  2059. GraphPrintSourceManager = &getContext().getSourceManager();
  2060. OwningPtr<ExplodedGraph> TrimmedG(G.trim(Nodes));
  2061. if (!TrimmedG.get())
  2062. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  2063. else
  2064. llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
  2065. GraphPrintCheckerState = NULL;
  2066. GraphPrintSourceManager = NULL;
  2067. #endif
  2068. }